From 6d5029895a54fcddbc3aa1bf1892bbdb5d92249e Mon Sep 17 00:00:00 2001 From: Craig Day Date: Fri, 27 Mar 2020 15:44:54 -0700 Subject: [PATCH] initial pass at extracting the action to standalone --- README.md | 132 + action.js | 52 + action.yml | 19 + node_modules/.bin/gp12-pem | 1 + node_modules/.bin/mime | 1 + node_modules/@actions/core/README.md | 146 + node_modules/@actions/core/lib/command.d.ts | 16 + node_modules/@actions/core/lib/command.js | 78 + node_modules/@actions/core/lib/command.js.map | 1 + node_modules/@actions/core/lib/core.d.ts | 116 + node_modules/@actions/core/lib/core.js | 209 + node_modules/@actions/core/lib/core.js.map | 1 + node_modules/@actions/core/package.json | 67 + node_modules/abort-controller/LICENSE | 21 + node_modules/abort-controller/README.md | 98 + node_modules/abort-controller/browser.js | 13 + node_modules/abort-controller/browser.mjs | 11 + .../dist/abort-controller.d.ts | 43 + .../abort-controller/dist/abort-controller.js | 127 + .../dist/abort-controller.js.map | 1 + .../dist/abort-controller.mjs | 118 + .../dist/abort-controller.mjs.map | 1 + .../dist/abort-controller.umd.js | 5 + .../dist/abort-controller.umd.js.map | 1 + node_modules/abort-controller/package.json | 127 + node_modules/abort-controller/polyfill.js | 21 + node_modules/abort-controller/polyfill.mjs | 19 + node_modules/agent-base/README.md | 145 + node_modules/agent-base/dist/src/index.d.ts | 73 + node_modules/agent-base/dist/src/index.js | 200 + node_modules/agent-base/dist/src/index.js.map | 1 + .../agent-base/dist/src/promisify.d.ts | 4 + node_modules/agent-base/dist/src/promisify.js | 18 + .../agent-base/dist/src/promisify.js.map | 1 + node_modules/agent-base/package.json | 91 + node_modules/arrify/index.d.ts | 38 + node_modules/arrify/index.js | 23 + node_modules/arrify/license | 9 + node_modules/arrify/package.json | 67 + node_modules/arrify/readme.md | 39 + node_modules/base64-js/LICENSE | 21 + node_modules/base64-js/README.md | 32 + node_modules/base64-js/base64js.min.js | 1 + node_modules/base64-js/index.js | 152 + node_modules/base64-js/package.json | 60 + node_modules/bignumber.js/CHANGELOG.md | 222 + node_modules/bignumber.js/LICENCE | 23 + node_modules/bignumber.js/README.md | 266 + node_modules/bignumber.js/bignumber.d.ts | 1797 +++++++ node_modules/bignumber.js/bignumber.js | 2814 +++++++++++ node_modules/bignumber.js/bignumber.js.map | 1 + node_modules/bignumber.js/bignumber.min.js | 3 + node_modules/bignumber.js/bignumber.mjs | 2793 +++++++++++ node_modules/bignumber.js/bower.json | 36 + node_modules/bignumber.js/doc/API.html | 2118 ++++++++ node_modules/bignumber.js/package.json | 68 + .../buffer-equal-constant-time/.npmignore | 2 + .../buffer-equal-constant-time/.travis.yml | 4 + .../buffer-equal-constant-time/LICENSE.txt | 12 + .../buffer-equal-constant-time/README.md | 50 + .../buffer-equal-constant-time/index.js | 41 + .../buffer-equal-constant-time/package.json | 55 + .../buffer-equal-constant-time/test.js | 42 + node_modules/debug/CHANGELOG.md | 395 ++ node_modules/debug/LICENSE | 19 + node_modules/debug/README.md | 455 ++ node_modules/debug/dist/debug.js | 912 ++++ node_modules/debug/package.json | 103 + node_modules/debug/src/browser.js | 264 + node_modules/debug/src/common.js | 266 + node_modules/debug/src/index.js | 10 + node_modules/debug/src/node.js | 257 + node_modules/ecdsa-sig-formatter/CODEOWNERS | 1 + node_modules/ecdsa-sig-formatter/LICENSE | 201 + node_modules/ecdsa-sig-formatter/README.md | 65 + node_modules/ecdsa-sig-formatter/package.json | 74 + .../src/ecdsa-sig-formatter.d.ts | 17 + .../src/ecdsa-sig-formatter.js | 187 + .../src/param-bytes-for-alg.js | 23 + node_modules/event-target-shim/LICENSE | 22 + node_modules/event-target-shim/README.md | 293 ++ .../dist/event-target-shim.js | 871 ++++ .../dist/event-target-shim.js.map | 1 + .../dist/event-target-shim.mjs | 862 ++++ .../dist/event-target-shim.mjs.map | 1 + .../dist/event-target-shim.umd.js | 6 + .../dist/event-target-shim.umd.js.map | 1 + node_modules/event-target-shim/index.d.ts | 399 ++ node_modules/event-target-shim/package.json | 109 + node_modules/extend/.editorconfig | 20 + node_modules/extend/.eslintrc | 17 + node_modules/extend/.jscs.json | 175 + node_modules/extend/.travis.yml | 230 + node_modules/extend/CHANGELOG.md | 83 + node_modules/extend/LICENSE | 23 + node_modules/extend/README.md | 81 + node_modules/extend/component.json | 32 + node_modules/extend/index.js | 117 + node_modules/extend/package.json | 77 + node_modules/fast-text-encoding/LICENSE | 201 + node_modules/fast-text-encoding/README.md | 54 + node_modules/fast-text-encoding/package.json | 48 + node_modules/fast-text-encoding/suite.js | 108 + node_modules/fast-text-encoding/test.html | 115 + node_modules/fast-text-encoding/text.js | 210 + node_modules/fast-text-encoding/text.min.js | 5 + node_modules/gaxios/CHANGELOG.md | 114 + node_modules/gaxios/LICENSE | 202 + node_modules/gaxios/README.md | 138 + node_modules/gaxios/build/src/common.d.ts | 104 + node_modules/gaxios/build/src/common.js | 25 + node_modules/gaxios/build/src/common.js.map | 1 + node_modules/gaxios/build/src/gaxios.d.ts | 40 + node_modules/gaxios/build/src/gaxios.js | 227 + node_modules/gaxios/build/src/gaxios.js.map | 1 + node_modules/gaxios/build/src/index.d.ts | 14 + node_modules/gaxios/build/src/index.js | 32 + node_modules/gaxios/build/src/index.js.map | 1 + node_modules/gaxios/build/src/retry.d.ts | 8 + node_modules/gaxios/build/src/retry.js | 132 + node_modules/gaxios/build/src/retry.js.map | 1 + node_modules/gaxios/package.json | 129 + node_modules/gcp-metadata/CHANGELOG.md | 315 ++ node_modules/gcp-metadata/LICENSE | 202 + node_modules/gcp-metadata/README.md | 65 + .../gcp-metadata/build/src/index.d.ts | 33 + node_modules/gcp-metadata/build/src/index.js | 217 + .../gcp-metadata/build/src/index.js.map | 1 + .../node_modules/gaxios/CHANGELOG.md | 87 + .../gcp-metadata/node_modules/gaxios/LICENSE | 202 + .../node_modules/gaxios/README.md | 138 + .../node_modules/gaxios/build/src/common.d.ts | 104 + .../node_modules/gaxios/build/src/common.js | 25 + .../gaxios/build/src/common.js.map | 1 + .../node_modules/gaxios/build/src/gaxios.d.ts | 40 + .../node_modules/gaxios/build/src/gaxios.js | 224 + .../gaxios/build/src/gaxios.js.map | 1 + .../node_modules/gaxios/build/src/index.d.ts | 14 + .../node_modules/gaxios/build/src/index.js | 32 + .../gaxios/build/src/index.js.map | 1 + .../node_modules/gaxios/build/src/retry.d.ts | 8 + .../node_modules/gaxios/build/src/retry.js | 132 + .../gaxios/build/src/retry.js.map | 1 + .../node_modules/gaxios/build/src/web.d.ts | 0 .../node_modules/gaxios/build/src/web.js | 2 + .../node_modules/gaxios/build/src/web.js.map | 1 + .../node_modules/gaxios/package.json | 130 + node_modules/gcp-metadata/package.json | 120 + node_modules/google-auth-library/CHANGELOG.md | 610 +++ node_modules/google-auth-library/LICENSE | 202 + node_modules/google-auth-library/README.md | 442 ++ .../build/src/auth/authclient.d.ts | 31 + .../build/src/auth/authclient.js | 50 + .../build/src/auth/computeclient.d.ts | 37 + .../build/src/auth/computeclient.js | 107 + .../build/src/auth/credentials.d.ts | 29 + .../build/src/auth/credentials.js | 16 + .../build/src/auth/envDetect.d.ts | 9 + .../build/src/auth/envDetect.js | 77 + .../build/src/auth/googleauth.d.ts | 243 + .../build/src/auth/googleauth.js | 583 +++ .../build/src/auth/iam.d.ts | 23 + .../google-auth-library/build/src/auth/iam.js | 41 + .../build/src/auth/idtokenclient.d.ts | 27 + .../build/src/auth/idtokenclient.js | 52 + .../build/src/auth/jwtaccess.d.ts | 47 + .../build/src/auth/jwtaccess.js | 135 + .../build/src/auth/jwtclient.d.ts | 103 + .../build/src/auth/jwtclient.js | 251 + .../build/src/auth/loginticket.d.ts | 135 + .../build/src/auth/loginticket.js | 57 + .../build/src/auth/oauth2client.d.ts | 502 ++ .../build/src/auth/oauth2client.js | 674 +++ .../build/src/auth/refreshclient.d.ts | 43 + .../build/src/auth/refreshclient.js | 104 + .../build/src/crypto/browser/crypto.d.ts | 11 + .../build/src/crypto/browser/crypto.js | 99 + .../build/src/crypto/crypto.d.ts | 23 + .../build/src/crypto/crypto.js | 32 + .../build/src/crypto/node/crypto.d.ts | 10 + .../build/src/crypto/node/crypto.js | 44 + .../google-auth-library/build/src/index.d.ts | 15 + .../google-auth-library/build/src/index.js | 41 + .../build/src/messages.d.ts | 11 + .../google-auth-library/build/src/messages.js | 39 + .../build/src/options.d.ts | 1 + .../google-auth-library/build/src/options.js | 35 + .../build/src/transporters.d.ts | 36 + .../build/src/transporters.js | 115 + node_modules/google-auth-library/package.json | 146 + node_modules/google-p12-pem/CHANGELOG.md | 149 + node_modules/google-p12-pem/LICENSE | 21 + node_modules/google-p12-pem/README.md | 121 + .../build/src/bin/gp12-pem.d.ts | 8 + .../google-p12-pem/build/src/bin/gp12-pem.js | 26 + .../google-p12-pem/build/src/index.d.ts | 15 + .../google-p12-pem/build/src/index.js | 48 + node_modules/google-p12-pem/package.json | 104 + node_modules/gtoken/CHANGELOG.md | 223 + node_modules/gtoken/LICENSE | 21 + node_modules/gtoken/README.md | 182 + node_modules/gtoken/build/src/index.d.ts | 90 + node_modules/gtoken/build/src/index.js | 234 + .../gtoken/node_modules/gaxios/CHANGELOG.md | 87 + .../gtoken/node_modules/gaxios/LICENSE | 202 + .../gtoken/node_modules/gaxios/README.md | 138 + .../node_modules/gaxios/build/src/common.d.ts | 104 + .../node_modules/gaxios/build/src/common.js | 25 + .../gaxios/build/src/common.js.map | 1 + .../node_modules/gaxios/build/src/gaxios.d.ts | 40 + .../node_modules/gaxios/build/src/gaxios.js | 224 + .../gaxios/build/src/gaxios.js.map | 1 + .../node_modules/gaxios/build/src/index.d.ts | 14 + .../node_modules/gaxios/build/src/index.js | 32 + .../gaxios/build/src/index.js.map | 1 + .../node_modules/gaxios/build/src/retry.d.ts | 8 + .../node_modules/gaxios/build/src/retry.js | 132 + .../gaxios/build/src/retry.js.map | 1 + .../node_modules/gaxios/build/src/web.d.ts | 0 .../node_modules/gaxios/build/src/web.js | 2 + .../node_modules/gaxios/build/src/web.js.map | 1 + .../gtoken/node_modules/gaxios/package.json | 130 + node_modules/gtoken/package.json | 113 + node_modules/https-proxy-agent/README.md | 137 + .../https-proxy-agent/dist/agent.d.ts | 30 + node_modules/https-proxy-agent/dist/agent.js | 180 + .../https-proxy-agent/dist/agent.js.map | 1 + .../https-proxy-agent/dist/index.d.ts | 23 + node_modules/https-proxy-agent/dist/index.js | 14 + .../https-proxy-agent/dist/index.js.map | 1 + .../dist/parse-proxy-response.d.ts | 7 + .../dist/parse-proxy-response.js | 66 + .../dist/parse-proxy-response.js.map | 1 + node_modules/https-proxy-agent/package.json | 88 + node_modules/is-stream/index.d.ts | 80 + node_modules/is-stream/index.js | 29 + node_modules/is-stream/license | 9 + node_modules/is-stream/package.json | 75 + node_modules/is-stream/readme.md | 57 + node_modules/json-bigint/.npmignore | 16 + node_modules/json-bigint/.travis.yml | 4 + node_modules/json-bigint/LICENSE | 20 + node_modules/json-bigint/README.md | 117 + node_modules/json-bigint/index.js | 12 + node_modules/json-bigint/lib/parse.js | 384 ++ node_modules/json-bigint/lib/stringify.js | 383 ++ node_modules/json-bigint/package.json | 61 + node_modules/json-bigint/test/bigint-test.js | 31 + .../json-bigint/test/strict-option-test.js | 34 + .../json-bigint/test/string-option-test.js | 21 + node_modules/jwa/LICENSE | 17 + node_modules/jwa/README.md | 150 + node_modules/jwa/index.js | 252 + node_modules/jwa/package.json | 69 + node_modules/jws/CHANGELOG.md | 34 + node_modules/jws/LICENSE | 17 + node_modules/jws/index.js | 22 + node_modules/jws/lib/data-stream.js | 55 + node_modules/jws/lib/sign-stream.js | 78 + node_modules/jws/lib/tostring.js | 10 + node_modules/jws/lib/verify-stream.js | 120 + node_modules/jws/package.json | 65 + node_modules/jws/readme.md | 255 + node_modules/lru-cache/LICENSE | 15 + node_modules/lru-cache/README.md | 166 + node_modules/lru-cache/index.js | 334 ++ node_modules/lru-cache/package.json | 67 + node_modules/mime/.eslintrc.json | 51 + node_modules/mime/.github/ISSUE_TEMPLATE.md | 6 + .../mime/.github/PULL_REQUEST_TEMPLATE.md | 6 + node_modules/mime/.travis.yml | 5 + node_modules/mime/CHANGELOG.md | 262 + node_modules/mime/CONTRIBUTING.md | 5 + node_modules/mime/LICENSE | 21 + node_modules/mime/Mime.js | 95 + node_modules/mime/README.md | 193 + node_modules/mime/cli.js | 10 + node_modules/mime/index.js | 4 + node_modules/mime/lite.js | 4 + node_modules/mime/package.json | 74 + node_modules/mime/src/README_js.md | 184 + node_modules/mime/src/benchmark.js | 26 + node_modules/mime/src/build.js | 71 + node_modules/mime/src/test.js | 256 + node_modules/mime/types/other.js | 1 + node_modules/mime/types/standard.js | 1 + node_modules/ms/index.js | 162 + node_modules/ms/license.md | 21 + node_modules/ms/package.json | 69 + node_modules/ms/readme.md | 60 + node_modules/node-fetch/CHANGELOG.md | 266 + node_modules/node-fetch/LICENSE.md | 22 + node_modules/node-fetch/README.md | 583 +++ node_modules/node-fetch/browser.js | 23 + node_modules/node-fetch/lib/index.es.js | 1633 +++++++ node_modules/node-fetch/lib/index.js | 1642 +++++++ node_modules/node-fetch/lib/index.mjs | 1631 +++++++ node_modules/node-fetch/package.json | 95 + node_modules/node-forge/CHANGELOG.md | 225 + node_modules/node-forge/LICENSE | 331 ++ node_modules/node-forge/README.md | 2099 ++++++++ node_modules/node-forge/dist/forge.all.min.js | 2 + .../node-forge/dist/forge.all.min.js.map | 1 + node_modules/node-forge/dist/forge.min.js | 2 + node_modules/node-forge/dist/forge.min.js.map | 1 + .../node-forge/dist/prime.worker.min.js | 2 + .../node-forge/dist/prime.worker.min.js.map | 1 + node_modules/node-forge/flash/README.md | 48 + node_modules/node-forge/flash/package.json | 28 + .../node-forge/flash/swf/SocketPool.swf | Bin 0 -> 21162 bytes node_modules/node-forge/lib/aes.js | 1091 +++++ .../node-forge/lib/aesCipherSuites.js | 282 ++ node_modules/node-forge/lib/asn1-validator.js | 91 + node_modules/node-forge/lib/asn1.js | 1408 ++++++ node_modules/node-forge/lib/baseN.js | 186 + node_modules/node-forge/lib/cipher.js | 230 + node_modules/node-forge/lib/cipherModes.js | 999 ++++ node_modules/node-forge/lib/debug.js | 78 + node_modules/node-forge/lib/des.js | 496 ++ node_modules/node-forge/lib/ed25519.js | 1072 +++++ node_modules/node-forge/lib/forge.js | 13 + node_modules/node-forge/lib/form.js | 149 + node_modules/node-forge/lib/hmac.js | 146 + node_modules/node-forge/lib/http.js | 1364 ++++++ node_modules/node-forge/lib/index.all.js | 16 + node_modules/node-forge/lib/index.js | 35 + node_modules/node-forge/lib/jsbn.js | 1264 +++++ node_modules/node-forge/lib/kem.js | 168 + node_modules/node-forge/lib/log.js | 317 ++ node_modules/node-forge/lib/md.all.js | 13 + node_modules/node-forge/lib/md.js | 11 + node_modules/node-forge/lib/md5.js | 289 ++ node_modules/node-forge/lib/mgf.js | 12 + node_modules/node-forge/lib/mgf1.js | 57 + node_modules/node-forge/lib/oids.js | 170 + node_modules/node-forge/lib/pbe.js | 1023 ++++ node_modules/node-forge/lib/pbkdf2.js | 211 + node_modules/node-forge/lib/pem.js | 230 + node_modules/node-forge/lib/pkcs1.js | 276 ++ node_modules/node-forge/lib/pkcs12.js | 1074 +++++ node_modules/node-forge/lib/pkcs7.js | 1257 +++++ node_modules/node-forge/lib/pkcs7asn1.js | 409 ++ node_modules/node-forge/lib/pki.js | 102 + node_modules/node-forge/lib/prime.js | 297 ++ node_modules/node-forge/lib/prime.worker.js | 168 + node_modules/node-forge/lib/prng.js | 419 ++ node_modules/node-forge/lib/pss.js | 241 + node_modules/node-forge/lib/random.js | 191 + node_modules/node-forge/lib/rc2.js | 410 ++ node_modules/node-forge/lib/rsa.js | 1858 +++++++ node_modules/node-forge/lib/sha1.js | 319 ++ node_modules/node-forge/lib/sha256.js | 327 ++ node_modules/node-forge/lib/sha512.js | 561 +++ node_modules/node-forge/lib/socket.js | 287 ++ node_modules/node-forge/lib/ssh.js | 236 + node_modules/node-forge/lib/task.js | 725 +++ node_modules/node-forge/lib/tls.js | 4282 +++++++++++++++++ node_modules/node-forge/lib/tlssocket.js | 249 + node_modules/node-forge/lib/util.js | 3000 ++++++++++++ node_modules/node-forge/lib/x509.js | 3333 +++++++++++++ node_modules/node-forge/lib/xhr.js | 736 +++ node_modules/node-forge/package.json | 157 + node_modules/safe-buffer/LICENSE | 21 + node_modules/safe-buffer/README.md | 586 +++ node_modules/safe-buffer/index.d.ts | 187 + node_modules/safe-buffer/index.js | 64 + node_modules/safe-buffer/package.json | 64 + node_modules/yallist/LICENSE | 15 + node_modules/yallist/README.md | 204 + node_modules/yallist/iterator.js | 8 + node_modules/yallist/package.json | 62 + node_modules/yallist/yallist.js | 426 ++ package-lock.json | 243 + package.json | 23 + 374 files changed, 79295 insertions(+) create mode 100644 README.md create mode 100644 action.js create mode 100644 action.yml create mode 120000 node_modules/.bin/gp12-pem create mode 120000 node_modules/.bin/mime create mode 100644 node_modules/@actions/core/README.md create mode 100644 node_modules/@actions/core/lib/command.d.ts create mode 100644 node_modules/@actions/core/lib/command.js create mode 100644 node_modules/@actions/core/lib/command.js.map create mode 100644 node_modules/@actions/core/lib/core.d.ts create mode 100644 node_modules/@actions/core/lib/core.js create mode 100644 node_modules/@actions/core/lib/core.js.map create mode 100644 node_modules/@actions/core/package.json create mode 100644 node_modules/abort-controller/LICENSE create mode 100644 node_modules/abort-controller/README.md create mode 100644 node_modules/abort-controller/browser.js create mode 100644 node_modules/abort-controller/browser.mjs create mode 100644 node_modules/abort-controller/dist/abort-controller.d.ts create mode 100644 node_modules/abort-controller/dist/abort-controller.js create mode 100644 node_modules/abort-controller/dist/abort-controller.js.map create mode 100644 node_modules/abort-controller/dist/abort-controller.mjs create mode 100644 node_modules/abort-controller/dist/abort-controller.mjs.map create mode 100644 node_modules/abort-controller/dist/abort-controller.umd.js create mode 100644 node_modules/abort-controller/dist/abort-controller.umd.js.map create mode 100644 node_modules/abort-controller/package.json create mode 100644 node_modules/abort-controller/polyfill.js create mode 100644 node_modules/abort-controller/polyfill.mjs create mode 100644 node_modules/agent-base/README.md create mode 100644 node_modules/agent-base/dist/src/index.d.ts create mode 100644 node_modules/agent-base/dist/src/index.js create mode 100644 node_modules/agent-base/dist/src/index.js.map create mode 100644 node_modules/agent-base/dist/src/promisify.d.ts create mode 100644 node_modules/agent-base/dist/src/promisify.js create mode 100644 node_modules/agent-base/dist/src/promisify.js.map create mode 100644 node_modules/agent-base/package.json create mode 100644 node_modules/arrify/index.d.ts create mode 100644 node_modules/arrify/index.js create mode 100644 node_modules/arrify/license create mode 100644 node_modules/arrify/package.json create mode 100644 node_modules/arrify/readme.md create mode 100644 node_modules/base64-js/LICENSE create mode 100644 node_modules/base64-js/README.md create mode 100644 node_modules/base64-js/base64js.min.js create mode 100644 node_modules/base64-js/index.js create mode 100644 node_modules/base64-js/package.json create mode 100644 node_modules/bignumber.js/CHANGELOG.md create mode 100644 node_modules/bignumber.js/LICENCE create mode 100644 node_modules/bignumber.js/README.md create mode 100644 node_modules/bignumber.js/bignumber.d.ts create mode 100644 node_modules/bignumber.js/bignumber.js create mode 100644 node_modules/bignumber.js/bignumber.js.map create mode 100644 node_modules/bignumber.js/bignumber.min.js create mode 100644 node_modules/bignumber.js/bignumber.mjs create mode 100644 node_modules/bignumber.js/bower.json create mode 100644 node_modules/bignumber.js/doc/API.html create mode 100644 node_modules/bignumber.js/package.json create mode 100644 node_modules/buffer-equal-constant-time/.npmignore create mode 100644 node_modules/buffer-equal-constant-time/.travis.yml create mode 100644 node_modules/buffer-equal-constant-time/LICENSE.txt create mode 100644 node_modules/buffer-equal-constant-time/README.md create mode 100644 node_modules/buffer-equal-constant-time/index.js create mode 100644 node_modules/buffer-equal-constant-time/package.json create mode 100644 node_modules/buffer-equal-constant-time/test.js create mode 100644 node_modules/debug/CHANGELOG.md create mode 100644 node_modules/debug/LICENSE create mode 100644 node_modules/debug/README.md create mode 100644 node_modules/debug/dist/debug.js create mode 100644 node_modules/debug/package.json create mode 100644 node_modules/debug/src/browser.js create mode 100644 node_modules/debug/src/common.js create mode 100644 node_modules/debug/src/index.js create mode 100644 node_modules/debug/src/node.js create mode 100644 node_modules/ecdsa-sig-formatter/CODEOWNERS create mode 100644 node_modules/ecdsa-sig-formatter/LICENSE create mode 100644 node_modules/ecdsa-sig-formatter/README.md create mode 100644 node_modules/ecdsa-sig-formatter/package.json create mode 100644 node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.d.ts create mode 100644 node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js create mode 100644 node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js create mode 100644 node_modules/event-target-shim/LICENSE create mode 100644 node_modules/event-target-shim/README.md create mode 100644 node_modules/event-target-shim/dist/event-target-shim.js create mode 100644 node_modules/event-target-shim/dist/event-target-shim.js.map create mode 100644 node_modules/event-target-shim/dist/event-target-shim.mjs create mode 100644 node_modules/event-target-shim/dist/event-target-shim.mjs.map create mode 100644 node_modules/event-target-shim/dist/event-target-shim.umd.js create mode 100644 node_modules/event-target-shim/dist/event-target-shim.umd.js.map create mode 100644 node_modules/event-target-shim/index.d.ts create mode 100644 node_modules/event-target-shim/package.json create mode 100644 node_modules/extend/.editorconfig create mode 100644 node_modules/extend/.eslintrc create mode 100644 node_modules/extend/.jscs.json create mode 100644 node_modules/extend/.travis.yml create mode 100644 node_modules/extend/CHANGELOG.md create mode 100644 node_modules/extend/LICENSE create mode 100644 node_modules/extend/README.md create mode 100644 node_modules/extend/component.json create mode 100644 node_modules/extend/index.js create mode 100644 node_modules/extend/package.json create mode 100644 node_modules/fast-text-encoding/LICENSE create mode 100644 node_modules/fast-text-encoding/README.md create mode 100644 node_modules/fast-text-encoding/package.json create mode 100644 node_modules/fast-text-encoding/suite.js create mode 100644 node_modules/fast-text-encoding/test.html create mode 100644 node_modules/fast-text-encoding/text.js create mode 100644 node_modules/fast-text-encoding/text.min.js create mode 100644 node_modules/gaxios/CHANGELOG.md create mode 100644 node_modules/gaxios/LICENSE create mode 100644 node_modules/gaxios/README.md create mode 100644 node_modules/gaxios/build/src/common.d.ts create mode 100644 node_modules/gaxios/build/src/common.js create mode 100644 node_modules/gaxios/build/src/common.js.map create mode 100644 node_modules/gaxios/build/src/gaxios.d.ts create mode 100644 node_modules/gaxios/build/src/gaxios.js create mode 100644 node_modules/gaxios/build/src/gaxios.js.map create mode 100644 node_modules/gaxios/build/src/index.d.ts create mode 100644 node_modules/gaxios/build/src/index.js create mode 100644 node_modules/gaxios/build/src/index.js.map create mode 100644 node_modules/gaxios/build/src/retry.d.ts create mode 100644 node_modules/gaxios/build/src/retry.js create mode 100644 node_modules/gaxios/build/src/retry.js.map create mode 100644 node_modules/gaxios/package.json create mode 100644 node_modules/gcp-metadata/CHANGELOG.md create mode 100644 node_modules/gcp-metadata/LICENSE create mode 100644 node_modules/gcp-metadata/README.md create mode 100644 node_modules/gcp-metadata/build/src/index.d.ts create mode 100644 node_modules/gcp-metadata/build/src/index.js create mode 100644 node_modules/gcp-metadata/build/src/index.js.map create mode 100644 node_modules/gcp-metadata/node_modules/gaxios/CHANGELOG.md create mode 100644 node_modules/gcp-metadata/node_modules/gaxios/LICENSE create mode 100644 node_modules/gcp-metadata/node_modules/gaxios/README.md create mode 100644 node_modules/gcp-metadata/node_modules/gaxios/build/src/common.d.ts create mode 100644 node_modules/gcp-metadata/node_modules/gaxios/build/src/common.js create mode 100644 node_modules/gcp-metadata/node_modules/gaxios/build/src/common.js.map create mode 100644 node_modules/gcp-metadata/node_modules/gaxios/build/src/gaxios.d.ts create mode 100644 node_modules/gcp-metadata/node_modules/gaxios/build/src/gaxios.js create mode 100644 node_modules/gcp-metadata/node_modules/gaxios/build/src/gaxios.js.map create mode 100644 node_modules/gcp-metadata/node_modules/gaxios/build/src/index.d.ts create mode 100644 node_modules/gcp-metadata/node_modules/gaxios/build/src/index.js create mode 100644 node_modules/gcp-metadata/node_modules/gaxios/build/src/index.js.map create mode 100644 node_modules/gcp-metadata/node_modules/gaxios/build/src/retry.d.ts create mode 100644 node_modules/gcp-metadata/node_modules/gaxios/build/src/retry.js create mode 100644 node_modules/gcp-metadata/node_modules/gaxios/build/src/retry.js.map create mode 100644 node_modules/gcp-metadata/node_modules/gaxios/build/src/web.d.ts create mode 100644 node_modules/gcp-metadata/node_modules/gaxios/build/src/web.js create mode 100644 node_modules/gcp-metadata/node_modules/gaxios/build/src/web.js.map create mode 100644 node_modules/gcp-metadata/node_modules/gaxios/package.json create mode 100644 node_modules/gcp-metadata/package.json create mode 100644 node_modules/google-auth-library/CHANGELOG.md create mode 100644 node_modules/google-auth-library/LICENSE create mode 100644 node_modules/google-auth-library/README.md create mode 100644 node_modules/google-auth-library/build/src/auth/authclient.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/authclient.js create mode 100644 node_modules/google-auth-library/build/src/auth/computeclient.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/computeclient.js create mode 100644 node_modules/google-auth-library/build/src/auth/credentials.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/credentials.js create mode 100644 node_modules/google-auth-library/build/src/auth/envDetect.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/envDetect.js create mode 100644 node_modules/google-auth-library/build/src/auth/googleauth.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/googleauth.js create mode 100644 node_modules/google-auth-library/build/src/auth/iam.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/iam.js create mode 100644 node_modules/google-auth-library/build/src/auth/idtokenclient.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/idtokenclient.js create mode 100644 node_modules/google-auth-library/build/src/auth/jwtaccess.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/jwtaccess.js create mode 100644 node_modules/google-auth-library/build/src/auth/jwtclient.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/jwtclient.js create mode 100644 node_modules/google-auth-library/build/src/auth/loginticket.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/loginticket.js create mode 100644 node_modules/google-auth-library/build/src/auth/oauth2client.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/oauth2client.js create mode 100644 node_modules/google-auth-library/build/src/auth/refreshclient.d.ts create mode 100644 node_modules/google-auth-library/build/src/auth/refreshclient.js create mode 100644 node_modules/google-auth-library/build/src/crypto/browser/crypto.d.ts create mode 100644 node_modules/google-auth-library/build/src/crypto/browser/crypto.js create mode 100644 node_modules/google-auth-library/build/src/crypto/crypto.d.ts create mode 100644 node_modules/google-auth-library/build/src/crypto/crypto.js create mode 100644 node_modules/google-auth-library/build/src/crypto/node/crypto.d.ts create mode 100644 node_modules/google-auth-library/build/src/crypto/node/crypto.js create mode 100644 node_modules/google-auth-library/build/src/index.d.ts create mode 100644 node_modules/google-auth-library/build/src/index.js create mode 100644 node_modules/google-auth-library/build/src/messages.d.ts create mode 100644 node_modules/google-auth-library/build/src/messages.js create mode 100644 node_modules/google-auth-library/build/src/options.d.ts create mode 100644 node_modules/google-auth-library/build/src/options.js create mode 100644 node_modules/google-auth-library/build/src/transporters.d.ts create mode 100644 node_modules/google-auth-library/build/src/transporters.js create mode 100644 node_modules/google-auth-library/package.json create mode 100644 node_modules/google-p12-pem/CHANGELOG.md create mode 100644 node_modules/google-p12-pem/LICENSE create mode 100644 node_modules/google-p12-pem/README.md create mode 100644 node_modules/google-p12-pem/build/src/bin/gp12-pem.d.ts create mode 100755 node_modules/google-p12-pem/build/src/bin/gp12-pem.js create mode 100644 node_modules/google-p12-pem/build/src/index.d.ts create mode 100644 node_modules/google-p12-pem/build/src/index.js create mode 100644 node_modules/google-p12-pem/package.json create mode 100644 node_modules/gtoken/CHANGELOG.md create mode 100644 node_modules/gtoken/LICENSE create mode 100644 node_modules/gtoken/README.md create mode 100644 node_modules/gtoken/build/src/index.d.ts create mode 100644 node_modules/gtoken/build/src/index.js create mode 100644 node_modules/gtoken/node_modules/gaxios/CHANGELOG.md create mode 100644 node_modules/gtoken/node_modules/gaxios/LICENSE create mode 100644 node_modules/gtoken/node_modules/gaxios/README.md create mode 100644 node_modules/gtoken/node_modules/gaxios/build/src/common.d.ts create mode 100644 node_modules/gtoken/node_modules/gaxios/build/src/common.js create mode 100644 node_modules/gtoken/node_modules/gaxios/build/src/common.js.map create mode 100644 node_modules/gtoken/node_modules/gaxios/build/src/gaxios.d.ts create mode 100644 node_modules/gtoken/node_modules/gaxios/build/src/gaxios.js create mode 100644 node_modules/gtoken/node_modules/gaxios/build/src/gaxios.js.map create mode 100644 node_modules/gtoken/node_modules/gaxios/build/src/index.d.ts create mode 100644 node_modules/gtoken/node_modules/gaxios/build/src/index.js create mode 100644 node_modules/gtoken/node_modules/gaxios/build/src/index.js.map create mode 100644 node_modules/gtoken/node_modules/gaxios/build/src/retry.d.ts create mode 100644 node_modules/gtoken/node_modules/gaxios/build/src/retry.js create mode 100644 node_modules/gtoken/node_modules/gaxios/build/src/retry.js.map create mode 100644 node_modules/gtoken/node_modules/gaxios/build/src/web.d.ts create mode 100644 node_modules/gtoken/node_modules/gaxios/build/src/web.js create mode 100644 node_modules/gtoken/node_modules/gaxios/build/src/web.js.map create mode 100644 node_modules/gtoken/node_modules/gaxios/package.json create mode 100644 node_modules/gtoken/package.json create mode 100644 node_modules/https-proxy-agent/README.md create mode 100644 node_modules/https-proxy-agent/dist/agent.d.ts create mode 100644 node_modules/https-proxy-agent/dist/agent.js create mode 100644 node_modules/https-proxy-agent/dist/agent.js.map create mode 100644 node_modules/https-proxy-agent/dist/index.d.ts create mode 100644 node_modules/https-proxy-agent/dist/index.js create mode 100644 node_modules/https-proxy-agent/dist/index.js.map create mode 100644 node_modules/https-proxy-agent/dist/parse-proxy-response.d.ts create mode 100644 node_modules/https-proxy-agent/dist/parse-proxy-response.js create mode 100644 node_modules/https-proxy-agent/dist/parse-proxy-response.js.map create mode 100644 node_modules/https-proxy-agent/package.json create mode 100644 node_modules/is-stream/index.d.ts create mode 100644 node_modules/is-stream/index.js create mode 100644 node_modules/is-stream/license create mode 100644 node_modules/is-stream/package.json create mode 100644 node_modules/is-stream/readme.md create mode 100644 node_modules/json-bigint/.npmignore create mode 100644 node_modules/json-bigint/.travis.yml create mode 100644 node_modules/json-bigint/LICENSE create mode 100644 node_modules/json-bigint/README.md create mode 100644 node_modules/json-bigint/index.js create mode 100644 node_modules/json-bigint/lib/parse.js create mode 100644 node_modules/json-bigint/lib/stringify.js create mode 100644 node_modules/json-bigint/package.json create mode 100644 node_modules/json-bigint/test/bigint-test.js create mode 100644 node_modules/json-bigint/test/strict-option-test.js create mode 100644 node_modules/json-bigint/test/string-option-test.js create mode 100644 node_modules/jwa/LICENSE create mode 100644 node_modules/jwa/README.md create mode 100644 node_modules/jwa/index.js create mode 100644 node_modules/jwa/package.json create mode 100644 node_modules/jws/CHANGELOG.md create mode 100644 node_modules/jws/LICENSE create mode 100644 node_modules/jws/index.js create mode 100644 node_modules/jws/lib/data-stream.js create mode 100644 node_modules/jws/lib/sign-stream.js create mode 100644 node_modules/jws/lib/tostring.js create mode 100644 node_modules/jws/lib/verify-stream.js create mode 100644 node_modules/jws/package.json create mode 100644 node_modules/jws/readme.md create mode 100644 node_modules/lru-cache/LICENSE create mode 100644 node_modules/lru-cache/README.md create mode 100644 node_modules/lru-cache/index.js create mode 100644 node_modules/lru-cache/package.json create mode 100644 node_modules/mime/.eslintrc.json create mode 100644 node_modules/mime/.github/ISSUE_TEMPLATE.md create mode 100644 node_modules/mime/.github/PULL_REQUEST_TEMPLATE.md create mode 100644 node_modules/mime/.travis.yml create mode 100644 node_modules/mime/CHANGELOG.md create mode 100644 node_modules/mime/CONTRIBUTING.md create mode 100644 node_modules/mime/LICENSE create mode 100644 node_modules/mime/Mime.js create mode 100644 node_modules/mime/README.md create mode 100755 node_modules/mime/cli.js create mode 100644 node_modules/mime/index.js create mode 100644 node_modules/mime/lite.js create mode 100644 node_modules/mime/package.json create mode 100644 node_modules/mime/src/README_js.md create mode 100644 node_modules/mime/src/benchmark.js create mode 100755 node_modules/mime/src/build.js create mode 100644 node_modules/mime/src/test.js create mode 100644 node_modules/mime/types/other.js create mode 100644 node_modules/mime/types/standard.js create mode 100644 node_modules/ms/index.js create mode 100644 node_modules/ms/license.md create mode 100644 node_modules/ms/package.json create mode 100644 node_modules/ms/readme.md create mode 100644 node_modules/node-fetch/CHANGELOG.md create mode 100644 node_modules/node-fetch/LICENSE.md create mode 100644 node_modules/node-fetch/README.md create mode 100644 node_modules/node-fetch/browser.js create mode 100644 node_modules/node-fetch/lib/index.es.js create mode 100644 node_modules/node-fetch/lib/index.js create mode 100644 node_modules/node-fetch/lib/index.mjs create mode 100644 node_modules/node-fetch/package.json create mode 100644 node_modules/node-forge/CHANGELOG.md create mode 100644 node_modules/node-forge/LICENSE create mode 100644 node_modules/node-forge/README.md create mode 100644 node_modules/node-forge/dist/forge.all.min.js create mode 100644 node_modules/node-forge/dist/forge.all.min.js.map create mode 100644 node_modules/node-forge/dist/forge.min.js create mode 100644 node_modules/node-forge/dist/forge.min.js.map create mode 100644 node_modules/node-forge/dist/prime.worker.min.js create mode 100644 node_modules/node-forge/dist/prime.worker.min.js.map create mode 100644 node_modules/node-forge/flash/README.md create mode 100644 node_modules/node-forge/flash/package.json create mode 100644 node_modules/node-forge/flash/swf/SocketPool.swf create mode 100644 node_modules/node-forge/lib/aes.js create mode 100644 node_modules/node-forge/lib/aesCipherSuites.js create mode 100644 node_modules/node-forge/lib/asn1-validator.js create mode 100644 node_modules/node-forge/lib/asn1.js create mode 100644 node_modules/node-forge/lib/baseN.js create mode 100644 node_modules/node-forge/lib/cipher.js create mode 100644 node_modules/node-forge/lib/cipherModes.js create mode 100644 node_modules/node-forge/lib/debug.js create mode 100644 node_modules/node-forge/lib/des.js create mode 100644 node_modules/node-forge/lib/ed25519.js create mode 100644 node_modules/node-forge/lib/forge.js create mode 100644 node_modules/node-forge/lib/form.js create mode 100644 node_modules/node-forge/lib/hmac.js create mode 100644 node_modules/node-forge/lib/http.js create mode 100644 node_modules/node-forge/lib/index.all.js create mode 100644 node_modules/node-forge/lib/index.js create mode 100644 node_modules/node-forge/lib/jsbn.js create mode 100644 node_modules/node-forge/lib/kem.js create mode 100644 node_modules/node-forge/lib/log.js create mode 100644 node_modules/node-forge/lib/md.all.js create mode 100644 node_modules/node-forge/lib/md.js create mode 100644 node_modules/node-forge/lib/md5.js create mode 100644 node_modules/node-forge/lib/mgf.js create mode 100644 node_modules/node-forge/lib/mgf1.js create mode 100644 node_modules/node-forge/lib/oids.js create mode 100644 node_modules/node-forge/lib/pbe.js create mode 100644 node_modules/node-forge/lib/pbkdf2.js create mode 100644 node_modules/node-forge/lib/pem.js create mode 100644 node_modules/node-forge/lib/pkcs1.js create mode 100644 node_modules/node-forge/lib/pkcs12.js create mode 100644 node_modules/node-forge/lib/pkcs7.js create mode 100644 node_modules/node-forge/lib/pkcs7asn1.js create mode 100644 node_modules/node-forge/lib/pki.js create mode 100644 node_modules/node-forge/lib/prime.js create mode 100644 node_modules/node-forge/lib/prime.worker.js create mode 100644 node_modules/node-forge/lib/prng.js create mode 100644 node_modules/node-forge/lib/pss.js create mode 100644 node_modules/node-forge/lib/random.js create mode 100644 node_modules/node-forge/lib/rc2.js create mode 100644 node_modules/node-forge/lib/rsa.js create mode 100644 node_modules/node-forge/lib/sha1.js create mode 100644 node_modules/node-forge/lib/sha256.js create mode 100644 node_modules/node-forge/lib/sha512.js create mode 100644 node_modules/node-forge/lib/socket.js create mode 100644 node_modules/node-forge/lib/ssh.js create mode 100644 node_modules/node-forge/lib/task.js create mode 100644 node_modules/node-forge/lib/tls.js create mode 100644 node_modules/node-forge/lib/tlssocket.js create mode 100644 node_modules/node-forge/lib/util.js create mode 100644 node_modules/node-forge/lib/x509.js create mode 100644 node_modules/node-forge/lib/xhr.js create mode 100644 node_modules/node-forge/package.json create mode 100644 node_modules/safe-buffer/LICENSE create mode 100644 node_modules/safe-buffer/README.md create mode 100644 node_modules/safe-buffer/index.d.ts create mode 100644 node_modules/safe-buffer/index.js create mode 100644 node_modules/safe-buffer/package.json create mode 100644 node_modules/yallist/LICENSE create mode 100644 node_modules/yallist/README.md create mode 100644 node_modules/yallist/iterator.js create mode 100644 node_modules/yallist/package.json create mode 100644 node_modules/yallist/yallist.js create mode 100644 package-lock.json create mode 100644 package.json diff --git a/README.md b/README.md new file mode 100644 index 0000000..2dcb5e7 --- /dev/null +++ b/README.md @@ -0,0 +1,132 @@ +# Fetch Build from GCB + +A Github action to fetch a given build from GCB and extract the docker digest of a target image. + +## Inputs + +- `build_url` **Required** The link to the GCB build so we can extract the build ID. +- `target_image` **Required** The name of the image to find the digest for. + +## Output + +- `digest` The SHA256 docker digest of the image. + +## Setup + +This action uses a Google Cloud service account to fetch build information from the API. To use it +in your workflow you need to do the following things: + +1. Have the service account credentials file available as a repository secret. + +1. Dump the contents of that secret to a file. This is required by the `google-auth-library` package. + + ```yaml + - name: initialize credentials + run: | + mkdir -p ./secrets + echo $GOOGLE_APPLICATION_CREDENTIALS > ./secrets/GOOGLE_APPLICATION_CREDENTIALS + env: + GOOGLE_APPLICATION_CREDENTIALS: ${{ secrets.GOOGLE_APPLICATION_CREDENTIALS }} + ``` + +1. Set the location of that secrets file in the `GOOGLE_APPLICATION_CREDENTIALS` environment + variable when running this action. + + ```yaml + - id: find_digest + uses: zendesk/fetch-build-from-gcb + with: + build_url: ${{ github.event.path-to-build-url }} + target_image: my-app + env: + GOOGLE_APPLICATION_CREDENTIALS: ./secrets/GOOGLE_APPLICATION_CREDENTIALS + ``` + +## Usage + +### With a repo mirrored to GCR and GCB webhooks + +If your repository is mirrored into GCR and the build information appears on your repository with +a PR status from `docker-images-180022`, then you need to have your workflow response to `status` +events. + +If your build creates an image tagged as `my-app:{commit_sha}`, then your workflow might look like +this: + +```yaml +on: status + +jobs: + find_digest: + runs-on: ubuntu-latest + if: | + github.event.state == 'success' && + contains(github.event.description, 'GCB build') + steps: + - name: initialize credentials + run: | + mkdir -p ./secrets + echo $GOOGLE_APPLICATION_CREDENTIALS > ./secrets/GOOGLE_APPLICATION_CREDENTIALS + env: + GOOGLE_APPLICATION_CREDENTIALS: ${{ secrets.GOOGLE_APPLICATION_CREDENTIALS }} + + - id: find_digest + uses: zendesk/fetch-build-from-gcb + with: + build_url: ${{ github.event.target_url }} + target_image: my-app + env: + GOOGLE_APPLICATION_CREDENTIALS: ./secrets/GOOGLE_APPLICATION_CREDENTIALS + + - name: cleanup credentials + run: rm -rf ./secrets + + - name: Something that uses the digest + env: + IMAGE_DIGEST: ${{ steps.find_digest.outputs.digest }} +``` + +### With a repo connected to the GCB app and GCB check runs + +If your repository is connected to the GCB app and the build information appears on your repository +with a PR status from `Google Cloud Build`, then you need to have your workflow response to +`check_run` events. + +If your build creates an image tagged as `fun-app:{git_tag}`, then your workflow might include steps +that look like this: + +```yaml +on: + check_run: + types: + - completed + +jobs: + from_gcb_check_run: + runs-on: ubuntu-latest + if: | + github.event.check_run.app.name == 'Google Cloud Build' && + github.event.check_run.conclusion == 'success' + steps: + - name: initialize credentials + run: | + mkdir -p ./secrets + echo $GOOGLE_APPLICATION_CREDENTIALS > ./secrets/GOOGLE_APPLICATION_CREDENTIALS + env: + GOOGLE_APPLICATION_CREDENTIALS: ${{ secrets.GOOGLE_APPLICATION_CREDENTIALS }} + + - id: find_digest + uses: zendesk/fetch-build-from-gcb + with: + build_url: ${{ github.event.check_run.details_url }} + target_image: fun-app + env: + GOOGLE_APPLICATION_CREDENTIALS: ./secrets/GOOGLE_APPLICATION_CREDENTIALS + + - name: cleanup credentials + run: rm -rf ./secrets + + - name: Something that uses the digest + env: + IMAGE_DIGEST: ${{ steps.find_digest.outputs.digest }} +``` diff --git a/action.js b/action.js new file mode 100644 index 0000000..855903b --- /dev/null +++ b/action.js @@ -0,0 +1,52 @@ +const core = require('@actions/core') +const { GoogleAuth } = require('google-auth-library') + +function buildId() { + const url = new URL(core.getInput('build_url')) + + return url.pathname.split('/').pop() +} + +async function fetchBuild(buildId) { + const auth = new GoogleAuth({ + scopes: 'https://www.googleapis.com/auth/cloud-platform', + }) + + const client = await auth.getClient() + const projectId = await auth.getProjectId() + + const response = await client.request({ + url: `https://cloudbuild.googleapis.com/v1/projects/${projectId}/builds/${buildId}`, + }) + + const targetImage = core.getInput('target_image') + const build = response.data + + if (build.status.toUpperCase() != 'SUCCESS') { + core.setFailed(`Build ${build.id} was not successful`) + return + } else { + const image = build.results.images.find(image => + image.name.split(':', 2)[0].endsWith(targetImage) + ) + + if (!image) { + core.setFailed(`Failed to find image matching ${targetImage}`) + return + } + + return image.digest + } +} + +async function run() { + const digest = await fetchBuild(buildId()) + + core.setOutput('digest', digest) +} + +try { + run() +} catch (error) { + core.setFailed(`Action failed with error ${error}`) +} diff --git a/action.yml b/action.yml new file mode 100644 index 0000000..c69a34d --- /dev/null +++ b/action.yml @@ -0,0 +1,19 @@ +name: Fetch Build from GCB +description: Use the GCB API to extract the Docker digest of a build completed for a given git SHA. +author: Support Platform + +runs: + using: node12 + main: action.js + +inputs: + build_url: + description: The link to the GCB build so we can extract the build ID + required: true + target_image: + description: The name of the image to find the digest for + required: true + +outputs: + digest: + description: The Docker digest for the image pulled from GCB diff --git a/node_modules/.bin/gp12-pem b/node_modules/.bin/gp12-pem new file mode 120000 index 0000000..cfbbf67 --- /dev/null +++ b/node_modules/.bin/gp12-pem @@ -0,0 +1 @@ +../google-p12-pem/build/src/bin/gp12-pem.js \ No newline at end of file diff --git a/node_modules/.bin/mime b/node_modules/.bin/mime new file mode 120000 index 0000000..fbb7ee0 --- /dev/null +++ b/node_modules/.bin/mime @@ -0,0 +1 @@ +../mime/cli.js \ No newline at end of file diff --git a/node_modules/@actions/core/README.md b/node_modules/@actions/core/README.md new file mode 100644 index 0000000..5ad27ee --- /dev/null +++ b/node_modules/@actions/core/README.md @@ -0,0 +1,146 @@ +# `@actions/core` + +> Core functions for setting results, logging, registering secrets and exporting variables across actions + +## Usage + +### Import the package + +```js +// javascript +const core = require('@actions/core'); + +// typescript +import * as core from '@actions/core'; +``` + +#### Inputs/Outputs + +Action inputs can be read with `getInput`. Outputs can be set with `setOutput` which makes them available to be mapped into inputs of other actions to ensure they are decoupled. + +```js +const myInput = core.getInput('inputName', { required: true }); + +core.setOutput('outputKey', 'outputVal'); +``` + +#### Exporting variables + +Since each step runs in a separate process, you can use `exportVariable` to add it to this step and future steps environment blocks. + +```js +core.exportVariable('envVar', 'Val'); +``` + +#### Setting a secret + +Setting a secret registers the secret with the runner to ensure it is masked in logs. + +```js +core.setSecret('myPassword'); +``` + +#### PATH Manipulation + +To make a tool's path available in the path for the remainder of the job (without altering the machine or containers state), use `addPath`. The runner will prepend the path given to the jobs PATH. + +```js +core.addPath('/path/to/mytool'); +``` + +#### Exit codes + +You should use this library to set the failing exit code for your action. If status is not set and the script runs to completion, that will lead to a success. + +```js +const core = require('@actions/core'); + +try { + // Do stuff +} +catch (err) { + // setFailed logs the message and sets a failing exit code + core.setFailed(`Action failed with error ${err}`); +} + +Note that `setNeutral` is not yet implemented in actions V2 but equivalent functionality is being planned. + +``` + +#### Logging + +Finally, this library provides some utilities for logging. Note that debug logging is hidden from the logs by default. This behavior can be toggled by enabling the [Step Debug Logs](../../docs/action-debugging.md#step-debug-logs). + +```js +const core = require('@actions/core'); + +const myInput = core.getInput('input'); +try { + core.debug('Inside try block'); + + if (!myInput) { + core.warning('myInput was not set'); + } + + if (core.isDebug()) { + // curl -v https://github.com + } else { + // curl https://github.com + } + + // Do stuff +} +catch (err) { + core.error(`Error ${err}, action may still succeed though`); +} +``` + +This library can also wrap chunks of output in foldable groups. + +```js +const core = require('@actions/core') + +// Manually wrap output +core.startGroup('Do some function') +doSomeFunction() +core.endGroup() + +// Wrap an asynchronous function call +const result = await core.group('Do something async', async () => { + const response = await doSomeHTTPRequest() + return response +}) +``` + +#### Action state + +You can use this library to save state and get state for sharing information between a given wrapper action: + +**action.yml** +```yaml +name: 'Wrapper action sample' +inputs: + name: + default: 'GitHub' +runs: + using: 'node12' + main: 'main.js' + post: 'cleanup.js' +``` + +In action's `main.js`: + +```js +const core = require('@actions/core'); + +core.saveState("pidToKill", 12345); +``` + +In action's `cleanup.js`: +```js +const core = require('@actions/core'); + +var pid = core.getState("pidToKill"); + +process.kill(pid); +``` \ No newline at end of file diff --git a/node_modules/@actions/core/lib/command.d.ts b/node_modules/@actions/core/lib/command.d.ts new file mode 100644 index 0000000..51b8f11 --- /dev/null +++ b/node_modules/@actions/core/lib/command.d.ts @@ -0,0 +1,16 @@ +interface CommandProperties { + [key: string]: string; +} +/** + * Commands + * + * Command Format: + * ::name key=value,key=value::message + * + * Examples: + * ::warning::This is the message + * ::set-env name=MY_VAR::some value + */ +export declare function issueCommand(command: string, properties: CommandProperties, message: string): void; +export declare function issue(name: string, message?: string): void; +export {}; diff --git a/node_modules/@actions/core/lib/command.js b/node_modules/@actions/core/lib/command.js new file mode 100644 index 0000000..eeef233 --- /dev/null +++ b/node_modules/@actions/core/lib/command.js @@ -0,0 +1,78 @@ +"use strict"; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const os = __importStar(require("os")); +/** + * Commands + * + * Command Format: + * ::name key=value,key=value::message + * + * Examples: + * ::warning::This is the message + * ::set-env name=MY_VAR::some value + */ +function issueCommand(command, properties, message) { + const cmd = new Command(command, properties, message); + process.stdout.write(cmd.toString() + os.EOL); +} +exports.issueCommand = issueCommand; +function issue(name, message = '') { + issueCommand(name, {}, message); +} +exports.issue = issue; +const CMD_STRING = '::'; +class Command { + constructor(command, properties, message) { + if (!command) { + command = 'missing.command'; + } + this.command = command; + this.properties = properties; + this.message = message; + } + toString() { + let cmdStr = CMD_STRING + this.command; + if (this.properties && Object.keys(this.properties).length > 0) { + cmdStr += ' '; + let first = true; + for (const key in this.properties) { + if (this.properties.hasOwnProperty(key)) { + const val = this.properties[key]; + if (val) { + if (first) { + first = false; + } + else { + cmdStr += ','; + } + cmdStr += `${key}=${escapeProperty(val)}`; + } + } + } + } + cmdStr += `${CMD_STRING}${escapeData(this.message)}`; + return cmdStr; + } +} +function escapeData(s) { + return (s || '') + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A'); +} +function escapeProperty(s) { + return (s || '') + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A') + .replace(/:/g, '%3A') + .replace(/,/g, '%2C'); +} +//# sourceMappingURL=command.js.map \ No newline at end of file diff --git a/node_modules/@actions/core/lib/command.js.map b/node_modules/@actions/core/lib/command.js.map new file mode 100644 index 0000000..00a9861 --- /dev/null +++ b/node_modules/@actions/core/lib/command.js.map @@ -0,0 +1 @@ +{"version":3,"file":"command.js","sourceRoot":"","sources":["../src/command.ts"],"names":[],"mappings":";;;;;;;;;AAAA,uCAAwB;AAQxB;;;;;;;;;GASG;AACH,SAAgB,YAAY,CAC1B,OAAe,EACf,UAA6B,EAC7B,OAAe;IAEf,MAAM,GAAG,GAAG,IAAI,OAAO,CAAC,OAAO,EAAE,UAAU,EAAE,OAAO,CAAC,CAAA;IACrD,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,CAAC,QAAQ,EAAE,GAAG,EAAE,CAAC,GAAG,CAAC,CAAA;AAC/C,CAAC;AAPD,oCAOC;AAED,SAAgB,KAAK,CAAC,IAAY,EAAE,UAAkB,EAAE;IACtD,YAAY,CAAC,IAAI,EAAE,EAAE,EAAE,OAAO,CAAC,CAAA;AACjC,CAAC;AAFD,sBAEC;AAED,MAAM,UAAU,GAAG,IAAI,CAAA;AAEvB,MAAM,OAAO;IAKX,YAAY,OAAe,EAAE,UAA6B,EAAE,OAAe;QACzE,IAAI,CAAC,OAAO,EAAE;YACZ,OAAO,GAAG,iBAAiB,CAAA;SAC5B;QAED,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;QACtB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAA;QAC5B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAA;IACxB,CAAC;IAED,QAAQ;QACN,IAAI,MAAM,GAAG,UAAU,GAAG,IAAI,CAAC,OAAO,CAAA;QAEtC,IAAI,IAAI,CAAC,UAAU,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,MAAM,GAAG,CAAC,EAAE;YAC9D,MAAM,IAAI,GAAG,CAAA;YACb,IAAI,KAAK,GAAG,IAAI,CAAA;YAChB,KAAK,MAAM,GAAG,IAAI,IAAI,CAAC,UAAU,EAAE;gBACjC,IAAI,IAAI,CAAC,UAAU,CAAC,cAAc,CAAC,GAAG,CAAC,EAAE;oBACvC,MAAM,GAAG,GAAG,IAAI,CAAC,UAAU,CAAC,GAAG,CAAC,CAAA;oBAChC,IAAI,GAAG,EAAE;wBACP,IAAI,KAAK,EAAE;4BACT,KAAK,GAAG,KAAK,CAAA;yBACd;6BAAM;4BACL,MAAM,IAAI,GAAG,CAAA;yBACd;wBAED,MAAM,IAAI,GAAG,GAAG,IAAI,cAAc,CAAC,GAAG,CAAC,EAAE,CAAA;qBAC1C;iBACF;aACF;SACF;QAED,MAAM,IAAI,GAAG,UAAU,GAAG,UAAU,CAAC,IAAI,CAAC,OAAO,CAAC,EAAE,CAAA;QACpD,OAAO,MAAM,CAAA;IACf,CAAC;CACF;AAED,SAAS,UAAU,CAAC,CAAS;IAC3B,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC;SACb,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC;SACpB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;SACrB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC,CAAA;AAC1B,CAAC;AAED,SAAS,cAAc,CAAC,CAAS;IAC/B,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC;SACb,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC;SACpB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;SACrB,OAAO,CAAC,KAAK,EAAE,KAAK,CAAC;SACrB,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC;SACpB,OAAO,CAAC,IAAI,EAAE,KAAK,CAAC,CAAA;AACzB,CAAC"} \ No newline at end of file diff --git a/node_modules/@actions/core/lib/core.d.ts b/node_modules/@actions/core/lib/core.d.ts new file mode 100644 index 0000000..8fcc31b --- /dev/null +++ b/node_modules/@actions/core/lib/core.d.ts @@ -0,0 +1,116 @@ +/** + * Interface for getInput options + */ +export interface InputOptions { + /** Optional. Whether the input is required. If required and not present, will throw. Defaults to false */ + required?: boolean; +} +/** + * The code to exit an action + */ +export declare enum ExitCode { + /** + * A code indicating that the action was successful + */ + Success = 0, + /** + * A code indicating that the action was a failure + */ + Failure = 1 +} +/** + * Sets env variable for this action and future actions in the job + * @param name the name of the variable to set + * @param val the value of the variable + */ +export declare function exportVariable(name: string, val: string): void; +/** + * Registers a secret which will get masked from logs + * @param secret value of the secret + */ +export declare function setSecret(secret: string): void; +/** + * Prepends inputPath to the PATH (for this action and future actions) + * @param inputPath + */ +export declare function addPath(inputPath: string): void; +/** + * Gets the value of an input. The value is also trimmed. + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns string + */ +export declare function getInput(name: string, options?: InputOptions): string; +/** + * Sets the value of an output. + * + * @param name name of the output to set + * @param value value to store + */ +export declare function setOutput(name: string, value: string): void; +/** + * Sets the action status to failed. + * When the action exits it will be with an exit code of 1 + * @param message add error issue message + */ +export declare function setFailed(message: string): void; +/** + * Gets whether Actions Step Debug is on or not + */ +export declare function isDebug(): boolean; +/** + * Writes debug message to user log + * @param message debug message + */ +export declare function debug(message: string): void; +/** + * Adds an error issue + * @param message error issue message + */ +export declare function error(message: string): void; +/** + * Adds an warning issue + * @param message warning issue message + */ +export declare function warning(message: string): void; +/** + * Writes info to log with console.log. + * @param message info message + */ +export declare function info(message: string): void; +/** + * Begin an output group. + * + * Output until the next `groupEnd` will be foldable in this group + * + * @param name The name of the output group + */ +export declare function startGroup(name: string): void; +/** + * End an output group. + */ +export declare function endGroup(): void; +/** + * Wrap an asynchronous function call in a group. + * + * Returns the same type as the function itself. + * + * @param name The name of the group + * @param fn The function to wrap in the group + */ +export declare function group(name: string, fn: () => Promise): Promise; +/** + * Saves state for current action, the state can only be retrieved by this action's post job execution. + * + * @param name name of the state to store + * @param value value to store + */ +export declare function saveState(name: string, value: string): void; +/** + * Gets the value of an state set by this action's main execution. + * + * @param name name of the state to get + * @returns string + */ +export declare function getState(name: string): string; diff --git a/node_modules/@actions/core/lib/core.js b/node_modules/@actions/core/lib/core.js new file mode 100644 index 0000000..b7ec8ab --- /dev/null +++ b/node_modules/@actions/core/lib/core.js @@ -0,0 +1,209 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k]; + result["default"] = mod; + return result; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const command_1 = require("./command"); +const os = __importStar(require("os")); +const path = __importStar(require("path")); +/** + * The code to exit an action + */ +var ExitCode; +(function (ExitCode) { + /** + * A code indicating that the action was successful + */ + ExitCode[ExitCode["Success"] = 0] = "Success"; + /** + * A code indicating that the action was a failure + */ + ExitCode[ExitCode["Failure"] = 1] = "Failure"; +})(ExitCode = exports.ExitCode || (exports.ExitCode = {})); +//----------------------------------------------------------------------- +// Variables +//----------------------------------------------------------------------- +/** + * Sets env variable for this action and future actions in the job + * @param name the name of the variable to set + * @param val the value of the variable + */ +function exportVariable(name, val) { + process.env[name] = val; + command_1.issueCommand('set-env', { name }, val); +} +exports.exportVariable = exportVariable; +/** + * Registers a secret which will get masked from logs + * @param secret value of the secret + */ +function setSecret(secret) { + command_1.issueCommand('add-mask', {}, secret); +} +exports.setSecret = setSecret; +/** + * Prepends inputPath to the PATH (for this action and future actions) + * @param inputPath + */ +function addPath(inputPath) { + command_1.issueCommand('add-path', {}, inputPath); + process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; +} +exports.addPath = addPath; +/** + * Gets the value of an input. The value is also trimmed. + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns string + */ +function getInput(name, options) { + const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; + if (options && options.required && !val) { + throw new Error(`Input required and not supplied: ${name}`); + } + return val.trim(); +} +exports.getInput = getInput; +/** + * Sets the value of an output. + * + * @param name name of the output to set + * @param value value to store + */ +function setOutput(name, value) { + command_1.issueCommand('set-output', { name }, value); +} +exports.setOutput = setOutput; +//----------------------------------------------------------------------- +// Results +//----------------------------------------------------------------------- +/** + * Sets the action status to failed. + * When the action exits it will be with an exit code of 1 + * @param message add error issue message + */ +function setFailed(message) { + process.exitCode = ExitCode.Failure; + error(message); +} +exports.setFailed = setFailed; +//----------------------------------------------------------------------- +// Logging Commands +//----------------------------------------------------------------------- +/** + * Gets whether Actions Step Debug is on or not + */ +function isDebug() { + return process.env['RUNNER_DEBUG'] === '1'; +} +exports.isDebug = isDebug; +/** + * Writes debug message to user log + * @param message debug message + */ +function debug(message) { + command_1.issueCommand('debug', {}, message); +} +exports.debug = debug; +/** + * Adds an error issue + * @param message error issue message + */ +function error(message) { + command_1.issue('error', message); +} +exports.error = error; +/** + * Adds an warning issue + * @param message warning issue message + */ +function warning(message) { + command_1.issue('warning', message); +} +exports.warning = warning; +/** + * Writes info to log with console.log. + * @param message info message + */ +function info(message) { + process.stdout.write(message + os.EOL); +} +exports.info = info; +/** + * Begin an output group. + * + * Output until the next `groupEnd` will be foldable in this group + * + * @param name The name of the output group + */ +function startGroup(name) { + command_1.issue('group', name); +} +exports.startGroup = startGroup; +/** + * End an output group. + */ +function endGroup() { + command_1.issue('endgroup'); +} +exports.endGroup = endGroup; +/** + * Wrap an asynchronous function call in a group. + * + * Returns the same type as the function itself. + * + * @param name The name of the group + * @param fn The function to wrap in the group + */ +function group(name, fn) { + return __awaiter(this, void 0, void 0, function* () { + startGroup(name); + let result; + try { + result = yield fn(); + } + finally { + endGroup(); + } + return result; + }); +} +exports.group = group; +//----------------------------------------------------------------------- +// Wrapper action state +//----------------------------------------------------------------------- +/** + * Saves state for current action, the state can only be retrieved by this action's post job execution. + * + * @param name name of the state to store + * @param value value to store + */ +function saveState(name, value) { + command_1.issueCommand('save-state', { name }, value); +} +exports.saveState = saveState; +/** + * Gets the value of an state set by this action's main execution. + * + * @param name name of the state to get + * @returns string + */ +function getState(name) { + return process.env[`STATE_${name}`] || ''; +} +exports.getState = getState; +//# sourceMappingURL=core.js.map \ No newline at end of file diff --git a/node_modules/@actions/core/lib/core.js.map b/node_modules/@actions/core/lib/core.js.map new file mode 100644 index 0000000..fb93bd3 --- /dev/null +++ b/node_modules/@actions/core/lib/core.js.map @@ -0,0 +1 @@ +{"version":3,"file":"core.js","sourceRoot":"","sources":["../src/core.ts"],"names":[],"mappings":"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"} \ No newline at end of file diff --git a/node_modules/@actions/core/package.json b/node_modules/@actions/core/package.json new file mode 100644 index 0000000..5b5d48a --- /dev/null +++ b/node_modules/@actions/core/package.json @@ -0,0 +1,67 @@ +{ + "_from": "@actions/core", + "_id": "@actions/core@1.2.3", + "_inBundle": false, + "_integrity": "sha512-Wp4xnyokakM45Uuj4WLUxdsa8fJjKVl1fDTsPbTEcTcuu0Nb26IPQbOtjmnfaCPGcaoPOOqId8H9NapZ8gii4w==", + "_location": "/@actions/core", + "_phantomChildren": {}, + "_requested": { + "type": "tag", + "registry": true, + "raw": "@actions/core", + "name": "@actions/core", + "escapedName": "@actions%2fcore", + "scope": "@actions", + "rawSpec": "", + "saveSpec": null, + "fetchSpec": "latest" + }, + "_requiredBy": [ + "#USER", + "/" + ], + "_resolved": "https://registry.npmjs.org/@actions/core/-/core-1.2.3.tgz", + "_shasum": "e844b4fa0820e206075445079130868f95bfca95", + "_spec": "@actions/core", + "_where": "/Users/cday/Code/zendesk/fetch-build-from-gcb", + "bugs": { + "url": "https://github.com/actions/toolkit/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Actions core lib", + "devDependencies": { + "@types/node": "^12.0.2" + }, + "directories": { + "lib": "lib", + "test": "__tests__" + }, + "files": [ + "lib" + ], + "homepage": "https://github.com/actions/toolkit/tree/master/packages/core", + "keywords": [ + "github", + "actions", + "core" + ], + "license": "MIT", + "main": "lib/core.js", + "name": "@actions/core", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/actions/toolkit.git", + "directory": "packages/core" + }, + "scripts": { + "audit-moderate": "npm install && npm audit --audit-level=moderate", + "test": "echo \"Error: run tests from root\" && exit 1", + "tsc": "tsc" + }, + "types": "lib/core.d.ts", + "version": "1.2.3" +} diff --git a/node_modules/abort-controller/LICENSE b/node_modules/abort-controller/LICENSE new file mode 100644 index 0000000..c914149 --- /dev/null +++ b/node_modules/abort-controller/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017 Toru Nagashima + +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. diff --git a/node_modules/abort-controller/README.md b/node_modules/abort-controller/README.md new file mode 100644 index 0000000..9de3e45 --- /dev/null +++ b/node_modules/abort-controller/README.md @@ -0,0 +1,98 @@ +# abort-controller + +[![npm version](https://img.shields.io/npm/v/abort-controller.svg)](https://www.npmjs.com/package/abort-controller) +[![Downloads/month](https://img.shields.io/npm/dm/abort-controller.svg)](http://www.npmtrends.com/abort-controller) +[![Build Status](https://travis-ci.org/mysticatea/abort-controller.svg?branch=master)](https://travis-ci.org/mysticatea/abort-controller) +[![Coverage Status](https://codecov.io/gh/mysticatea/abort-controller/branch/master/graph/badge.svg)](https://codecov.io/gh/mysticatea/abort-controller) +[![Dependency Status](https://david-dm.org/mysticatea/abort-controller.svg)](https://david-dm.org/mysticatea/abort-controller) + +An implementation of [WHATWG AbortController interface](https://dom.spec.whatwg.org/#interface-abortcontroller). + +```js +import AbortController from "abort-controller" + +const controller = new AbortController() +const signal = controller.signal + +signal.addEventListener("abort", () => { + console.log("aborted!") +}) + +controller.abort() +``` + +> https://jsfiddle.net/1r2994qp/1/ + +## 💿 Installation + +Use [npm](https://www.npmjs.com/) to install then use a bundler. + +``` +npm install abort-controller +``` + +Or download from [`dist` directory](./dist). + +- [dist/abort-controller.mjs](dist/abort-controller.mjs) ... ES modules version. +- [dist/abort-controller.js](dist/abort-controller.js) ... Common JS version. +- [dist/abort-controller.umd.js](dist/abort-controller.umd.js) ... UMD (Universal Module Definition) version. This is transpiled by [Babel](https://babeljs.io/) for IE 11. + +## 📖 Usage + +### Basic + +```js +import AbortController from "abort-controller" +// or +const AbortController = require("abort-controller") + +// or UMD version defines a global variable: +const AbortController = window.AbortControllerShim +``` + +If your bundler recognizes `browser` field of `package.json`, the imported `AbortController` is the native one and it doesn't contain shim (even if the native implementation was nothing). +If you wanted to polyfill `AbortController` for IE, use `abort-controller/polyfill`. + +### Polyfilling + +Importing `abort-controller/polyfill` assigns the `AbortController` shim to the `AbortController` global variable if the native implementation was nothing. + +```js +import "abort-controller/polyfill" +// or +require("abort-controller/polyfill") +``` + +### API + +#### AbortController + +> https://dom.spec.whatwg.org/#interface-abortcontroller + +##### controller.signal + +The [AbortSignal](https://dom.spec.whatwg.org/#interface-AbortSignal) object which is associated to this controller. + +##### controller.abort() + +Notify `abort` event to listeners that the `signal` has. + +## 📰 Changelog + +- See [GitHub releases](https://github.com/mysticatea/abort-controller/releases). + +## 🍻 Contributing + +Contributing is welcome ❤️ + +Please use GitHub issues/PRs. + +### Development tools + +- `npm install` installs dependencies for development. +- `npm test` runs tests and measures code coverage. +- `npm run clean` removes temporary files of tests. +- `npm run coverage` opens code coverage of the previous test with your default browser. +- `npm run lint` runs ESLint. +- `npm run build` generates `dist` codes. +- `npm run watch` runs tests on each file change. diff --git a/node_modules/abort-controller/browser.js b/node_modules/abort-controller/browser.js new file mode 100644 index 0000000..b0c5ec3 --- /dev/null +++ b/node_modules/abort-controller/browser.js @@ -0,0 +1,13 @@ +/*globals self, window */ +"use strict" + +/*eslint-disable @mysticatea/prettier */ +const { AbortController, AbortSignal } = + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : + /* otherwise */ undefined +/*eslint-enable @mysticatea/prettier */ + +module.exports = AbortController +module.exports.AbortSignal = AbortSignal +module.exports.default = AbortController diff --git a/node_modules/abort-controller/browser.mjs b/node_modules/abort-controller/browser.mjs new file mode 100644 index 0000000..a8f321a --- /dev/null +++ b/node_modules/abort-controller/browser.mjs @@ -0,0 +1,11 @@ +/*globals self, window */ + +/*eslint-disable @mysticatea/prettier */ +const { AbortController, AbortSignal } = + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : + /* otherwise */ undefined +/*eslint-enable @mysticatea/prettier */ + +export default AbortController +export { AbortController, AbortSignal } diff --git a/node_modules/abort-controller/dist/abort-controller.d.ts b/node_modules/abort-controller/dist/abort-controller.d.ts new file mode 100644 index 0000000..75852fb --- /dev/null +++ b/node_modules/abort-controller/dist/abort-controller.d.ts @@ -0,0 +1,43 @@ +import { EventTarget } from "event-target-shim" + +type Events = { + abort: any +} +type EventAttributes = { + onabort: any +} +/** + * The signal class. + * @see https://dom.spec.whatwg.org/#abortsignal + */ +declare class AbortSignal extends EventTarget { + /** + * AbortSignal cannot be constructed directly. + */ + constructor() + /** + * Returns `true` if this `AbortSignal`"s `AbortController` has signaled to abort, and `false` otherwise. + */ + readonly aborted: boolean +} +/** + * The AbortController. + * @see https://dom.spec.whatwg.org/#abortcontroller + */ +declare class AbortController { + /** + * Initialize this controller. + */ + constructor() + /** + * Returns the `AbortSignal` object associated with this object. + */ + readonly signal: AbortSignal + /** + * Abort and signal to any observers that the associated activity is to be aborted. + */ + abort(): void +} + +export default AbortController +export { AbortController, AbortSignal } diff --git a/node_modules/abort-controller/dist/abort-controller.js b/node_modules/abort-controller/dist/abort-controller.js new file mode 100644 index 0000000..49af739 --- /dev/null +++ b/node_modules/abort-controller/dist/abort-controller.js @@ -0,0 +1,127 @@ +/** + * @author Toru Nagashima + * See LICENSE file in root directory for full license. + */ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +var eventTargetShim = require('event-target-shim'); + +/** + * The signal class. + * @see https://dom.spec.whatwg.org/#abortsignal + */ +class AbortSignal extends eventTargetShim.EventTarget { + /** + * AbortSignal cannot be constructed directly. + */ + constructor() { + super(); + throw new TypeError("AbortSignal cannot be constructed directly"); + } + /** + * Returns `true` if this `AbortSignal`'s `AbortController` has signaled to abort, and `false` otherwise. + */ + get aborted() { + const aborted = abortedFlags.get(this); + if (typeof aborted !== "boolean") { + throw new TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this === null ? "null" : typeof this}`); + } + return aborted; + } +} +eventTargetShim.defineEventAttribute(AbortSignal.prototype, "abort"); +/** + * Create an AbortSignal object. + */ +function createAbortSignal() { + const signal = Object.create(AbortSignal.prototype); + eventTargetShim.EventTarget.call(signal); + abortedFlags.set(signal, false); + return signal; +} +/** + * Abort a given signal. + */ +function abortSignal(signal) { + if (abortedFlags.get(signal) !== false) { + return; + } + abortedFlags.set(signal, true); + signal.dispatchEvent({ type: "abort" }); +} +/** + * Aborted flag for each instances. + */ +const abortedFlags = new WeakMap(); +// Properties should be enumerable. +Object.defineProperties(AbortSignal.prototype, { + aborted: { enumerable: true }, +}); +// `toString()` should return `"[object AbortSignal]"` +if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(AbortSignal.prototype, Symbol.toStringTag, { + configurable: true, + value: "AbortSignal", + }); +} + +/** + * The AbortController. + * @see https://dom.spec.whatwg.org/#abortcontroller + */ +class AbortController { + /** + * Initialize this controller. + */ + constructor() { + signals.set(this, createAbortSignal()); + } + /** + * Returns the `AbortSignal` object associated with this object. + */ + get signal() { + return getSignal(this); + } + /** + * Abort and signal to any observers that the associated activity is to be aborted. + */ + abort() { + abortSignal(getSignal(this)); + } +} +/** + * Associated signals. + */ +const signals = new WeakMap(); +/** + * Get the associated signal of a given controller. + */ +function getSignal(controller) { + const signal = signals.get(controller); + if (signal == null) { + throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${controller === null ? "null" : typeof controller}`); + } + return signal; +} +// Properties should be enumerable. +Object.defineProperties(AbortController.prototype, { + signal: { enumerable: true }, + abort: { enumerable: true }, +}); +if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(AbortController.prototype, Symbol.toStringTag, { + configurable: true, + value: "AbortController", + }); +} + +exports.AbortController = AbortController; +exports.AbortSignal = AbortSignal; +exports.default = AbortController; + +module.exports = AbortController +module.exports.AbortController = module.exports["default"] = AbortController +module.exports.AbortSignal = AbortSignal +//# sourceMappingURL=abort-controller.js.map diff --git a/node_modules/abort-controller/dist/abort-controller.js.map b/node_modules/abort-controller/dist/abort-controller.js.map new file mode 100644 index 0000000..cfdcafd --- /dev/null +++ b/node_modules/abort-controller/dist/abort-controller.js.map @@ -0,0 +1 @@ +{"version":3,"file":"abort-controller.js","sources":["../src/abort-signal.ts","../src/abort-controller.ts"],"sourcesContent":["import {\n // Event,\n EventTarget,\n // Type,\n defineEventAttribute,\n} from \"event-target-shim\"\n\n// Known Limitation\n// Use `any` because the type of `AbortSignal` in `lib.dom.d.ts` is wrong and\n// to make assignable our `AbortSignal` into that.\n// https://github.com/Microsoft/TSJS-lib-generator/pull/623\ntype Events = {\n abort: any // Event & Type<\"abort\">\n}\ntype EventAttributes = {\n onabort: any // Event & Type<\"abort\">\n}\n\n/**\n * The signal class.\n * @see https://dom.spec.whatwg.org/#abortsignal\n */\nexport default class AbortSignal extends EventTarget {\n /**\n * AbortSignal cannot be constructed directly.\n */\n public constructor() {\n super()\n throw new TypeError(\"AbortSignal cannot be constructed directly\")\n }\n\n /**\n * Returns `true` if this `AbortSignal`'s `AbortController` has signaled to abort, and `false` otherwise.\n */\n public get aborted(): boolean {\n const aborted = abortedFlags.get(this)\n if (typeof aborted !== \"boolean\") {\n throw new TypeError(\n `Expected 'this' to be an 'AbortSignal' object, but got ${\n this === null ? \"null\" : typeof this\n }`,\n )\n }\n return aborted\n }\n}\ndefineEventAttribute(AbortSignal.prototype, \"abort\")\n\n/**\n * Create an AbortSignal object.\n */\nexport function createAbortSignal(): AbortSignal {\n const signal = Object.create(AbortSignal.prototype)\n EventTarget.call(signal)\n abortedFlags.set(signal, false)\n return signal\n}\n\n/**\n * Abort a given signal.\n */\nexport function abortSignal(signal: AbortSignal): void {\n if (abortedFlags.get(signal) !== false) {\n return\n }\n\n abortedFlags.set(signal, true)\n signal.dispatchEvent<\"abort\">({ type: \"abort\" })\n}\n\n/**\n * Aborted flag for each instances.\n */\nconst abortedFlags = new WeakMap()\n\n// Properties should be enumerable.\nObject.defineProperties(AbortSignal.prototype, {\n aborted: { enumerable: true },\n})\n\n// `toString()` should return `\"[object AbortSignal]\"`\nif (typeof Symbol === \"function\" && typeof Symbol.toStringTag === \"symbol\") {\n Object.defineProperty(AbortSignal.prototype, Symbol.toStringTag, {\n configurable: true,\n value: \"AbortSignal\",\n })\n}\n","import AbortSignal, { abortSignal, createAbortSignal } from \"./abort-signal\"\n\n/**\n * The AbortController.\n * @see https://dom.spec.whatwg.org/#abortcontroller\n */\nexport default class AbortController {\n /**\n * Initialize this controller.\n */\n public constructor() {\n signals.set(this, createAbortSignal())\n }\n\n /**\n * Returns the `AbortSignal` object associated with this object.\n */\n public get signal(): AbortSignal {\n return getSignal(this)\n }\n\n /**\n * Abort and signal to any observers that the associated activity is to be aborted.\n */\n public abort(): void {\n abortSignal(getSignal(this))\n }\n}\n\n/**\n * Associated signals.\n */\nconst signals = new WeakMap()\n\n/**\n * Get the associated signal of a given controller.\n */\nfunction getSignal(controller: AbortController): AbortSignal {\n const signal = signals.get(controller)\n if (signal == null) {\n throw new TypeError(\n `Expected 'this' to be an 'AbortController' object, but got ${\n controller === null ? \"null\" : typeof controller\n }`,\n )\n }\n return signal\n}\n\n// Properties should be enumerable.\nObject.defineProperties(AbortController.prototype, {\n signal: { enumerable: true },\n abort: { enumerable: true },\n})\n\nif (typeof Symbol === \"function\" && typeof Symbol.toStringTag === \"symbol\") {\n Object.defineProperty(AbortController.prototype, Symbol.toStringTag, {\n configurable: true,\n value: \"AbortController\",\n })\n}\n\nexport { AbortController, AbortSignal }\n"],"names":["EventTarget","defineEventAttribute"],"mappings":"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"} \ No newline at end of file diff --git a/node_modules/abort-controller/dist/abort-controller.mjs b/node_modules/abort-controller/dist/abort-controller.mjs new file mode 100644 index 0000000..88ba22d --- /dev/null +++ b/node_modules/abort-controller/dist/abort-controller.mjs @@ -0,0 +1,118 @@ +/** + * @author Toru Nagashima + * See LICENSE file in root directory for full license. + */ +import { EventTarget, defineEventAttribute } from 'event-target-shim'; + +/** + * The signal class. + * @see https://dom.spec.whatwg.org/#abortsignal + */ +class AbortSignal extends EventTarget { + /** + * AbortSignal cannot be constructed directly. + */ + constructor() { + super(); + throw new TypeError("AbortSignal cannot be constructed directly"); + } + /** + * Returns `true` if this `AbortSignal`'s `AbortController` has signaled to abort, and `false` otherwise. + */ + get aborted() { + const aborted = abortedFlags.get(this); + if (typeof aborted !== "boolean") { + throw new TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this === null ? "null" : typeof this}`); + } + return aborted; + } +} +defineEventAttribute(AbortSignal.prototype, "abort"); +/** + * Create an AbortSignal object. + */ +function createAbortSignal() { + const signal = Object.create(AbortSignal.prototype); + EventTarget.call(signal); + abortedFlags.set(signal, false); + return signal; +} +/** + * Abort a given signal. + */ +function abortSignal(signal) { + if (abortedFlags.get(signal) !== false) { + return; + } + abortedFlags.set(signal, true); + signal.dispatchEvent({ type: "abort" }); +} +/** + * Aborted flag for each instances. + */ +const abortedFlags = new WeakMap(); +// Properties should be enumerable. +Object.defineProperties(AbortSignal.prototype, { + aborted: { enumerable: true }, +}); +// `toString()` should return `"[object AbortSignal]"` +if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(AbortSignal.prototype, Symbol.toStringTag, { + configurable: true, + value: "AbortSignal", + }); +} + +/** + * The AbortController. + * @see https://dom.spec.whatwg.org/#abortcontroller + */ +class AbortController { + /** + * Initialize this controller. + */ + constructor() { + signals.set(this, createAbortSignal()); + } + /** + * Returns the `AbortSignal` object associated with this object. + */ + get signal() { + return getSignal(this); + } + /** + * Abort and signal to any observers that the associated activity is to be aborted. + */ + abort() { + abortSignal(getSignal(this)); + } +} +/** + * Associated signals. + */ +const signals = new WeakMap(); +/** + * Get the associated signal of a given controller. + */ +function getSignal(controller) { + const signal = signals.get(controller); + if (signal == null) { + throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${controller === null ? "null" : typeof controller}`); + } + return signal; +} +// Properties should be enumerable. +Object.defineProperties(AbortController.prototype, { + signal: { enumerable: true }, + abort: { enumerable: true }, +}); +if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(AbortController.prototype, Symbol.toStringTag, { + configurable: true, + value: "AbortController", + }); +} + +export default AbortController; +export { AbortController, AbortSignal }; +//# sourceMappingURL=abort-controller.mjs.map diff --git a/node_modules/abort-controller/dist/abort-controller.mjs.map b/node_modules/abort-controller/dist/abort-controller.mjs.map new file mode 100644 index 0000000..1e8fa6b --- /dev/null +++ b/node_modules/abort-controller/dist/abort-controller.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"abort-controller.mjs","sources":["../src/abort-signal.ts","../src/abort-controller.ts"],"sourcesContent":["import {\n // Event,\n EventTarget,\n // Type,\n defineEventAttribute,\n} from \"event-target-shim\"\n\n// Known Limitation\n// Use `any` because the type of `AbortSignal` in `lib.dom.d.ts` is wrong and\n// to make assignable our `AbortSignal` into that.\n// https://github.com/Microsoft/TSJS-lib-generator/pull/623\ntype Events = {\n abort: any // Event & Type<\"abort\">\n}\ntype EventAttributes = {\n onabort: any // Event & Type<\"abort\">\n}\n\n/**\n * The signal class.\n * @see https://dom.spec.whatwg.org/#abortsignal\n */\nexport default class AbortSignal extends EventTarget {\n /**\n * AbortSignal cannot be constructed directly.\n */\n public constructor() {\n super()\n throw new TypeError(\"AbortSignal cannot be constructed directly\")\n }\n\n /**\n * Returns `true` if this `AbortSignal`'s `AbortController` has signaled to abort, and `false` otherwise.\n */\n public get aborted(): boolean {\n const aborted = abortedFlags.get(this)\n if (typeof aborted !== \"boolean\") {\n throw new TypeError(\n `Expected 'this' to be an 'AbortSignal' object, but got ${\n this === null ? \"null\" : typeof this\n }`,\n )\n }\n return aborted\n }\n}\ndefineEventAttribute(AbortSignal.prototype, \"abort\")\n\n/**\n * Create an AbortSignal object.\n */\nexport function createAbortSignal(): AbortSignal {\n const signal = Object.create(AbortSignal.prototype)\n EventTarget.call(signal)\n abortedFlags.set(signal, false)\n return signal\n}\n\n/**\n * Abort a given signal.\n */\nexport function abortSignal(signal: AbortSignal): void {\n if (abortedFlags.get(signal) !== false) {\n return\n }\n\n abortedFlags.set(signal, true)\n signal.dispatchEvent<\"abort\">({ type: \"abort\" })\n}\n\n/**\n * Aborted flag for each instances.\n */\nconst abortedFlags = new WeakMap()\n\n// Properties should be enumerable.\nObject.defineProperties(AbortSignal.prototype, {\n aborted: { enumerable: true },\n})\n\n// `toString()` should return `\"[object AbortSignal]\"`\nif (typeof Symbol === \"function\" && typeof Symbol.toStringTag === \"symbol\") {\n Object.defineProperty(AbortSignal.prototype, Symbol.toStringTag, {\n configurable: true,\n value: \"AbortSignal\",\n })\n}\n","import AbortSignal, { abortSignal, createAbortSignal } from \"./abort-signal\"\n\n/**\n * The AbortController.\n * @see https://dom.spec.whatwg.org/#abortcontroller\n */\nexport default class AbortController {\n /**\n * Initialize this controller.\n */\n public constructor() {\n signals.set(this, createAbortSignal())\n }\n\n /**\n * Returns the `AbortSignal` object associated with this object.\n */\n public get signal(): AbortSignal {\n return getSignal(this)\n }\n\n /**\n * Abort and signal to any observers that the associated activity is to be aborted.\n */\n public abort(): void {\n abortSignal(getSignal(this))\n }\n}\n\n/**\n * Associated signals.\n */\nconst signals = new WeakMap()\n\n/**\n * Get the associated signal of a given controller.\n */\nfunction getSignal(controller: AbortController): AbortSignal {\n const signal = signals.get(controller)\n if (signal == null) {\n throw new TypeError(\n `Expected 'this' to be an 'AbortController' object, but got ${\n controller === null ? \"null\" : typeof controller\n }`,\n )\n }\n return signal\n}\n\n// Properties should be enumerable.\nObject.defineProperties(AbortController.prototype, {\n signal: { enumerable: true },\n abort: { enumerable: true },\n})\n\nif (typeof Symbol === \"function\" && typeof Symbol.toStringTag === \"symbol\") {\n Object.defineProperty(AbortController.prototype, Symbol.toStringTag, {\n configurable: true,\n value: \"AbortController\",\n })\n}\n\nexport { AbortController, AbortSignal }\n"],"names":[],"mappings":"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"} \ No newline at end of file diff --git a/node_modules/abort-controller/dist/abort-controller.umd.js b/node_modules/abort-controller/dist/abort-controller.umd.js new file mode 100644 index 0000000..f643cfd --- /dev/null +++ b/node_modules/abort-controller/dist/abort-controller.umd.js @@ -0,0 +1,5 @@ +/** + * @author Toru Nagashima + * See LICENSE file in root directory for full license. + */(function(a,b){"object"==typeof exports&&"undefined"!=typeof module?b(exports):"function"==typeof define&&define.amd?define(["exports"],b):(a=a||self,b(a.AbortControllerShim={}))})(this,function(a){'use strict';function b(a){return b="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a},b(a)}function c(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}function d(a,b){for(var c,d=0;d\n * @copyright 2015 Toru Nagashima. All rights reserved.\n * See LICENSE file in root directory for full license.\n */\n/**\n * @typedef {object} PrivateData\n * @property {EventTarget} eventTarget The event target.\n * @property {{type:string}} event The original event object.\n * @property {number} eventPhase The current event phase.\n * @property {EventTarget|null} currentTarget The current event target.\n * @property {boolean} canceled The flag to prevent default.\n * @property {boolean} stopped The flag to stop propagation.\n * @property {boolean} immediateStopped The flag to stop propagation immediately.\n * @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null.\n * @property {number} timeStamp The unix time.\n * @private\n */\n\n/**\n * Private data for event wrappers.\n * @type {WeakMap}\n * @private\n */\nconst privateData = new WeakMap();\n\n/**\n * Cache for wrapper classes.\n * @type {WeakMap}\n * @private\n */\nconst wrappers = new WeakMap();\n\n/**\n * Get private data.\n * @param {Event} event The event object to get private data.\n * @returns {PrivateData} The private data of the event.\n * @private\n */\nfunction pd(event) {\n const retv = privateData.get(event);\n console.assert(\n retv != null,\n \"'this' is expected an Event object, but got\",\n event\n );\n return retv\n}\n\n/**\n * https://dom.spec.whatwg.org/#set-the-canceled-flag\n * @param data {PrivateData} private data.\n */\nfunction setCancelFlag(data) {\n if (data.passiveListener != null) {\n if (\n typeof console !== \"undefined\" &&\n typeof console.error === \"function\"\n ) {\n console.error(\n \"Unable to preventDefault inside passive event listener invocation.\",\n data.passiveListener\n );\n }\n return\n }\n if (!data.event.cancelable) {\n return\n }\n\n data.canceled = true;\n if (typeof data.event.preventDefault === \"function\") {\n data.event.preventDefault();\n }\n}\n\n/**\n * @see https://dom.spec.whatwg.org/#interface-event\n * @private\n */\n/**\n * The event wrapper.\n * @constructor\n * @param {EventTarget} eventTarget The event target of this dispatching.\n * @param {Event|{type:string}} event The original event to wrap.\n */\nfunction Event(eventTarget, event) {\n privateData.set(this, {\n eventTarget,\n event,\n eventPhase: 2,\n currentTarget: eventTarget,\n canceled: false,\n stopped: false,\n immediateStopped: false,\n passiveListener: null,\n timeStamp: event.timeStamp || Date.now(),\n });\n\n // https://heycam.github.io/webidl/#Unforgeable\n Object.defineProperty(this, \"isTrusted\", { value: false, enumerable: true });\n\n // Define accessors\n const keys = Object.keys(event);\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i];\n if (!(key in this)) {\n Object.defineProperty(this, key, defineRedirectDescriptor(key));\n }\n }\n}\n\n// Should be enumerable, but class methods are not enumerable.\nEvent.prototype = {\n /**\n * The type of this event.\n * @type {string}\n */\n get type() {\n return pd(this).event.type\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n */\n get target() {\n return pd(this).eventTarget\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n */\n get currentTarget() {\n return pd(this).currentTarget\n },\n\n /**\n * @returns {EventTarget[]} The composed path of this event.\n */\n composedPath() {\n const currentTarget = pd(this).currentTarget;\n if (currentTarget == null) {\n return []\n }\n return [currentTarget]\n },\n\n /**\n * Constant of NONE.\n * @type {number}\n */\n get NONE() {\n return 0\n },\n\n /**\n * Constant of CAPTURING_PHASE.\n * @type {number}\n */\n get CAPTURING_PHASE() {\n return 1\n },\n\n /**\n * Constant of AT_TARGET.\n * @type {number}\n */\n get AT_TARGET() {\n return 2\n },\n\n /**\n * Constant of BUBBLING_PHASE.\n * @type {number}\n */\n get BUBBLING_PHASE() {\n return 3\n },\n\n /**\n * The target of this event.\n * @type {number}\n */\n get eventPhase() {\n return pd(this).eventPhase\n },\n\n /**\n * Stop event bubbling.\n * @returns {void}\n */\n stopPropagation() {\n const data = pd(this);\n\n data.stopped = true;\n if (typeof data.event.stopPropagation === \"function\") {\n data.event.stopPropagation();\n }\n },\n\n /**\n * Stop event bubbling.\n * @returns {void}\n */\n stopImmediatePropagation() {\n const data = pd(this);\n\n data.stopped = true;\n data.immediateStopped = true;\n if (typeof data.event.stopImmediatePropagation === \"function\") {\n data.event.stopImmediatePropagation();\n }\n },\n\n /**\n * The flag to be bubbling.\n * @type {boolean}\n */\n get bubbles() {\n return Boolean(pd(this).event.bubbles)\n },\n\n /**\n * The flag to be cancelable.\n * @type {boolean}\n */\n get cancelable() {\n return Boolean(pd(this).event.cancelable)\n },\n\n /**\n * Cancel this event.\n * @returns {void}\n */\n preventDefault() {\n setCancelFlag(pd(this));\n },\n\n /**\n * The flag to indicate cancellation state.\n * @type {boolean}\n */\n get defaultPrevented() {\n return pd(this).canceled\n },\n\n /**\n * The flag to be composed.\n * @type {boolean}\n */\n get composed() {\n return Boolean(pd(this).event.composed)\n },\n\n /**\n * The unix time of this event.\n * @type {number}\n */\n get timeStamp() {\n return pd(this).timeStamp\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n * @deprecated\n */\n get srcElement() {\n return pd(this).eventTarget\n },\n\n /**\n * The flag to stop event bubbling.\n * @type {boolean}\n * @deprecated\n */\n get cancelBubble() {\n return pd(this).stopped\n },\n set cancelBubble(value) {\n if (!value) {\n return\n }\n const data = pd(this);\n\n data.stopped = true;\n if (typeof data.event.cancelBubble === \"boolean\") {\n data.event.cancelBubble = true;\n }\n },\n\n /**\n * The flag to indicate cancellation state.\n * @type {boolean}\n * @deprecated\n */\n get returnValue() {\n return !pd(this).canceled\n },\n set returnValue(value) {\n if (!value) {\n setCancelFlag(pd(this));\n }\n },\n\n /**\n * Initialize this event object. But do nothing under event dispatching.\n * @param {string} type The event type.\n * @param {boolean} [bubbles=false] The flag to be possible to bubble up.\n * @param {boolean} [cancelable=false] The flag to be possible to cancel.\n * @deprecated\n */\n initEvent() {\n // Do nothing.\n },\n};\n\n// `constructor` is not enumerable.\nObject.defineProperty(Event.prototype, \"constructor\", {\n value: Event,\n configurable: true,\n writable: true,\n});\n\n// Ensure `event instanceof window.Event` is `true`.\nif (typeof window !== \"undefined\" && typeof window.Event !== \"undefined\") {\n Object.setPrototypeOf(Event.prototype, window.Event.prototype);\n\n // Make association for wrappers.\n wrappers.set(window.Event.prototype, Event);\n}\n\n/**\n * Get the property descriptor to redirect a given property.\n * @param {string} key Property name to define property descriptor.\n * @returns {PropertyDescriptor} The property descriptor to redirect the property.\n * @private\n */\nfunction defineRedirectDescriptor(key) {\n return {\n get() {\n return pd(this).event[key]\n },\n set(value) {\n pd(this).event[key] = value;\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Get the property descriptor to call a given method property.\n * @param {string} key Property name to define property descriptor.\n * @returns {PropertyDescriptor} The property descriptor to call the method property.\n * @private\n */\nfunction defineCallDescriptor(key) {\n return {\n value() {\n const event = pd(this).event;\n return event[key].apply(event, arguments)\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Define new wrapper class.\n * @param {Function} BaseEvent The base wrapper class.\n * @param {Object} proto The prototype of the original event.\n * @returns {Function} The defined wrapper class.\n * @private\n */\nfunction defineWrapper(BaseEvent, proto) {\n const keys = Object.keys(proto);\n if (keys.length === 0) {\n return BaseEvent\n }\n\n /** CustomEvent */\n function CustomEvent(eventTarget, event) {\n BaseEvent.call(this, eventTarget, event);\n }\n\n CustomEvent.prototype = Object.create(BaseEvent.prototype, {\n constructor: { value: CustomEvent, configurable: true, writable: true },\n });\n\n // Define accessors.\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i];\n if (!(key in BaseEvent.prototype)) {\n const descriptor = Object.getOwnPropertyDescriptor(proto, key);\n const isFunc = typeof descriptor.value === \"function\";\n Object.defineProperty(\n CustomEvent.prototype,\n key,\n isFunc\n ? defineCallDescriptor(key)\n : defineRedirectDescriptor(key)\n );\n }\n }\n\n return CustomEvent\n}\n\n/**\n * Get the wrapper class of a given prototype.\n * @param {Object} proto The prototype of the original event to get its wrapper.\n * @returns {Function} The wrapper class.\n * @private\n */\nfunction getWrapper(proto) {\n if (proto == null || proto === Object.prototype) {\n return Event\n }\n\n let wrapper = wrappers.get(proto);\n if (wrapper == null) {\n wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto);\n wrappers.set(proto, wrapper);\n }\n return wrapper\n}\n\n/**\n * Wrap a given event to management a dispatching.\n * @param {EventTarget} eventTarget The event target of this dispatching.\n * @param {Object} event The event to wrap.\n * @returns {Event} The wrapper instance.\n * @private\n */\nfunction wrapEvent(eventTarget, event) {\n const Wrapper = getWrapper(Object.getPrototypeOf(event));\n return new Wrapper(eventTarget, event)\n}\n\n/**\n * Get the immediateStopped flag of a given event.\n * @param {Event} event The event to get.\n * @returns {boolean} The flag to stop propagation immediately.\n * @private\n */\nfunction isStopped(event) {\n return pd(event).immediateStopped\n}\n\n/**\n * Set the current event phase of a given event.\n * @param {Event} event The event to set current target.\n * @param {number} eventPhase New event phase.\n * @returns {void}\n * @private\n */\nfunction setEventPhase(event, eventPhase) {\n pd(event).eventPhase = eventPhase;\n}\n\n/**\n * Set the current target of a given event.\n * @param {Event} event The event to set current target.\n * @param {EventTarget|null} currentTarget New current target.\n * @returns {void}\n * @private\n */\nfunction setCurrentTarget(event, currentTarget) {\n pd(event).currentTarget = currentTarget;\n}\n\n/**\n * Set a passive listener of a given event.\n * @param {Event} event The event to set current target.\n * @param {Function|null} passiveListener New passive listener.\n * @returns {void}\n * @private\n */\nfunction setPassiveListener(event, passiveListener) {\n pd(event).passiveListener = passiveListener;\n}\n\n/**\n * @typedef {object} ListenerNode\n * @property {Function} listener\n * @property {1|2|3} listenerType\n * @property {boolean} passive\n * @property {boolean} once\n * @property {ListenerNode|null} next\n * @private\n */\n\n/**\n * @type {WeakMap>}\n * @private\n */\nconst listenersMap = new WeakMap();\n\n// Listener types\nconst CAPTURE = 1;\nconst BUBBLE = 2;\nconst ATTRIBUTE = 3;\n\n/**\n * Check whether a given value is an object or not.\n * @param {any} x The value to check.\n * @returns {boolean} `true` if the value is an object.\n */\nfunction isObject(x) {\n return x !== null && typeof x === \"object\" //eslint-disable-line no-restricted-syntax\n}\n\n/**\n * Get listeners.\n * @param {EventTarget} eventTarget The event target to get.\n * @returns {Map} The listeners.\n * @private\n */\nfunction getListeners(eventTarget) {\n const listeners = listenersMap.get(eventTarget);\n if (listeners == null) {\n throw new TypeError(\n \"'this' is expected an EventTarget object, but got another value.\"\n )\n }\n return listeners\n}\n\n/**\n * Get the property descriptor for the event attribute of a given event.\n * @param {string} eventName The event name to get property descriptor.\n * @returns {PropertyDescriptor} The property descriptor.\n * @private\n */\nfunction defineEventAttributeDescriptor(eventName) {\n return {\n get() {\n const listeners = getListeners(this);\n let node = listeners.get(eventName);\n while (node != null) {\n if (node.listenerType === ATTRIBUTE) {\n return node.listener\n }\n node = node.next;\n }\n return null\n },\n\n set(listener) {\n if (typeof listener !== \"function\" && !isObject(listener)) {\n listener = null; // eslint-disable-line no-param-reassign\n }\n const listeners = getListeners(this);\n\n // Traverse to the tail while removing old value.\n let prev = null;\n let node = listeners.get(eventName);\n while (node != null) {\n if (node.listenerType === ATTRIBUTE) {\n // Remove old value.\n if (prev !== null) {\n prev.next = node.next;\n } else if (node.next !== null) {\n listeners.set(eventName, node.next);\n } else {\n listeners.delete(eventName);\n }\n } else {\n prev = node;\n }\n\n node = node.next;\n }\n\n // Add new value.\n if (listener !== null) {\n const newNode = {\n listener,\n listenerType: ATTRIBUTE,\n passive: false,\n once: false,\n next: null,\n };\n if (prev === null) {\n listeners.set(eventName, newNode);\n } else {\n prev.next = newNode;\n }\n }\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Define an event attribute (e.g. `eventTarget.onclick`).\n * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite.\n * @param {string} eventName The event name to define.\n * @returns {void}\n */\nfunction defineEventAttribute(eventTargetPrototype, eventName) {\n Object.defineProperty(\n eventTargetPrototype,\n `on${eventName}`,\n defineEventAttributeDescriptor(eventName)\n );\n}\n\n/**\n * Define a custom EventTarget with event attributes.\n * @param {string[]} eventNames Event names for event attributes.\n * @returns {EventTarget} The custom EventTarget.\n * @private\n */\nfunction defineCustomEventTarget(eventNames) {\n /** CustomEventTarget */\n function CustomEventTarget() {\n EventTarget.call(this);\n }\n\n CustomEventTarget.prototype = Object.create(EventTarget.prototype, {\n constructor: {\n value: CustomEventTarget,\n configurable: true,\n writable: true,\n },\n });\n\n for (let i = 0; i < eventNames.length; ++i) {\n defineEventAttribute(CustomEventTarget.prototype, eventNames[i]);\n }\n\n return CustomEventTarget\n}\n\n/**\n * EventTarget.\n *\n * - This is constructor if no arguments.\n * - This is a function which returns a CustomEventTarget constructor if there are arguments.\n *\n * For example:\n *\n * class A extends EventTarget {}\n * class B extends EventTarget(\"message\") {}\n * class C extends EventTarget(\"message\", \"error\") {}\n * class D extends EventTarget([\"message\", \"error\"]) {}\n */\nfunction EventTarget() {\n /*eslint-disable consistent-return */\n if (this instanceof EventTarget) {\n listenersMap.set(this, new Map());\n return\n }\n if (arguments.length === 1 && Array.isArray(arguments[0])) {\n return defineCustomEventTarget(arguments[0])\n }\n if (arguments.length > 0) {\n const types = new Array(arguments.length);\n for (let i = 0; i < arguments.length; ++i) {\n types[i] = arguments[i];\n }\n return defineCustomEventTarget(types)\n }\n throw new TypeError(\"Cannot call a class as a function\")\n /*eslint-enable consistent-return */\n}\n\n// Should be enumerable, but class methods are not enumerable.\nEventTarget.prototype = {\n /**\n * Add a given listener to this event target.\n * @param {string} eventName The event name to add.\n * @param {Function} listener The listener to add.\n * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.\n * @returns {void}\n */\n addEventListener(eventName, listener, options) {\n if (listener == null) {\n return\n }\n if (typeof listener !== \"function\" && !isObject(listener)) {\n throw new TypeError(\"'listener' should be a function or an object.\")\n }\n\n const listeners = getListeners(this);\n const optionsIsObj = isObject(options);\n const capture = optionsIsObj\n ? Boolean(options.capture)\n : Boolean(options);\n const listenerType = capture ? CAPTURE : BUBBLE;\n const newNode = {\n listener,\n listenerType,\n passive: optionsIsObj && Boolean(options.passive),\n once: optionsIsObj && Boolean(options.once),\n next: null,\n };\n\n // Set it as the first node if the first node is null.\n let node = listeners.get(eventName);\n if (node === undefined) {\n listeners.set(eventName, newNode);\n return\n }\n\n // Traverse to the tail while checking duplication..\n let prev = null;\n while (node != null) {\n if (\n node.listener === listener &&\n node.listenerType === listenerType\n ) {\n // Should ignore duplication.\n return\n }\n prev = node;\n node = node.next;\n }\n\n // Add it.\n prev.next = newNode;\n },\n\n /**\n * Remove a given listener from this event target.\n * @param {string} eventName The event name to remove.\n * @param {Function} listener The listener to remove.\n * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.\n * @returns {void}\n */\n removeEventListener(eventName, listener, options) {\n if (listener == null) {\n return\n }\n\n const listeners = getListeners(this);\n const capture = isObject(options)\n ? Boolean(options.capture)\n : Boolean(options);\n const listenerType = capture ? CAPTURE : BUBBLE;\n\n let prev = null;\n let node = listeners.get(eventName);\n while (node != null) {\n if (\n node.listener === listener &&\n node.listenerType === listenerType\n ) {\n if (prev !== null) {\n prev.next = node.next;\n } else if (node.next !== null) {\n listeners.set(eventName, node.next);\n } else {\n listeners.delete(eventName);\n }\n return\n }\n\n prev = node;\n node = node.next;\n }\n },\n\n /**\n * Dispatch a given event.\n * @param {Event|{type:string}} event The event to dispatch.\n * @returns {boolean} `false` if canceled.\n */\n dispatchEvent(event) {\n if (event == null || typeof event.type !== \"string\") {\n throw new TypeError('\"event.type\" should be a string.')\n }\n\n // If listeners aren't registered, terminate.\n const listeners = getListeners(this);\n const eventName = event.type;\n let node = listeners.get(eventName);\n if (node == null) {\n return true\n }\n\n // Since we cannot rewrite several properties, so wrap object.\n const wrappedEvent = wrapEvent(this, event);\n\n // This doesn't process capturing phase and bubbling phase.\n // This isn't participating in a tree.\n let prev = null;\n while (node != null) {\n // Remove this listener if it's once\n if (node.once) {\n if (prev !== null) {\n prev.next = node.next;\n } else if (node.next !== null) {\n listeners.set(eventName, node.next);\n } else {\n listeners.delete(eventName);\n }\n } else {\n prev = node;\n }\n\n // Call this listener\n setPassiveListener(\n wrappedEvent,\n node.passive ? node.listener : null\n );\n if (typeof node.listener === \"function\") {\n try {\n node.listener.call(this, wrappedEvent);\n } catch (err) {\n if (\n typeof console !== \"undefined\" &&\n typeof console.error === \"function\"\n ) {\n console.error(err);\n }\n }\n } else if (\n node.listenerType !== ATTRIBUTE &&\n typeof node.listener.handleEvent === \"function\"\n ) {\n node.listener.handleEvent(wrappedEvent);\n }\n\n // Break if `event.stopImmediatePropagation` was called.\n if (isStopped(wrappedEvent)) {\n break\n }\n\n node = node.next;\n }\n setPassiveListener(wrappedEvent, null);\n setEventPhase(wrappedEvent, 0);\n setCurrentTarget(wrappedEvent, null);\n\n return !wrappedEvent.defaultPrevented\n },\n};\n\n// `constructor` is not enumerable.\nObject.defineProperty(EventTarget.prototype, \"constructor\", {\n value: EventTarget,\n configurable: true,\n writable: true,\n});\n\n// Ensure `eventTarget instanceof window.EventTarget` is `true`.\nif (\n typeof window !== \"undefined\" &&\n typeof window.EventTarget !== \"undefined\"\n) {\n Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype);\n}\n\nexport default EventTarget;\nexport { defineEventAttribute, EventTarget };\n//# sourceMappingURL=event-target-shim.mjs.map\n","import {\n // Event,\n EventTarget,\n // Type,\n defineEventAttribute,\n} from \"event-target-shim\"\n\n// Known Limitation\n// Use `any` because the type of `AbortSignal` in `lib.dom.d.ts` is wrong and\n// to make assignable our `AbortSignal` into that.\n// https://github.com/Microsoft/TSJS-lib-generator/pull/623\ntype Events = {\n abort: any // Event & Type<\"abort\">\n}\ntype EventAttributes = {\n onabort: any // Event & Type<\"abort\">\n}\n\n/**\n * The signal class.\n * @see https://dom.spec.whatwg.org/#abortsignal\n */\nexport default class AbortSignal extends EventTarget {\n /**\n * AbortSignal cannot be constructed directly.\n */\n public constructor() {\n super()\n throw new TypeError(\"AbortSignal cannot be constructed directly\")\n }\n\n /**\n * Returns `true` if this `AbortSignal`'s `AbortController` has signaled to abort, and `false` otherwise.\n */\n public get aborted(): boolean {\n const aborted = abortedFlags.get(this)\n if (typeof aborted !== \"boolean\") {\n throw new TypeError(\n `Expected 'this' to be an 'AbortSignal' object, but got ${\n this === null ? \"null\" : typeof this\n }`,\n )\n }\n return aborted\n }\n}\ndefineEventAttribute(AbortSignal.prototype, \"abort\")\n\n/**\n * Create an AbortSignal object.\n */\nexport function createAbortSignal(): AbortSignal {\n const signal = Object.create(AbortSignal.prototype)\n EventTarget.call(signal)\n abortedFlags.set(signal, false)\n return signal\n}\n\n/**\n * Abort a given signal.\n */\nexport function abortSignal(signal: AbortSignal): void {\n if (abortedFlags.get(signal) !== false) {\n return\n }\n\n abortedFlags.set(signal, true)\n signal.dispatchEvent<\"abort\">({ type: \"abort\" })\n}\n\n/**\n * Aborted flag for each instances.\n */\nconst abortedFlags = new WeakMap()\n\n// Properties should be enumerable.\nObject.defineProperties(AbortSignal.prototype, {\n aborted: { enumerable: true },\n})\n\n// `toString()` should return `\"[object AbortSignal]\"`\nif (typeof Symbol === \"function\" && typeof Symbol.toStringTag === \"symbol\") {\n Object.defineProperty(AbortSignal.prototype, Symbol.toStringTag, {\n configurable: true,\n value: \"AbortSignal\",\n })\n}\n","import AbortSignal, { abortSignal, createAbortSignal } from \"./abort-signal\"\n\n/**\n * The AbortController.\n * @see https://dom.spec.whatwg.org/#abortcontroller\n */\nexport default class AbortController {\n /**\n * Initialize this controller.\n */\n public constructor() {\n signals.set(this, createAbortSignal())\n }\n\n /**\n * Returns the `AbortSignal` object associated with this object.\n */\n public get signal(): AbortSignal {\n return getSignal(this)\n }\n\n /**\n * Abort and signal to any observers that the associated activity is to be aborted.\n */\n public abort(): void {\n abortSignal(getSignal(this))\n }\n}\n\n/**\n * Associated signals.\n */\nconst signals = new WeakMap()\n\n/**\n * Get the associated signal of a given controller.\n */\nfunction getSignal(controller: AbortController): AbortSignal {\n const signal = signals.get(controller)\n if (signal == null) {\n throw new TypeError(\n `Expected 'this' to be an 'AbortController' object, but got ${\n controller === null ? \"null\" : typeof controller\n }`,\n )\n }\n return signal\n}\n\n// Properties should be enumerable.\nObject.defineProperties(AbortController.prototype, {\n signal: { enumerable: true },\n abort: { enumerable: true },\n})\n\nif (typeof Symbol === \"function\" && typeof Symbol.toStringTag === \"symbol\") {\n Object.defineProperty(AbortController.prototype, Symbol.toStringTag, {\n configurable: true,\n value: \"AbortController\",\n })\n}\n\nexport { AbortController, AbortSignal }\n"],"names":["pd","event","retv","privateData","get","console","assert","setCancelFlag","data","passiveListener","cancelable","canceled","preventDefault","error","Event","eventTarget","set","eventPhase","currentTarget","stopped","immediateStopped","timeStamp","Date","now","Object","defineProperty","value","enumerable","key","keys","i","length","defineRedirectDescriptor","configurable","defineCallDescriptor","apply","arguments","defineWrapper","BaseEvent","proto","CustomEvent","call","prototype","create","constructor","writable","descriptor","getOwnPropertyDescriptor","isFunc","getWrapper","wrapper","wrappers","getPrototypeOf","wrapEvent","Wrapper","isStopped","setEventPhase","setCurrentTarget","setPassiveListener","createAbortSignal","signal","AbortSignal","EventTarget","abortedFlags","abortSignal","dispatchEvent","type","getSignal","controller","signals","TypeError","WeakMap","target","composedPath","NONE","CAPTURING_PHASE","AT_TARGET","BUBBLING_PHASE","stopPropagation","stopImmediatePropagation","bubbles","defaultPrevented","composed","srcElement","cancelBubble","returnValue","initEvent","window","setPrototypeOf","aborted","defineEventAttribute","defineProperties","Symbol","_typeof","toStringTag","AbortController","abort"],"mappings":"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"} \ No newline at end of file diff --git a/node_modules/abort-controller/package.json b/node_modules/abort-controller/package.json new file mode 100644 index 0000000..fad7891 --- /dev/null +++ b/node_modules/abort-controller/package.json @@ -0,0 +1,127 @@ +{ + "_from": "abort-controller@^3.0.0", + "_id": "abort-controller@3.0.0", + "_inBundle": false, + "_integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", + "_location": "/abort-controller", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "abort-controller@^3.0.0", + "name": "abort-controller", + "escapedName": "abort-controller", + "rawSpec": "^3.0.0", + "saveSpec": null, + "fetchSpec": "^3.0.0" + }, + "_requiredBy": [ + "/gaxios", + "/gcp-metadata/gaxios", + "/gtoken/gaxios" + ], + "_resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", + "_shasum": "eaf54d53b62bae4138e809ca225c8439a6efb392", + "_spec": "abort-controller@^3.0.0", + "_where": "/Users/cday/Code/zendesk/fetch-build-from-gcb/node_modules/gaxios", + "author": { + "name": "Toru Nagashima", + "url": "https://github.com/mysticatea" + }, + "browser": "./browser.js", + "bugs": { + "url": "https://github.com/mysticatea/abort-controller/issues" + }, + "bundleDependencies": false, + "dependencies": { + "event-target-shim": "^5.0.0" + }, + "deprecated": false, + "description": "An implementation of WHATWG AbortController interface.", + "devDependencies": { + "@babel/core": "^7.2.2", + "@babel/plugin-transform-modules-commonjs": "^7.2.0", + "@babel/preset-env": "^7.3.0", + "@babel/register": "^7.0.0", + "@mysticatea/eslint-plugin": "^8.0.1", + "@mysticatea/spy": "^0.1.2", + "@types/mocha": "^5.2.5", + "@types/node": "^10.12.18", + "assert": "^1.4.1", + "codecov": "^3.1.0", + "dts-bundle-generator": "^2.0.0", + "eslint": "^5.12.1", + "karma": "^3.1.4", + "karma-chrome-launcher": "^2.2.0", + "karma-coverage": "^1.1.2", + "karma-firefox-launcher": "^1.1.0", + "karma-growl-reporter": "^1.0.0", + "karma-ie-launcher": "^1.0.0", + "karma-mocha": "^1.3.0", + "karma-rollup-preprocessor": "^7.0.0-rc.2", + "mocha": "^5.2.0", + "npm-run-all": "^4.1.5", + "nyc": "^13.1.0", + "opener": "^1.5.1", + "rimraf": "^2.6.3", + "rollup": "^1.1.2", + "rollup-plugin-babel": "^4.3.2", + "rollup-plugin-babel-minify": "^7.0.0", + "rollup-plugin-commonjs": "^9.2.0", + "rollup-plugin-node-resolve": "^4.0.0", + "rollup-plugin-sourcemaps": "^0.4.2", + "rollup-plugin-typescript": "^1.0.0", + "rollup-watch": "^4.3.1", + "ts-node": "^8.0.1", + "type-tester": "^1.0.0", + "typescript": "^3.2.4" + }, + "engines": { + "node": ">=6.5" + }, + "files": [ + "dist", + "polyfill.*", + "browser.*" + ], + "homepage": "https://github.com/mysticatea/abort-controller#readme", + "keywords": [ + "w3c", + "whatwg", + "event", + "events", + "abort", + "cancel", + "abortcontroller", + "abortsignal", + "controller", + "signal", + "shim" + ], + "license": "MIT", + "main": "dist/abort-controller", + "name": "abort-controller", + "repository": { + "type": "git", + "url": "git+https://github.com/mysticatea/abort-controller.git" + }, + "scripts": { + "build": "run-s -s build:*", + "build:dts": "dts-bundle-generator -o dist/abort-controller.d.ts src/abort-controller.ts && ts-node scripts/fix-dts", + "build:rollup": "rollup -c", + "clean": "rimraf .nyc_output coverage", + "codecov": "codecov", + "coverage": "opener coverage/lcov-report/index.html", + "lint": "eslint . --ext .ts", + "postversion": "git push && git push --tags", + "preversion": "npm test", + "test": "run-s -s lint test:*", + "test:karma": "karma start --single-run", + "test:mocha": "nyc mocha test/*.ts", + "version": "npm run -s build && git add dist/*", + "watch": "run-p -s watch:*", + "watch:karma": "karma start --watch", + "watch:mocha": "mocha test/*.ts --require ts-node/register --watch-extensions ts --watch --growl" + }, + "version": "3.0.0" +} diff --git a/node_modules/abort-controller/polyfill.js b/node_modules/abort-controller/polyfill.js new file mode 100644 index 0000000..3ca8923 --- /dev/null +++ b/node_modules/abort-controller/polyfill.js @@ -0,0 +1,21 @@ +/*globals require, self, window */ +"use strict" + +const ac = require("./dist/abort-controller") + +/*eslint-disable @mysticatea/prettier */ +const g = + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : + typeof global !== "undefined" ? global : + /* otherwise */ undefined +/*eslint-enable @mysticatea/prettier */ + +if (g) { + if (typeof g.AbortController === "undefined") { + g.AbortController = ac.AbortController + } + if (typeof g.AbortSignal === "undefined") { + g.AbortSignal = ac.AbortSignal + } +} diff --git a/node_modules/abort-controller/polyfill.mjs b/node_modules/abort-controller/polyfill.mjs new file mode 100644 index 0000000..0602a64 --- /dev/null +++ b/node_modules/abort-controller/polyfill.mjs @@ -0,0 +1,19 @@ +/*globals self, window */ +import * as ac from "./dist/abort-controller" + +/*eslint-disable @mysticatea/prettier */ +const g = + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : + typeof global !== "undefined" ? global : + /* otherwise */ undefined +/*eslint-enable @mysticatea/prettier */ + +if (g) { + if (typeof g.AbortController === "undefined") { + g.AbortController = ac.AbortController + } + if (typeof g.AbortSignal === "undefined") { + g.AbortSignal = ac.AbortSignal + } +} diff --git a/node_modules/agent-base/README.md b/node_modules/agent-base/README.md new file mode 100644 index 0000000..d791f00 --- /dev/null +++ b/node_modules/agent-base/README.md @@ -0,0 +1,145 @@ +agent-base +========== +### Turn a function into an [`http.Agent`][http.Agent] instance +[![Build Status](https://github.com/TooTallNate/node-agent-base/workflows/Node%20CI/badge.svg)](https://github.com/TooTallNate/node-agent-base/actions?workflow=Node+CI) + +This module provides an `http.Agent` generator. That is, you pass it an async +callback function, and it returns a new `http.Agent` instance that will invoke the +given callback function when sending outbound HTTP requests. + +#### Some subclasses: + +Here's some more interesting uses of `agent-base`. +Send a pull request to list yours! + + * [`http-proxy-agent`][http-proxy-agent]: An HTTP(s) proxy `http.Agent` implementation for HTTP endpoints + * [`https-proxy-agent`][https-proxy-agent]: An HTTP(s) proxy `http.Agent` implementation for HTTPS endpoints + * [`pac-proxy-agent`][pac-proxy-agent]: A PAC file proxy `http.Agent` implementation for HTTP and HTTPS + * [`socks-proxy-agent`][socks-proxy-agent]: A SOCKS (v4a) proxy `http.Agent` implementation for HTTP and HTTPS + + +Installation +------------ + +Install with `npm`: + +``` bash +$ npm install agent-base +``` + + +Example +------- + +Here's a minimal example that creates a new `net.Socket` connection to the server +for every HTTP request (i.e. the equivalent of `agent: false` option): + +```js +var net = require('net'); +var tls = require('tls'); +var url = require('url'); +var http = require('http'); +var agent = require('agent-base'); + +var endpoint = 'http://nodejs.org/api/'; +var parsed = url.parse(endpoint); + +// This is the important part! +parsed.agent = agent(function (req, opts) { + var socket; + // `secureEndpoint` is true when using the https module + if (opts.secureEndpoint) { + socket = tls.connect(opts); + } else { + socket = net.connect(opts); + } + return socket; +}); + +// Everything else works just like normal... +http.get(parsed, function (res) { + console.log('"response" event!', res.headers); + res.pipe(process.stdout); +}); +``` + +Returning a Promise or using an `async` function is also supported: + +```js +agent(async function (req, opts) { + await sleep(1000); + // etc… +}); +``` + +Return another `http.Agent` instance to "pass through" the responsibility +for that HTTP request to that agent: + +```js +agent(function (req, opts) { + return opts.secureEndpoint ? https.globalAgent : http.globalAgent; +}); +``` + + +API +--- + +## Agent(Function callback[, Object options]) → [http.Agent][] + +Creates a base `http.Agent` that will execute the callback function `callback` +for every HTTP request that it is used as the `agent` for. The callback function +is responsible for creating a `stream.Duplex` instance of some kind that will be +used as the underlying socket in the HTTP request. + +The `options` object accepts the following properties: + + * `timeout` - Number - Timeout for the `callback()` function in milliseconds. Defaults to Infinity (optional). + +The callback function should have the following signature: + +### callback(http.ClientRequest req, Object options, Function cb) → undefined + +The ClientRequest `req` can be accessed to read request headers and +and the path, etc. The `options` object contains the options passed +to the `http.request()`/`https.request()` function call, and is formatted +to be directly passed to `net.connect()`/`tls.connect()`, or however +else you want a Socket to be created. Pass the created socket to +the callback function `cb` once created, and the HTTP request will +continue to proceed. + +If the `https` module is used to invoke the HTTP request, then the +`secureEndpoint` property on `options` _will be set to `true`_. + + +License +------- + +(The MIT License) + +Copyright (c) 2013 Nathan Rajlich <nathan@tootallnate.net> + +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. + +[http-proxy-agent]: https://github.com/TooTallNate/node-http-proxy-agent +[https-proxy-agent]: https://github.com/TooTallNate/node-https-proxy-agent +[pac-proxy-agent]: https://github.com/TooTallNate/node-pac-proxy-agent +[socks-proxy-agent]: https://github.com/TooTallNate/node-socks-proxy-agent +[http.Agent]: https://nodejs.org/api/http.html#http_class_http_agent diff --git a/node_modules/agent-base/dist/src/index.d.ts b/node_modules/agent-base/dist/src/index.d.ts new file mode 100644 index 0000000..e44a88a --- /dev/null +++ b/node_modules/agent-base/dist/src/index.d.ts @@ -0,0 +1,73 @@ +/// +import net from 'net'; +import http from 'http'; +import https from 'https'; +import { Duplex } from 'stream'; +import { EventEmitter } from 'events'; +declare function createAgent(opts?: createAgent.AgentOptions): createAgent.Agent; +declare function createAgent(callback: createAgent.AgentCallback, opts?: createAgent.AgentOptions): createAgent.Agent; +declare namespace createAgent { + interface ClientRequest extends http.ClientRequest { + _last?: boolean; + _hadError?: boolean; + method: string; + } + interface AgentRequestOptions { + host?: string; + path?: string; + port: number; + } + interface HttpRequestOptions extends AgentRequestOptions, Omit { + secureEndpoint: false; + } + interface HttpsRequestOptions extends AgentRequestOptions, Omit { + secureEndpoint: true; + } + type RequestOptions = HttpRequestOptions | HttpsRequestOptions; + type AgentLike = Pick | http.Agent; + type AgentCallbackReturn = Duplex | AgentLike; + type AgentCallbackCallback = (err: Error | null | undefined, socket: createAgent.AgentCallbackReturn) => void; + type AgentCallbackPromise = (req: createAgent.ClientRequest, opts: createAgent.RequestOptions) => createAgent.AgentCallbackReturn | Promise; + type AgentCallback = typeof Agent.prototype.callback; + type AgentOptions = { + timeout?: number; + }; + /** + * Base `http.Agent` implementation. + * No pooling/keep-alive is implemented by default. + * + * @param {Function} callback + * @api public + */ + class Agent extends EventEmitter { + timeout: number | null; + maxFreeSockets: number; + maxSockets: number; + sockets: { + [key: string]: net.Socket[]; + }; + requests: { + [key: string]: http.IncomingMessage[]; + }; + private promisifiedCallback?; + private explicitDefaultPort?; + private explicitProtocol?; + constructor(callback?: createAgent.AgentCallback | createAgent.AgentOptions, _opts?: createAgent.AgentOptions); + get defaultPort(): number; + set defaultPort(v: number); + get protocol(): string; + set protocol(v: string); + callback(req: createAgent.ClientRequest, opts: createAgent.RequestOptions, fn: createAgent.AgentCallbackCallback): void; + callback(req: createAgent.ClientRequest, opts: createAgent.RequestOptions): createAgent.AgentCallbackReturn | Promise; + /** + * Called by node-core's "_http_client.js" module when creating + * a new HTTP request with this Agent instance. + * + * @api public + */ + addRequest(req: ClientRequest, _opts: RequestOptions): void; + freeSocket(socket: net.Socket, opts: AgentOptions): void; + destroy(): void; + } +} +export = createAgent; diff --git a/node_modules/agent-base/dist/src/index.js b/node_modules/agent-base/dist/src/index.js new file mode 100644 index 0000000..1e7b8c2 --- /dev/null +++ b/node_modules/agent-base/dist/src/index.js @@ -0,0 +1,200 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +const events_1 = require("events"); +const debug_1 = __importDefault(require("debug")); +const promisify_1 = __importDefault(require("./promisify")); +const debug = debug_1.default('agent-base'); +function isAgent(v) { + return Boolean(v) && typeof v.addRequest === 'function'; +} +function isSecureEndpoint() { + const { stack } = new Error(); + if (typeof stack !== 'string') + return false; + return stack.split('\n').some(l => l.indexOf('(https.js:') !== -1); +} +function createAgent(callback, opts) { + return new createAgent.Agent(callback, opts); +} +(function (createAgent) { + /** + * Base `http.Agent` implementation. + * No pooling/keep-alive is implemented by default. + * + * @param {Function} callback + * @api public + */ + class Agent extends events_1.EventEmitter { + constructor(callback, _opts) { + super(); + let opts = _opts; + if (typeof callback === 'function') { + this.callback = callback; + } + else if (callback) { + opts = callback; + } + // Timeout for the socket to be returned from the callback + this.timeout = null; + if (opts && typeof opts.timeout === 'number') { + this.timeout = opts.timeout; + } + // These aren't actually used by `agent-base`, but are required + // for the TypeScript definition files in `@types/node` :/ + this.maxFreeSockets = 1; + this.maxSockets = 1; + this.sockets = {}; + this.requests = {}; + } + get defaultPort() { + if (typeof this.explicitDefaultPort === 'number') { + return this.explicitDefaultPort; + } + return isSecureEndpoint() ? 443 : 80; + } + set defaultPort(v) { + this.explicitDefaultPort = v; + } + get protocol() { + if (typeof this.explicitProtocol === 'string') { + return this.explicitProtocol; + } + return isSecureEndpoint() ? 'https:' : 'http:'; + } + set protocol(v) { + this.explicitProtocol = v; + } + callback(req, opts, fn) { + throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`'); + } + /** + * Called by node-core's "_http_client.js" module when creating + * a new HTTP request with this Agent instance. + * + * @api public + */ + addRequest(req, _opts) { + const opts = Object.assign({}, _opts); + if (typeof opts.secureEndpoint !== 'boolean') { + opts.secureEndpoint = isSecureEndpoint(); + } + if (opts.host == null) { + opts.host = 'localhost'; + } + if (opts.port == null) { + opts.port = opts.secureEndpoint ? 443 : 80; + } + if (opts.protocol == null) { + opts.protocol = opts.secureEndpoint ? 'https:' : 'http:'; + } + if (opts.host && opts.path) { + // If both a `host` and `path` are specified then it's most + // likely the result of a `url.parse()` call... we need to + // remove the `path` portion so that `net.connect()` doesn't + // attempt to open that as a unix socket file. + delete opts.path; + } + delete opts.agent; + delete opts.hostname; + delete opts._defaultAgent; + delete opts.defaultPort; + delete opts.createConnection; + // Hint to use "Connection: close" + // XXX: non-documented `http` module API :( + req._last = true; + req.shouldKeepAlive = false; + let timedOut = false; + let timeoutId = null; + const timeoutMs = opts.timeout || this.timeout; + const onerror = (err) => { + if (req._hadError) + return; + req.emit('error', err); + // For Safety. Some additional errors might fire later on + // and we need to make sure we don't double-fire the error event. + req._hadError = true; + }; + const ontimeout = () => { + timeoutId = null; + timedOut = true; + const err = new Error(`A "socket" was not created for HTTP request before ${timeoutMs}ms`); + err.code = 'ETIMEOUT'; + onerror(err); + }; + const callbackError = (err) => { + if (timedOut) + return; + if (timeoutId !== null) { + clearTimeout(timeoutId); + timeoutId = null; + } + onerror(err); + }; + const onsocket = (socket) => { + if (timedOut) + return; + if (timeoutId != null) { + clearTimeout(timeoutId); + timeoutId = null; + } + if (isAgent(socket)) { + // `socket` is actually an `http.Agent` instance, so + // relinquish responsibility for this `req` to the Agent + // from here on + debug('Callback returned another Agent instance %o', socket.constructor.name); + socket.addRequest(req, opts); + return; + } + if (socket) { + socket.once('free', () => { + this.freeSocket(socket, opts); + }); + req.onSocket(socket); + return; + } + const err = new Error(`no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\``); + onerror(err); + }; + if (typeof this.callback !== 'function') { + onerror(new Error('`callback` is not defined')); + return; + } + if (!this.promisifiedCallback) { + if (this.callback.length >= 3) { + debug('Converting legacy callback function to promise'); + this.promisifiedCallback = promisify_1.default(this.callback); + } + else { + this.promisifiedCallback = this.callback; + } + } + if (typeof timeoutMs === 'number' && timeoutMs > 0) { + timeoutId = setTimeout(ontimeout, timeoutMs); + } + if ('port' in opts && typeof opts.port !== 'number') { + opts.port = Number(opts.port); + } + try { + debug('Resolving socket for %o request: %o', opts.protocol, `${req.method} ${req.path}`); + Promise.resolve(this.promisifiedCallback(req, opts)).then(onsocket, callbackError); + } + catch (err) { + Promise.reject(err).catch(callbackError); + } + } + freeSocket(socket, opts) { + debug('Freeing socket %o %o', socket.constructor.name, opts); + socket.destroy(); + } + destroy() { + debug('Destroying agent %o', this.constructor.name); + } + } + createAgent.Agent = Agent; + // So that `instanceof` works correctly + createAgent.prototype = createAgent.Agent.prototype; +})(createAgent || (createAgent = {})); +module.exports = createAgent; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/agent-base/dist/src/index.js.map b/node_modules/agent-base/dist/src/index.js.map new file mode 100644 index 0000000..ccfaa75 --- /dev/null +++ b/node_modules/agent-base/dist/src/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"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"} \ No newline at end of file diff --git a/node_modules/agent-base/dist/src/promisify.d.ts b/node_modules/agent-base/dist/src/promisify.d.ts new file mode 100644 index 0000000..0268869 --- /dev/null +++ b/node_modules/agent-base/dist/src/promisify.d.ts @@ -0,0 +1,4 @@ +import { ClientRequest, RequestOptions, AgentCallbackCallback, AgentCallbackPromise } from './index'; +declare type LegacyCallback = (req: ClientRequest, opts: RequestOptions, fn: AgentCallbackCallback) => void; +export default function promisify(fn: LegacyCallback): AgentCallbackPromise; +export {}; diff --git a/node_modules/agent-base/dist/src/promisify.js b/node_modules/agent-base/dist/src/promisify.js new file mode 100644 index 0000000..b2f6132 --- /dev/null +++ b/node_modules/agent-base/dist/src/promisify.js @@ -0,0 +1,18 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +function promisify(fn) { + return function (req, opts) { + return new Promise((resolve, reject) => { + fn.call(this, req, opts, (err, rtn) => { + if (err) { + reject(err); + } + else { + resolve(rtn); + } + }); + }); + }; +} +exports.default = promisify; +//# sourceMappingURL=promisify.js.map \ No newline at end of file diff --git a/node_modules/agent-base/dist/src/promisify.js.map b/node_modules/agent-base/dist/src/promisify.js.map new file mode 100644 index 0000000..4bff9bf --- /dev/null +++ b/node_modules/agent-base/dist/src/promisify.js.map @@ -0,0 +1 @@ +{"version":3,"file":"promisify.js","sourceRoot":"","sources":["../../src/promisify.ts"],"names":[],"mappings":";;AAeA,SAAwB,SAAS,CAAC,EAAkB;IACnD,OAAO,UAAsB,GAAkB,EAAE,IAAoB;QACpE,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;YACtC,EAAE,CAAC,IAAI,CACN,IAAI,EACJ,GAAG,EACH,IAAI,EACJ,CAAC,GAA6B,EAAE,GAAyB,EAAE,EAAE;gBAC5D,IAAI,GAAG,EAAE;oBACR,MAAM,CAAC,GAAG,CAAC,CAAC;iBACZ;qBAAM;oBACN,OAAO,CAAC,GAAG,CAAC,CAAC;iBACb;YACF,CAAC,CACD,CAAC;QACH,CAAC,CAAC,CAAC;IACJ,CAAC,CAAC;AACH,CAAC;AAjBD,4BAiBC"} \ No newline at end of file diff --git a/node_modules/agent-base/package.json b/node_modules/agent-base/package.json new file mode 100644 index 0000000..e138eb3 --- /dev/null +++ b/node_modules/agent-base/package.json @@ -0,0 +1,91 @@ +{ + "_from": "agent-base@6", + "_id": "agent-base@6.0.0", + "_inBundle": false, + "_integrity": "sha512-j1Q7cSCqN+AwrmDd+pzgqc0/NpC655x2bUf5ZjRIO77DcNBFmh+OgRNzF6OKdCC9RSCb19fGd99+bhXFdkRNqw==", + "_location": "/agent-base", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "agent-base@6", + "name": "agent-base", + "escapedName": "agent-base", + "rawSpec": "6", + "saveSpec": null, + "fetchSpec": "6" + }, + "_requiredBy": [ + "/https-proxy-agent" + ], + "_resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.0.tgz", + "_shasum": "5d0101f19bbfaed39980b22ae866de153b93f09a", + "_spec": "agent-base@6", + "_where": "/Users/cday/Code/zendesk/fetch-build-from-gcb/node_modules/https-proxy-agent", + "author": { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net", + "url": "http://n8.io/" + }, + "bugs": { + "url": "https://github.com/TooTallNate/node-agent-base/issues" + }, + "bundleDependencies": false, + "dependencies": { + "debug": "4" + }, + "deprecated": false, + "description": "Turn a function into an `http.Agent` instance", + "devDependencies": { + "@types/debug": "4", + "@types/mocha": "^5.2.7", + "@types/node": "^12.12.17", + "@types/ws": "^6.0.3", + "@typescript-eslint/eslint-plugin": "1.6.0", + "@typescript-eslint/parser": "1.1.0", + "async-listen": "^1.2.0", + "cpy-cli": "^2.0.0", + "eslint": "5.16.0", + "eslint-config-airbnb": "17.1.0", + "eslint-config-prettier": "4.1.0", + "eslint-import-resolver-typescript": "1.1.1", + "eslint-plugin-import": "2.16.0", + "eslint-plugin-jsx-a11y": "6.2.1", + "eslint-plugin-react": "7.12.4", + "mocha": "^6.2.0", + "rimraf": "^3.0.0", + "typescript": "^3.5.3", + "ws": "^3.0.0" + }, + "engines": { + "node": ">= 6.0.0" + }, + "files": [ + "dist/src" + ], + "homepage": "https://github.com/TooTallNate/node-agent-base#readme", + "keywords": [ + "http", + "agent", + "base", + "barebones", + "https" + ], + "license": "MIT", + "main": "dist/src/index", + "name": "agent-base", + "repository": { + "type": "git", + "url": "git://github.com/TooTallNate/node-agent-base.git" + }, + "scripts": { + "build": "tsc", + "postbuild": "cpy --parents src test '!**/*.ts' dist", + "prebuild": "rimraf dist", + "prepublishOnly": "npm run build", + "test": "mocha --reporter spec dist/test/*.js", + "test-lint": "eslint src --ext .js,.ts" + }, + "typings": "dist/src/index", + "version": "6.0.0" +} diff --git a/node_modules/arrify/index.d.ts b/node_modules/arrify/index.d.ts new file mode 100644 index 0000000..bfd0cf5 --- /dev/null +++ b/node_modules/arrify/index.d.ts @@ -0,0 +1,38 @@ +/** +Convert a value to an array. + +_Supplying `null` or `undefined` results in an empty array._ + +@example +``` +import arrify = require('arrify'); + +arrify('🦄'); +//=> ['🦄'] + +arrify(['🦄']); +//=> ['🦄'] + +arrify(new Set(['🦄'])); +//=> ['🦄'] + +arrify(null); +//=> [] + +arrify(undefined); +//=> [] +``` +*/ +declare function arrify( + value: ValueType +): ValueType extends (null | undefined) + ? [] + : ValueType extends string + ? [string] + : ValueType extends ReadonlyArray // TODO: Use 'readonly unknown[]' in the next major version + ? ValueType + : ValueType extends Iterable + ? T[] + : [ValueType]; + +export = arrify; diff --git a/node_modules/arrify/index.js b/node_modules/arrify/index.js new file mode 100644 index 0000000..49a5c9a --- /dev/null +++ b/node_modules/arrify/index.js @@ -0,0 +1,23 @@ +'use strict'; + +const arrify = value => { + if (value === null || value === undefined) { + return []; + } + + if (Array.isArray(value)) { + return value; + } + + if (typeof value === 'string') { + return [value]; + } + + if (typeof value[Symbol.iterator] === 'function') { + return [...value]; + } + + return [value]; +}; + +module.exports = arrify; diff --git a/node_modules/arrify/license b/node_modules/arrify/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/arrify/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. diff --git a/node_modules/arrify/package.json b/node_modules/arrify/package.json new file mode 100644 index 0000000..fe1d587 --- /dev/null +++ b/node_modules/arrify/package.json @@ -0,0 +1,67 @@ +{ + "_from": "arrify@^2.0.0", + "_id": "arrify@2.0.1", + "_inBundle": false, + "_integrity": "sha512-3duEwti880xqi4eAMN8AyR4a0ByT90zoYdLlevfrvU43vb0YZwZVfxOgxWrLXXXpyugL0hNZc9G6BiB5B3nUug==", + "_location": "/arrify", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "arrify@^2.0.0", + "name": "arrify", + "escapedName": "arrify", + "rawSpec": "^2.0.0", + "saveSpec": null, + "fetchSpec": "^2.0.0" + }, + "_requiredBy": [ + "/google-auth-library" + ], + "_resolved": "https://registry.npmjs.org/arrify/-/arrify-2.0.1.tgz", + "_shasum": "c9655e9331e0abcd588d2a7cad7e9956f66701fa", + "_spec": "arrify@^2.0.0", + "_where": "/Users/cday/Code/zendesk/fetch-build-from-gcb/node_modules/google-auth-library", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/arrify/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Convert a value to an array", + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.2", + "xo": "^0.24.0" + }, + "engines": { + "node": ">=8" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "homepage": "https://github.com/sindresorhus/arrify#readme", + "keywords": [ + "array", + "arrify", + "arrayify", + "convert", + "value", + "ensure" + ], + "license": "MIT", + "name": "arrify", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/arrify.git" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "version": "2.0.1" +} diff --git a/node_modules/arrify/readme.md b/node_modules/arrify/readme.md new file mode 100644 index 0000000..b3dfc83 --- /dev/null +++ b/node_modules/arrify/readme.md @@ -0,0 +1,39 @@ +# arrify [![Build Status](https://travis-ci.org/sindresorhus/arrify.svg?branch=master)](https://travis-ci.org/sindresorhus/arrify) + +> Convert a value to an array + + +## Install + +``` +$ npm install arrify +``` + + +## Usage + +```js +const arrify = require('arrify'); + +arrify('🦄'); +//=> ['🦄'] + +arrify(['🦄']); +//=> ['🦄'] + +arrify(new Set(['🦄'])); +//=> ['🦄'] + +arrify(null); +//=> [] + +arrify(undefined); +//=> [] +``` + +*Supplying `null` or `undefined` results in an empty array.* + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/base64-js/LICENSE b/node_modules/base64-js/LICENSE new file mode 100644 index 0000000..6d52b8a --- /dev/null +++ b/node_modules/base64-js/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Jameson Little + +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. diff --git a/node_modules/base64-js/README.md b/node_modules/base64-js/README.md new file mode 100644 index 0000000..0395c33 --- /dev/null +++ b/node_modules/base64-js/README.md @@ -0,0 +1,32 @@ +base64-js +========= + +`base64-js` does basic base64 encoding/decoding in pure JS. + +[![build status](https://secure.travis-ci.org/beatgammit/base64-js.png)](http://travis-ci.org/beatgammit/base64-js) + +Many browsers already have base64 encoding/decoding functionality, but it is for text data, not all-purpose binary data. + +Sometimes encoding/decoding binary data in the browser is useful, and that is what this module does. + +## install + +With [npm](https://npmjs.org) do: + +`npm install base64-js` and `var base64js = require('base64-js')` + +For use in web browsers do: + +`` + +## methods + +`base64js` has three exposed functions, `byteLength`, `toByteArray` and `fromByteArray`, which both take a single argument. + +* `byteLength` - Takes a base64 string and returns length of byte array +* `toByteArray` - Takes a base64 string and returns a byte array +* `fromByteArray` - Takes a byte array and returns a base64 string + +## license + +MIT diff --git a/node_modules/base64-js/base64js.min.js b/node_modules/base64-js/base64js.min.js new file mode 100644 index 0000000..b0279c0 --- /dev/null +++ b/node_modules/base64-js/base64js.min.js @@ -0,0 +1 @@ +(function(r){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=r()}else if(typeof define==="function"&&define.amd){define([],r)}else{var e;if(typeof window!=="undefined"){e=window}else if(typeof global!=="undefined"){e=global}else if(typeof self!=="undefined"){e=self}else{e=this}e.base64js=r()}})(function(){var r,e,n;return function(){function d(a,f,i){function u(n,r){if(!f[n]){if(!a[n]){var e="function"==typeof require&&require;if(!r&&e)return e(n,!0);if(v)return v(n,!0);var t=new Error("Cannot find module '"+n+"'");throw t.code="MODULE_NOT_FOUND",t}var o=f[n]={exports:{}};a[n][0].call(o.exports,function(r){var e=a[n][1][r];return u(e||r)},o,o.exports,d,a,f,i)}return f[n].exports}for(var v="function"==typeof require&&require,r=0;r0){throw new Error("Invalid string. Length must be a multiple of 4")}var n=r.indexOf("=");if(n===-1)n=e;var t=n===e?0:4-n%4;return[n,t]}function f(r){var e=c(r);var n=e[0];var t=e[1];return(n+t)*3/4-t}function h(r,e,n){return(e+n)*3/4-n}function i(r){var e;var n=c(r);var t=n[0];var o=n[1];var a=new d(h(r,t,o));var f=0;var i=o>0?t-4:t;var u;for(u=0;u>16&255;a[f++]=e>>8&255;a[f++]=e&255}if(o===2){e=v[r.charCodeAt(u)]<<2|v[r.charCodeAt(u+1)]>>4;a[f++]=e&255}if(o===1){e=v[r.charCodeAt(u)]<<10|v[r.charCodeAt(u+1)]<<4|v[r.charCodeAt(u+2)]>>2;a[f++]=e>>8&255;a[f++]=e&255}return a}function s(r){return u[r>>18&63]+u[r>>12&63]+u[r>>6&63]+u[r&63]}function l(r,e,n){var t;var o=[];for(var a=e;ai?i:f+a))}if(t===1){e=r[n-1];o.push(u[e>>2]+u[e<<4&63]+"==")}else if(t===2){e=(r[n-2]<<8)+r[n-1];o.push(u[e>>10]+u[e>>4&63]+u[e<<2&63]+"=")}return o.join("")}},{}]},{},[])("/")}); diff --git a/node_modules/base64-js/index.js b/node_modules/base64-js/index.js new file mode 100644 index 0000000..f087f5b --- /dev/null +++ b/node_modules/base64-js/index.js @@ -0,0 +1,152 @@ +'use strict' + +exports.byteLength = byteLength +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray + +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i +} + +// Support decoding URL-safe base64 strings, as Node.js does. +// See: https://en.wikipedia.org/wiki/Base64#URL_applications +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 + +function getLens (b64) { + var len = b64.length + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len + + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) + + return [validLen, placeHoldersLen] +} + +// base64 is 4/3 + up to two characters of the original data +function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) + + var curByte = 0 + + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen + + var i + for (i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = 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) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + 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 parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk( + uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength) + )) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) + } + + return parts.join('') +} diff --git a/node_modules/base64-js/package.json b/node_modules/base64-js/package.json new file mode 100644 index 0000000..dfccff4 --- /dev/null +++ b/node_modules/base64-js/package.json @@ -0,0 +1,60 @@ +{ + "_from": "base64-js@^1.3.0", + "_id": "base64-js@1.3.1", + "_inBundle": false, + "_integrity": "sha512-mLQ4i2QO1ytvGWFWmcngKO//JXAQueZvwEKtjgQFM4jIK0kU+ytMfplL8j+n5mspOfjHwoAg+9yhb7BwAHm36g==", + "_location": "/base64-js", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "base64-js@^1.3.0", + "name": "base64-js", + "escapedName": "base64-js", + "rawSpec": "^1.3.0", + "saveSpec": null, + "fetchSpec": "^1.3.0" + }, + "_requiredBy": [ + "/google-auth-library" + ], + "_resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.3.1.tgz", + "_shasum": "58ece8cb75dd07e71ed08c736abc5fac4dbf8df1", + "_spec": "base64-js@^1.3.0", + "_where": "/Users/cday/Code/zendesk/fetch-build-from-gcb/node_modules/google-auth-library", + "author": { + "name": "T. Jameson Little", + "email": "t.jameson.little@gmail.com" + }, + "bugs": { + "url": "https://github.com/beatgammit/base64-js/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Base64 encoding/decoding in pure JS", + "devDependencies": { + "benchmark": "^2.1.4", + "browserify": "^16.3.0", + "standard": "*", + "tape": "4.x", + "uglify-js": "^3.6.0" + }, + "homepage": "https://github.com/beatgammit/base64-js", + "keywords": [ + "base64" + ], + "license": "MIT", + "main": "index.js", + "name": "base64-js", + "repository": { + "type": "git", + "url": "git://github.com/beatgammit/base64-js.git" + }, + "scripts": { + "build": "browserify -s base64js -r ./ | uglifyjs -m > base64js.min.js", + "lint": "standard", + "test": "npm run lint && npm run unit", + "unit": "tape test/*.js" + }, + "version": "1.3.1" +} diff --git a/node_modules/bignumber.js/CHANGELOG.md b/node_modules/bignumber.js/CHANGELOG.md new file mode 100644 index 0000000..4759fdd --- /dev/null +++ b/node_modules/bignumber.js/CHANGELOG.md @@ -0,0 +1,222 @@ +#### 7.2.1 +* 24/05/2018 +* Add `browser` field to *package.json*. + +#### 7.2.0 +* 22/05/2018 +* #166 Correct *.mjs* file. Remove extension from `main` field in *package.json*. + +#### 7.1.0 +* 18/05/2018 +* Add `module` field to *package.json* for *bignumber.mjs*. + +#### 7.0.2 +* 17/05/2018 +* #165 Bugfix: upper-case letters for bases 11-36 in a custom alphabet. +* Add note to *README* regarding creating BigNumbers from Number values. + +#### 7.0.1 +* 26/04/2018 +* #158 Fix global object variable name typo. + +#### 7.0.0 +* 26/04/2018 +* #143 Remove global BigNumber from typings. +* #144 Enable compatibility with `Object.freeze(Object.prototype)`. +* #148 #123 #11 Only throw on a number primitive with more than 15 significant digits if `BigNumber.DEBUG` is `true`. +* Only throw on an invalid BigNumber value if `BigNumber.DEBUG` is `true`. Return BigNumber `NaN` instead. +* #154 `exponentiatedBy`: allow BigNumber exponent. +* #156 Prevent Content Security Policy *unsafe-eval* issue. +* `toFraction`: allow `Infinity` maximum denominator. +* Comment-out some excess tests to reduce test time. +* Amend indentation and other spacing. + +#### 6.0.0 +* 26/01/2018 +* #137 Implement `APLHABET` configuration option. +* Remove `ERRORS` configuration option. +* Remove `toDigits` method; extend `precision` method accordingly. +* Remove s`round` method; extend `decimalPlaces` method accordingly. +* Remove methods: `ceil`, `floor`, and `truncated`. +* Remove method aliases: `add`, `cmp`, `isInt`, `isNeg`, `trunc`, `mul`, `neg` and `sub`. +* Rename methods: `shift` to `shiftedBy`, `another` to `clone`, `toPower` to `exponentiatedBy`, and `equals` to `isEqualTo`. +* Rename methods: add `is` prefix to `greaterThan`, `greaterThanOrEqualTo`, `lessThan` and `lessThanOrEqualTo`. +* Add methods: `multipliedBy`, `isBigNumber`, `isPositive`, `integerValue`, `maximum` and `minimum`. +* Refactor test suite. +* Add *CHANGELOG.md*. +* Rewrite *bignumber.d.ts*. +* Redo API image. + +#### 5.0.0 +* 27/11/2017 +* #81 Don't throw on constructor call without `new`. + +#### 4.1.0 +* 26/09/2017 +* Remove node 0.6 from *.travis.yml*. +* Add *bignumber.mjs*. + +#### 4.0.4 +* 03/09/2017 +* Add missing aliases to *bignumber.d.ts*. + +#### 4.0.3 +* 30/08/2017 +* Add types: *bignumber.d.ts*. + +#### 4.0.2 +* 03/05/2017 +* #120 Workaround Safari/Webkit bug. + +#### 4.0.1 +* 05/04/2017 +* #121 BigNumber.default to BigNumber['default']. + +#### 4.0.0 +* 09/01/2017 +* Replace BigNumber.isBigNumber method with isBigNumber prototype property. + +#### 3.1.2 +* 08/01/2017 +* Minor documentation edit. + +#### 3.1.1 +* 08/01/2017 +* Uncomment `isBigNumber` tests. +* Ignore dot files. + +#### 3.1.0 +* 08/01/2017 +* Add `isBigNumber` method. + +#### 3.0.2 +* 08/01/2017 +* Bugfix: Possible incorrect value of `ERRORS` after a `BigNumber.another` call (due to `parseNumeric` declaration in outer scope). + +#### 3.0.1 +* 23/11/2016 +* Apply fix for old ipads with `%` issue, see #57 and #102. +* Correct error message. + +#### 3.0.0 +* 09/11/2016 +* Remove `require('crypto')` - leave it to the user. +* Add `BigNumber.set` as `BigNumber.config` alias. +* Default `POW_PRECISION` to `0`. + +#### 2.4.0 +* 14/07/2016 +* #97 Add exports to support ES6 imports. + +#### 2.3.0 +* 07/03/2016 +* #86 Add modulus parameter to `toPower`. + +#### 2.2.0 +* 03/03/2016 +* #91 Permit larger JS integers. + +#### 2.1.4 +* 15/12/2015 +* Correct UMD. + +#### 2.1.3 +* 13/12/2015 +* Refactor re global object and crypto availability when bundling. + +#### 2.1.2 +* 10/12/2015 +* Bugfix: `window.crypto` not assigned to `crypto`. + +#### 2.1.1 +* 09/12/2015 +* Prevent code bundler from adding `crypto` shim. + +#### 2.1.0 +* 26/10/2015 +* For `valueOf` and `toJSON`, include the minus sign with negative zero. + +#### 2.0.8 +* 2/10/2015 +* Internal round function bugfix. + +#### 2.0.6 +* 31/03/2015 +* Add bower.json. Tweak division after in-depth review. + +#### 2.0.5 +* 25/03/2015 +* Amend README. Remove bitcoin address. + +#### 2.0.4 +* 25/03/2015 +* Critical bugfix #58: division. + +#### 2.0.3 +* 18/02/2015 +* Amend README. Add source map. + +#### 2.0.2 +* 18/02/2015 +* Correct links. + +#### 2.0.1 +* 18/02/2015 +* Add `max`, `min`, `precision`, `random`, `shiftedBy`, `toDigits` and `truncated` methods. +* Add the short-forms: `add`, `mul`, `sd`, `sub` and `trunc`. +* Add an `another` method to enable multiple independent constructors to be created. +* Add support for the base 2, 8 and 16 prefixes `0b`, `0o` and `0x`. +* Enable a rounding mode to be specified as a second parameter to `toExponential`, `toFixed`, `toFormat` and `toPrecision`. +* Add a `CRYPTO` configuration property so cryptographically-secure pseudo-random number generation can be specified. +* Add a `MODULO_MODE` configuration property to enable the rounding mode used by the `modulo` operation to be specified. +* Add a `POW_PRECISION` configuration property to enable the number of significant digits calculated by the power operation to be limited. +* Improve code quality. +* Improve documentation. + +#### 2.0.0 +* 29/12/2014 +* Add `dividedToIntegerBy`, `isInteger` and `toFormat` methods. +* Remove the following short-forms: `isF`, `isZ`, `toE`, `toF`, `toFr`, `toN`, `toP`, `toS`. +* Store a BigNumber's coefficient in base 1e14, rather than base 10. +* Add fast path for integers to BigNumber constructor. +* Incorporate the library into the online documentation. + +#### 1.5.0 +* 13/11/2014 +* Add `toJSON` and `decimalPlaces` methods. + +#### 1.4.1 +* 08/06/2014 +* Amend README. + +#### 1.4.0 +* 08/05/2014 +* Add `toNumber`. + +#### 1.3.0 +* 08/11/2013 +* Ensure correct rounding of `sqrt` in all, rather than almost all, cases. +* Maximum radix to 64. + +#### 1.2.1 +* 17/10/2013 +* Sign of zero when x < 0 and x + (-x) = 0. + +#### 1.2.0 +* 19/9/2013 +* Throw Error objects for stack. + +#### 1.1.1 +* 22/8/2013 +* Show original value in constructor error message. + +#### 1.1.0 +* 1/8/2013 +* Allow numbers with trailing radix point. + +#### 1.0.1 +* Bugfix: error messages with incorrect method name + +#### 1.0.0 +* 8/11/2012 +* Initial release diff --git a/node_modules/bignumber.js/LICENCE b/node_modules/bignumber.js/LICENCE new file mode 100644 index 0000000..3a2a4de --- /dev/null +++ b/node_modules/bignumber.js/LICENCE @@ -0,0 +1,23 @@ +The MIT Licence. + +Copyright (c) 2018 Michael Mclaughlin + +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. + diff --git a/node_modules/bignumber.js/README.md b/node_modules/bignumber.js/README.md new file mode 100644 index 0000000..0adaa79 --- /dev/null +++ b/node_modules/bignumber.js/README.md @@ -0,0 +1,266 @@ +![bignumber.js](https://raw.githubusercontent.com/MikeMcl/bignumber.js/gh-pages/bignumberjs.png) + +A JavaScript library for arbitrary-precision decimal and non-decimal arithmetic. + +[![Build Status](https://travis-ci.org/MikeMcl/bignumber.js.svg)](https://travis-ci.org/MikeMcl/bignumber.js) + +
+ +## Features + + - Integers and decimals + - Simple API but full-featured + - Faster, smaller, and perhaps easier to use than JavaScript versions of Java's BigDecimal + - 8 KB minified and gzipped + - Replicates the `toExponential`, `toFixed`, `toPrecision` and `toString` methods of JavaScript's Number type + - Includes a `toFraction` and a correctly-rounded `squareRoot` method + - Supports cryptographically-secure pseudo-random number generation + - No dependencies + - Wide platform compatibility: uses JavaScript 1.5 (ECMAScript 3) features only + - Comprehensive [documentation](http://mikemcl.github.io/bignumber.js/) and test set + +![API](https://raw.githubusercontent.com/MikeMcl/bignumber.js/gh-pages/API.png) + +If a smaller and simpler library is required see [big.js](https://github.com/MikeMcl/big.js/). +It's less than half the size but only works with decimal numbers and only has half the methods. +It also does not allow `NaN` or `Infinity`, or have the configuration options of this library. + +See also [decimal.js](https://github.com/MikeMcl/decimal.js/), which among other things adds support for non-integer powers, and performs all operations to a specified number of significant digits. + +## Load + +The library is the single JavaScript file *bignumber.js* (or minified, *bignumber.min.js*). + +Browser: + +```html + +``` + +[Node.js](http://nodejs.org): + +```bash +$ npm install --save bignumber.js +``` + +```javascript +var BigNumber = require('bignumber.js'); +``` + +ES6 module (*bignumber.mjs*): + +```javascript +//import BigNumber from 'bignumber.js'; +import {BigNumber} from 'bignumber.js'; +``` + +AMD loader libraries such as [requireJS](http://requirejs.org/): + +```javascript +require(['bignumber'], function(BigNumber) { + // Use BigNumber here in local scope. No global BigNumber. +}); +``` + +## Use + +*In all examples below, `var`, semicolons and `toString` calls are not shown. +If a commented-out value is in quotes it means `toString` has been called on the preceding expression.* + +The library exports a single function: `BigNumber`, the constructor of BigNumber instances. + +It accepts a value of type Number, String or BigNumber, + +```javascript +x = new BigNumber(123.4567) +y = BigNumber('123456.7e-3') +z = new BigNumber(x) +x.isEqualTo(y) && y.isEqualTo(z) && x.isEqualTo(z) // true +``` + +and a base can be specified. + +```javascript +a = new BigNumber(1011, 2) // "11" +b = new BigNumber('zz.9', 36) // "1295.25" +c = x.plus(y) // "1306.25" +``` + +Note that a BigNumber is created from a Number's decimal `toString()` value not from its underlying binary value. If the latter is required, then pass the Number's `toString(2)` value and specify base 2. + +```javascript +new BigNumber(Number.MAX_VALUE.toString(2), 2) +``` + +If the limited precision of Number values is not well understood, **it is recommended to pass String values rather than Number values** to avoid a potential loss of precision. + +```javascript +// Precision loss from using numeric literals with more than 15 significant digits. +new BigNumber(1.0000000000000001); // '1' +new BigNumber(88259496234518.57); // '88259496234518.56' +new BigNumber(99999999999999999999); // '100000000000000000000' + +// Precision loss from using numeric literals outside the range of Number values. +new BigNumber(2e+308); // 'Infinity' +new BigNumber(1e-324); // '0' + +// Precision loss from the unexpected result of arithmetic with Number values. +new BigNumber(0.7 + 0.1); // '0.7999999999999999' +``` + +A BigNumber is immutable in the sense that it is not changed by its methods. + +```javascript +0.3 - 0.1 // 0.19999999999999998 +x = new BigNumber(0.3) +x.minus(0.1) // "0.2" +x // "0.3" +``` + +The methods that return a BigNumber can be chained. + +```javascript +x.dividedBy(y).plus(z).times(9) +x.times('1.23456780123456789e+9').plus(9876.5432321).dividedBy('4444562598.111772').integerValue() +``` + +Some of the longer method names have a shorter alias. + +```javascript +x.squareRoot().dividedBy(y).exponentiatedBy(3).isEqualTo( x.sqrt().div(y).pow(3) ) // true +x.modulo(y).multipliedBy(z).eq( x.mod(y).times(z) ) // true +``` + +As with JavaScript's Number type, there are `toExponential`, `toFixed` and `toPrecision` methods + +```javascript +x = new BigNumber(255.5) +x.toExponential(5) // "2.55500e+2" +x.toFixed(5) // "255.50000" +x.toPrecision(5) // "255.50" +x.toNumber() // 255.5 +``` + + and a base can be specified for `toString`. + + ```javascript + x.toString(16) // "ff.8" + ``` + +There is also a `toFormat` method which may be useful for internationalisation + +```javascript +y = new BigNumber('1234567.898765') +y.toFormat(2) // "1,234,567.90" +``` + +The maximum number of decimal places of the result of an operation involving division (i.e. a division, square root, base conversion or negative power operation) is set using the `config` method of the `BigNumber` constructor. + +The other arithmetic operations always give the exact result. + +```javascript +BigNumber.config({ DECIMAL_PLACES: 10, ROUNDING_MODE: 4 }) + +x = new BigNumber(2); +y = new BigNumber(3); +z = x.dividedBy(y) // "0.6666666667" +z.squareRoot() // "0.8164965809" +z.exponentiatedBy(-3) // "3.3749999995" +z.toString(2) // "0.1010101011" +z.multipliedBy(z) // "0.44444444448888888889" +z.multipliedBy(z).decimalPlaces(10) // "0.4444444445" +``` + +There is a `toFraction` method with an optional *maximum denominator* argument + +```javascript +y = new BigNumber(355) +pi = y.dividedBy(113) // "3.1415929204" +pi.toFraction() // [ "7853982301", "2500000000" ] +pi.toFraction(1000) // [ "355", "113" ] +``` + +and `isNaN` and `isFinite` methods, as `NaN` and `Infinity` are valid `BigNumber` values. + +```javascript +x = new BigNumber(NaN) // "NaN" +y = new BigNumber(Infinity) // "Infinity" +x.isNaN() && !y.isNaN() && !x.isFinite() && !y.isFinite() // true +``` + +The value of a BigNumber is stored in a decimal floating point format in terms of a coefficient, exponent and sign. + +```javascript +x = new BigNumber(-123.456); +x.c // [ 123, 45600000000000 ] coefficient (i.e. significand) +x.e // 2 exponent +x.s // -1 sign +``` + +For advanced usage, multiple BigNumber constructors can be created, each with their own independent configuration which applies to all BigNumber's created from it. + +```javascript +// Set DECIMAL_PLACES for the original BigNumber constructor +BigNumber.config({ DECIMAL_PLACES: 10 }) + +// Create another BigNumber constructor, optionally passing in a configuration object +BN = BigNumber.clone({ DECIMAL_PLACES: 5 }) + +x = new BigNumber(1) +y = new BN(1) + +x.div(3) // '0.3333333333' +y.div(3) // '0.33333' +``` + +For futher information see the [API](http://mikemcl.github.io/bignumber.js/) reference in the *doc* directory. + +## Test + +The *test/modules* directory contains the test scripts for each method. + +The tests can be run with Node.js or a browser. For Node.js use + + $ npm test + +or + + $ node test/test + +To test a single method, use, for example + + $ node test/methods/toFraction + +For the browser, open *test/test.html*. + +## Performance + +See the [README](https://github.com/MikeMcl/bignumber.js/tree/master/perf) in the *perf* directory. + +## Build + +For Node, if [uglify-js](https://github.com/mishoo/UglifyJS2) is installed + + npm install uglify-js -g + +then + + npm run build + +will create *bignumber.min.js*. + +A source map will also be created in the root directory. + +## Feedback + +Open an issue, or email + +Michael + +M8ch88l@gmail.com + +## Licence + +The MIT Licence. + +See [LICENCE](https://github.com/MikeMcl/bignumber.js/blob/master/LICENCE). diff --git a/node_modules/bignumber.js/bignumber.d.ts b/node_modules/bignumber.js/bignumber.d.ts new file mode 100644 index 0000000..22ef0b1 --- /dev/null +++ b/node_modules/bignumber.js/bignumber.d.ts @@ -0,0 +1,1797 @@ +// Type definitions for bignumber.js >=6.0.0 +// Project: https://github.com/MikeMcl/bignumber.js +// Definitions by: Michael Mclaughlin +// Definitions: https://github.com/MikeMcl/bignumber.js + +// Documentation: http://mikemcl.github.io/bignumber.js/ +// +// Exports: +// +// class BigNumber (default export) +// type BigNumber.Constructor +// type BigNumber.Instance +// type BigNumber.ModuloMode +// type BigNumber.RoundingMOde +// type BigNumber.Value +// interface BigNumber.Config +// interface BigNumber.Format +// +// Example (alternative syntax commented-out): +// +// import {BigNumber} from "bignumber.js" +// //import BigNumber from "bignumber.js" +// +// let rm: BigNumber.RoundingMode = BigNumber.ROUND_UP; +// let f: BigNumber.Format = { decimalSeparator: ',' }; +// let c: BigNumber.Config = { DECIMAL_PLACES: 4, ROUNDING_MODE: rm, FORMAT: f }; +// BigNumber.config(c); +// +// let v: BigNumber.Value = '12345.6789'; +// let b: BigNumber = new BigNumber(v); +// //let b: BigNumber.Instance = new BigNumber(v); +// +// The use of compiler option `--strictNullChecks` is recommended. + +export default BigNumber; + +export namespace BigNumber { + + /** + * See `BigNumber.config` and `BigNumber.clone`. + */ + export interface Config { + + /** + * An integer, 0 to 1e+9. Default value: 20. + * + * The maximum number of decimal places of the result of operations involving division, i.e. + * division, square root and base conversion operations, and exponentiation when the exponent is + * negative. + * + * ```ts + * BigNumber.config({ DECIMAL_PLACES: 5 }) + * BigNumber.set({ DECIMAL_PLACES: 5 }) + * ``` + */ + DECIMAL_PLACES?: number; + + /** + * An integer, 0 to 8. Default value: `BigNumber.ROUND_HALF_UP` (4). + * + * The rounding mode used in operations that involve division (see `DECIMAL_PLACES`) and the + * default rounding mode of the `decimalPlaces`, `precision`, `toExponential`, `toFixed`, + * `toFormat` and `toPrecision` methods. + * + * The modes are available as enumerated properties of the BigNumber constructor. + * + * ```ts + * BigNumber.config({ ROUNDING_MODE: 0 }) + * BigNumber.set({ ROUNDING_MODE: BigNumber.ROUND_UP }) + * ``` + */ + ROUNDING_MODE?: BigNumber.RoundingMode; + + /** + * An integer, 0 to 1e+9, or an array, [-1e+9 to 0, 0 to 1e+9]. + * Default value: `[-7, 20]`. + * + * The exponent value(s) at which `toString` returns exponential notation. + * + * If a single number is assigned, the value is the exponent magnitude. + * + * If an array of two numbers is assigned then the first number is the negative exponent value at + * and beneath which exponential notation is used, and the second number is the positive exponent + * value at and above which exponential notation is used. + * + * For example, to emulate JavaScript numbers in terms of the exponent values at which they begin + * to use exponential notation, use `[-7, 20]`. + * + * ```ts + * BigNumber.config({ EXPONENTIAL_AT: 2 }) + * new BigNumber(12.3) // '12.3' e is only 1 + * new BigNumber(123) // '1.23e+2' + * new BigNumber(0.123) // '0.123' e is only -1 + * new BigNumber(0.0123) // '1.23e-2' + * + * BigNumber.config({ EXPONENTIAL_AT: [-7, 20] }) + * new BigNumber(123456789) // '123456789' e is only 8 + * new BigNumber(0.000000123) // '1.23e-7' + * + * // Almost never return exponential notation: + * BigNumber.config({ EXPONENTIAL_AT: 1e+9 }) + * + * // Always return exponential notation: + * BigNumber.config({ EXPONENTIAL_AT: 0 }) + * ``` + * + * Regardless of the value of `EXPONENTIAL_AT`, the `toFixed` method will always return a value in + * normal notation and the `toExponential` method will always return a value in exponential form. + * Calling `toString` with a base argument, e.g. `toString(10)`, will also always return normal + * notation. + */ + EXPONENTIAL_AT?: number|[number, number]; + + /** + * An integer, magnitude 1 to 1e+9, or an array, [-1e+9 to -1, 1 to 1e+9]. + * Default value: `[-1e+9, 1e+9]`. + * + * The exponent value(s) beyond which overflow to Infinity and underflow to zero occurs. + * + * If a single number is assigned, it is the maximum exponent magnitude: values wth a positive + * exponent of greater magnitude become Infinity and those with a negative exponent of greater + * magnitude become zero. + * + * If an array of two numbers is assigned then the first number is the negative exponent limit and + * the second number is the positive exponent limit. + * + * For example, to emulate JavaScript numbers in terms of the exponent values at which they + * become zero and Infinity, use [-324, 308]. + * + * ```ts + * BigNumber.config({ RANGE: 500 }) + * BigNumber.config().RANGE // [ -500, 500 ] + * new BigNumber('9.999e499') // '9.999e+499' + * new BigNumber('1e500') // 'Infinity' + * new BigNumber('1e-499') // '1e-499' + * new BigNumber('1e-500') // '0' + * + * BigNumber.config({ RANGE: [-3, 4] }) + * new BigNumber(99999) // '99999' e is only 4 + * new BigNumber(100000) // 'Infinity' e is 5 + * new BigNumber(0.001) // '0.01' e is only -3 + * new BigNumber(0.0001) // '0' e is -4 + * ``` + * The largest possible magnitude of a finite BigNumber is 9.999...e+1000000000. + * The smallest possible magnitude of a non-zero BigNumber is 1e-1000000000. + */ + RANGE?: number|[number, number]; + + /** + * A boolean: `true` or `false`. Default value: `false`. + * + * The value that determines whether cryptographically-secure pseudo-random number generation is + * used. If `CRYPTO` is set to true then the random method will generate random digits using + * `crypto.getRandomValues` in browsers that support it, or `crypto.randomBytes` if using a + * version of Node.js that supports it. + * + * If neither function is supported by the host environment then attempting to set `CRYPTO` to + * `true` will fail and an exception will be thrown. + * + * If `CRYPTO` is `false` then the source of randomness used will be `Math.random` (which is + * assumed to generate at least 30 bits of randomness). + * + * See `BigNumber.random`. + * + * ```ts + * BigNumber.config({ CRYPTO: true }) + * BigNumber.config().CRYPTO // true + * BigNumber.random() // 0.54340758610486147524 + * ``` + */ + CRYPTO?: boolean; + + /** + * An integer, 0, 1, 3, 6 or 9. Default value: `BigNumber.ROUND_DOWN` (1). + * + * The modulo mode used when calculating the modulus: `a mod n`. + * The quotient, `q = a / n`, is calculated according to the `ROUNDING_MODE` that corresponds to + * the chosen `MODULO_MODE`. + * The remainder, `r`, is calculated as: `r = a - n * q`. + * + * The modes that are most commonly used for the modulus/remainder operation are shown in the + * following table. Although the other rounding modes can be used, they may not give useful + * results. + * + * Property | Value | Description + * :------------------|:------|:------------------------------------------------------------------ + * `ROUND_UP` | 0 | The remainder is positive if the dividend is negative. + * `ROUND_DOWN` | 1 | The remainder has the same sign as the dividend. + * | | Uses 'truncating division' and matches JavaScript's `%` operator . + * `ROUND_FLOOR` | 3 | The remainder has the same sign as the divisor. + * | | This matches Python's `%` operator. + * `ROUND_HALF_EVEN` | 6 | The IEEE 754 remainder function. + * `EUCLID` | 9 | The remainder is always positive. + * | | Euclidian division: `q = sign(n) * floor(a / abs(n))` + * + * The rounding/modulo modes are available as enumerated properties of the BigNumber constructor. + * + * See `modulo`. + * + * ```ts + * BigNumber.config({ MODULO_MODE: BigNumber.EUCLID }) + * BigNumber.set({ MODULO_MODE: 9 }) // equivalent + * ``` + */ + MODULO_MODE?: BigNumber.ModuloMode; + + /** + * An integer, 0 to 1e+9. Default value: 0. + * + * The maximum precision, i.e. number of significant digits, of the result of the power operation + * - unless a modulus is specified. + * + * If set to 0, the number of significant digits will not be limited. + * + * See `exponentiatedBy`. + * + * ```ts + * BigNumber.config({ POW_PRECISION: 100 }) + * ``` + */ + POW_PRECISION?: number; + + /** + * An object including any number of the properties shown below. + * + * The object configures the format of the string returned by the `toFormat` method. + * The example below shows the properties of the object that are recognised, and + * their default values. + * + * Unlike the other configuration properties, the values of the properties of the `FORMAT` object + * will not be checked for validity - the existing object will simply be replaced by the object + * that is passed in. + * + * See `toFormat`. + * + * ```ts + * BigNumber.config({ + * FORMAT: { + * // the decimal separator + * decimalSeparator: '.', + * // the grouping separator of the integer part + * groupSeparator: ',', + * // the primary grouping size of the integer part + * groupSize: 3, + * // the secondary grouping size of the integer part + * secondaryGroupSize: 0, + * // the grouping separator of the fraction part + * fractionGroupSeparator: ' ', + * // the grouping size of the fraction part + * fractionGroupSize: 0 + * } + * }) + * ``` + */ + FORMAT?: BigNumber.Format; + + /** + * A string representing the alphabet used for base conversion. + * Default value: `'0123456789abcdefghijklmnopqrstuvwxyz'`. + * + * The length of the alphabet corresponds to the maximum value of the base argument that can be + * passed to the BigNumber constructor or `toString`. There is no maximum length, but it must be + * at least 2 characters long, and it must not contain a repeated character, or `'.'` - the + * decimal separator for all values whatever their base. + * + * ```ts + * // duodecimal (base 12) + * BigNumber.config({ ALPHABET: '0123456789TE' }) + * x = new BigNumber('T', 12) + * x.toString() // '10' + * x.toString(12) // 'T' + * ``` + */ + ALPHABET?: string; + } + + export type Constructor = typeof BigNumber; + + /** + * See `FORMAT` and `toFormat`. + */ + export interface Format { + + /** + * The decimal separator. + */ + decimalSeparator?: string; + + /** + * The grouping separator of the integer part. + */ + groupSeparator?: string; + + /** + * The primary grouping size of the integer part. + */ + groupSize?: number; + + /** + * The secondary grouping size of the integer part. + */ + secondaryGroupSize?: number; + + /** + * The grouping separator of the fraction part. + */ + fractionGroupSeparator?: string; + + /** + * The grouping size of the fraction part. + */ + fractionGroupSize?: number; + } + + export type Instance = BigNumber; + export type ModuloMode = 0 | 1 | 3 | 6 | 9; + export type RoundingMode = 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8; + export type Value = string | number | BigNumber; +} + +export declare class BigNumber { + + /** + * Used internally by the `BigNumber.isBigNumber` method. + */ + private readonly _isBigNumber: true; + + /** + * The coefficient of the value of this BigNumber, an array of base 1e14 integer numbers. + */ + readonly c: number[]; + + /** + * The exponent of the value of this BigNumber, an integer number, -1000000000 to 1000000000. + */ + readonly e: number; + + /** + * The sign of the value of this BigNumber, -1 or 1. + */ + readonly s: number; + + /** + * Returns a new instance of a BigNumber object with value `n`, where `n` is a numeric value in + * the specified `base`, or base 10 if `base` is omitted or is `null` or `undefined`. + * + * ```ts + * x = new BigNumber(123.4567) // '123.4567' + * // 'new' is optional + * y = BigNumber(x) // '123.4567' + * ``` + * + * If `n` is a base 10 value it can be in normal (fixed-point) or exponential notation. + * Values in other bases must be in normal notation. Values in any base can have fraction digits, + * i.e. digits after the decimal point. + * + * ```ts + * new BigNumber(43210) // '43210' + * new BigNumber('4.321e+4') // '43210' + * new BigNumber('-735.0918e-430') // '-7.350918e-428' + * new BigNumber('123412421.234324', 5) // '607236.557696' + * ``` + * + * Signed `0`, signed `Infinity` and `NaN` are supported. + * + * ```ts + * new BigNumber('-Infinity') // '-Infinity' + * new BigNumber(NaN) // 'NaN' + * new BigNumber(-0) // '0' + * new BigNumber('.5') // '0.5' + * new BigNumber('+2') // '2' + * ``` + * + * String values in hexadecimal literal form, e.g. `'0xff'`, are valid, as are string values with + * the octal and binary prefixs `'0o'` and `'0b'`. String values in octal literal form without the + * prefix will be interpreted as decimals, e.g. `'011'` is interpreted as 11, not 9. + * + * ```ts + * new BigNumber(-10110100.1, 2) // '-180.5' + * new BigNumber('-0b10110100.1') // '-180.5' + * new BigNumber('ff.8', 16) // '255.5' + * new BigNumber('0xff.8') // '255.5' + * ``` + * + * If a base is specified, `n` is rounded according to the current `DECIMAL_PLACES` and + * `ROUNDING_MODE` settings. This includes base 10, so don't include a `base` parameter for decimal + * values unless this behaviour is desired. + * + * ```ts + * BigNumber.config({ DECIMAL_PLACES: 5 }) + * new BigNumber(1.23456789) // '1.23456789' + * new BigNumber(1.23456789, 10) // '1.23457' + * ``` + * + * An error is thrown if `base` is invalid. + * + * There is no limit to the number of digits of a value of type string (other than that of + * JavaScript's maximum array size). See `RANGE` to set the maximum and minimum possible exponent + * value of a BigNumber. + * + * ```ts + * new BigNumber('5032485723458348569331745.33434346346912144534543') + * new BigNumber('4.321e10000000') + * ``` + * + * BigNumber `NaN` is returned if `n` is invalid (unless `BigNumber.DEBUG` is `true`, see below). + * + * ```ts + * new BigNumber('.1*') // 'NaN' + * new BigNumber('blurgh') // 'NaN' + * new BigNumber(9, 2) // 'NaN' + * ``` + * + * To aid in debugging, if `BigNumber.DEBUG` is `true` then an error will be thrown on an + * invalid `n`. An error will also be thrown if `n` is of type number with more than 15 + * significant digits, as calling `toString` or `valueOf` on these numbers may not result in the + * intended value. + * + * ```ts + * console.log(823456789123456.3) // 823456789123456.2 + * new BigNumber(823456789123456.3) // '823456789123456.2' + * BigNumber.DEBUG = true + * // 'Error: Number has more than 15 significant digits' + * new BigNumber(823456789123456.3) + * // 'Error: Not a base 2 number' + * new BigNumber(9, 2) + * ``` + * + * @param n A numeric value. + * @param base The base of `n`, integer, 2 to 36 (or `ALPHABET.length`, see `ALPHABET`). + */ + constructor(n: BigNumber.Value, base?: number); + + /** + * Returns a BigNumber whose value is the absolute value, i.e. the magnitude, of the value of this + * BigNumber. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber(-0.8) + * x.absoluteValue() // '0.8' + * ``` + */ + absoluteValue(): BigNumber; + + /** + * Returns a BigNumber whose value is the absolute value, i.e. the magnitude, of the value of this + * BigNumber. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber(-0.8) + * x.abs() // '0.8' + * ``` + */ + abs(): BigNumber; + + /** + * Returns | | + * :-------:|:--------------------------------------------------------------| + * 1 | If the value of this BigNumber is greater than the value of `n` + * -1 | If the value of this BigNumber is less than the value of `n` + * 0 | If this BigNumber and `n` have the same value + * `null` | If the value of either this BigNumber or `n` is `NaN` + * + * ```ts + * + * x = new BigNumber(Infinity) + * y = new BigNumber(5) + * x.comparedTo(y) // 1 + * x.comparedTo(x.minus(1)) // 0 + * y.comparedTo(NaN) // null + * y.comparedTo('110', 2) // -1 + * ``` + * @param n A numeric value. + * @param [base] The base of n. + */ + comparedTo(n: BigNumber.Value, base?: number): number; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded by rounding mode + * `roundingMode` to a maximum of `decimalPlaces` decimal places. + * + * If `decimalPlaces` is omitted, or is `null` or `undefined`, the return value is the number of + * decimal places of the value of this BigNumber, or `null` if the value of this BigNumber is + * ±`Infinity` or `NaN`. + * + * If `roundingMode` is omitted, or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * Throws if `decimalPlaces` or `roundingMode` is invalid. + * + * ```ts + * x = new BigNumber(1234.56) + * x.decimalPlaces() // 2 + * x.decimalPlaces(1) // '1234.6' + * x.decimalPlaces(2) // '1234.56' + * x.decimalPlaces(10) // '1234.56' + * x.decimalPlaces(0, 1) // '1234' + * x.decimalPlaces(0, 6) // '1235' + * x.decimalPlaces(1, 1) // '1234.5' + * x.decimalPlaces(1, BigNumber.ROUND_HALF_EVEN) // '1234.6' + * x // '1234.56' + * y = new BigNumber('9.9e-101') + * y.decimalPlaces() // 102 + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + decimalPlaces(): number; + decimalPlaces(decimalPlaces: number, roundingMode?: BigNumber.RoundingMode): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded by rounding mode + * `roundingMode` to a maximum of `decimalPlaces` decimal places. + * + * If `decimalPlaces` is omitted, or is `null` or `undefined`, the return value is the number of + * decimal places of the value of this BigNumber, or `null` if the value of this BigNumber is + * ±`Infinity` or `NaN`. + * + * If `roundingMode` is omitted, or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * Throws if `decimalPlaces` or `roundingMode` is invalid. + * + * ```ts + * x = new BigNumber(1234.56) + * x.dp() // 2 + * x.dp(1) // '1234.6' + * x.dp(2) // '1234.56' + * x.dp(10) // '1234.56' + * x.dp(0, 1) // '1234' + * x.dp(0, 6) // '1235' + * x.dp(1, 1) // '1234.5' + * x.dp(1, BigNumber.ROUND_HALF_EVEN) // '1234.6' + * x // '1234.56' + * y = new BigNumber('9.9e-101') + * y.dp() // 102 + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + dp(): number; + dp(decimalPlaces: number, roundingMode?: BigNumber.RoundingMode): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber divided by `n`, rounded + * according to the current `DECIMAL_PLACES` and `ROUNDING_MODE` settings. + * + * ```ts + * x = new BigNumber(355) + * y = new BigNumber(113) + * x.dividedBy(y) // '3.14159292035398230088' + * x.dividedBy(5) // '71' + * x.dividedBy(47, 16) // '5' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + dividedBy(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber divided by `n`, rounded + * according to the current `DECIMAL_PLACES` and `ROUNDING_MODE` settings. + * + * ```ts + * x = new BigNumber(355) + * y = new BigNumber(113) + * x.div(y) // '3.14159292035398230088' + * x.div(5) // '71' + * x.div(47, 16) // '5' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + div(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the integer part of dividing the value of this BigNumber by + * `n`. + * + * ```ts + * x = new BigNumber(5) + * y = new BigNumber(3) + * x.dividedToIntegerBy(y) // '1' + * x.dividedToIntegerBy(0.7) // '7' + * x.dividedToIntegerBy('0.f', 16) // '5' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + dividedToIntegerBy(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the integer part of dividing the value of this BigNumber by + * `n`. + * + * ```ts + * x = new BigNumber(5) + * y = new BigNumber(3) + * x.idiv(y) // '1' + * x.idiv(0.7) // '7' + * x.idiv('0.f', 16) // '5' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + idiv(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber exponentiated by `n`, i.e. + * raised to the power `n`, and optionally modulo a modulus `m`. + * + * If `n` is negative the result is rounded according to the current `DECIMAL_PLACES` and + * `ROUNDING_MODE` settings. + * + * As the number of digits of the result of the power operation can grow so large so quickly, + * e.g. 123.456**10000 has over 50000 digits, the number of significant digits calculated is + * limited to the value of the `POW_PRECISION` setting (unless a modulus `m` is specified). + * + * By default `POW_PRECISION` is set to 0. This means that an unlimited number of significant + * digits will be calculated, and that the method's performance will decrease dramatically for + * larger exponents. + * + * If `m` is specified and the value of `m`, `n` and this BigNumber are integers and `n` is + * positive, then a fast modular exponentiation algorithm is used, otherwise the operation will + * be performed as `x.exponentiatedBy(n).modulo(m)` with a `POW_PRECISION` of 0. + * + * Throws if `n` is not an integer. + * + * ```ts + * Math.pow(0.7, 2) // 0.48999999999999994 + * x = new BigNumber(0.7) + * x.exponentiatedBy(2) // '0.49' + * BigNumber(3).exponentiatedBy(-2) // '0.11111111111111111111' + * ``` + * + * @param n The exponent, an integer. + * @param [m] The modulus. + */ + exponentiatedBy(n: number, m?: BigNumber.Value): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber exponentiated by `n`, i.e. + * raised to the power `n`, and optionally modulo a modulus `m`. + * + * If `n` is negative the result is rounded according to the current `DECIMAL_PLACES` and + * `ROUNDING_MODE` settings. + * + * As the number of digits of the result of the power operation can grow so large so quickly, + * e.g. 123.456**10000 has over 50000 digits, the number of significant digits calculated is + * limited to the value of the `POW_PRECISION` setting (unless a modulus `m` is specified). + * + * By default `POW_PRECISION` is set to 0. This means that an unlimited number of significant + * digits will be calculated, and that the method's performance will decrease dramatically for + * larger exponents. + * + * If `m` is specified and the value of `m`, `n` and this BigNumber are integers and `n` is + * positive, then a fast modular exponentiation algorithm is used, otherwise the operation will + * be performed as `x.pow(n).modulo(m)` with a `POW_PRECISION` of 0. + * + * Throws if `n` is not an integer. + * + * ```ts + * Math.pow(0.7, 2) // 0.48999999999999994 + * x = new BigNumber(0.7) + * x.pow(2) // '0.49' + * BigNumber(3).pow(-2) // '0.11111111111111111111' + * ``` + * + * @param n The exponent, an integer. + * @param [m] The modulus. + */ + pow(n: number, m?: BigNumber.Value): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded to an integer using + * rounding mode `rm`. + * + * If `rm` is omitted, or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * Throws if `rm` is invalid. + * + * ```ts + * x = new BigNumber(123.456) + * x.integerValue() // '123' + * x.integerValue(BigNumber.ROUND_CEIL) // '124' + * y = new BigNumber(-12.7) + * y.integerValue() // '-13' + * x.integerValue(BigNumber.ROUND_DOWN) // '-12' + * ``` + * + * @param {BigNumber.RoundingMode} [rm] The roundng mode, an integer, 0 to 8. + */ + integerValue(rm?: BigNumber.RoundingMode): BigNumber; + + /** + * Returns `true` if the value of this BigNumber is equal to the value of `n`, otherwise returns + * `false`. + * + * As with JavaScript, `NaN` does not equal `NaN`. + * + * ```ts + * 0 === 1e-324 // true + * x = new BigNumber(0) + * x.isEqualTo('1e-324') // false + * BigNumber(-0).isEqualTo(x) // true ( -0 === 0 ) + * BigNumber(255).isEqualTo('ff', 16) // true + * + * y = new BigNumber(NaN) + * y.isEqualTo(NaN) // false + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + isEqualTo(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is equal to the value of `n`, otherwise returns + * `false`. + * + * As with JavaScript, `NaN` does not equal `NaN`. + * + * ```ts + * 0 === 1e-324 // true + * x = new BigNumber(0) + * x.eq('1e-324') // false + * BigNumber(-0).eq(x) // true ( -0 === 0 ) + * BigNumber(255).eq('ff', 16) // true + * + * y = new BigNumber(NaN) + * y.eq(NaN) // false + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + eq(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is a finite number, otherwise returns `false`. + * + * The only possible non-finite values of a BigNumber are `NaN`, `Infinity` and `-Infinity`. + * + * ```ts + * x = new BigNumber(1) + * x.isFinite() // true + * y = new BigNumber(Infinity) + * y.isFinite() // false + * ``` + */ + isFinite(): boolean; + + /** + * Returns `true` if the value of this BigNumber is greater than the value of `n`, otherwise + * returns `false`. + * + * ```ts + * 0.1 > (0.3 - 0.2) // true + * x = new BigNumber(0.1) + * x.isGreaterThan(BigNumber(0.3).minus(0.2)) // false + * BigNumber(0).isGreaterThan(x) // false + * BigNumber(11, 3).isGreaterThan(11.1, 2) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + isGreaterThan(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is greater than the value of `n`, otherwise + * returns `false`. + * + * ```ts + * 0.1 > (0.3 - 0 // true + * x = new BigNumber(0.1) + * x.gt(BigNumber(0.3).minus(0.2)) // false + * BigNumber(0).gt(x) // false + * BigNumber(11, 3).gt(11.1, 2) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + gt(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is greater than or equal to the value of `n`, + * otherwise returns `false`. + * + * ```ts + * (0.3 - 0.2) >= 0.1 // false + * x = new BigNumber(0.3).minus(0.2) + * x.isGreaterThanOrEqualTo(0.1) // true + * BigNumber(1).isGreaterThanOrEqualTo(x) // true + * BigNumber(10, 18).isGreaterThanOrEqualTo('i', 36) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + isGreaterThanOrEqualTo(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is greater than or equal to the value of `n`, + * otherwise returns `false`. + * + * ```ts + * (0.3 - 0.2) >= 0.1 // false + * x = new BigNumber(0.3).minus(0.2) + * x.gte(0.1) // true + * BigNumber(1).gte(x) // true + * BigNumber(10, 18).gte('i', 36) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + gte(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is an integer, otherwise returns `false`. + * + * ```ts + * x = new BigNumber(1) + * x.isInteger() // true + * y = new BigNumber(123.456) + * y.isInteger() // false + * ``` + */ + isInteger(): boolean; + + /** + * Returns `true` if the value of this BigNumber is less than the value of `n`, otherwise returns + * `false`. + * + * ```ts + * (0.3 - 0.2) < 0.1 // true + * x = new BigNumber(0.3).minus(0.2) + * x.isLessThan(0.1) // false + * BigNumber(0).isLessThan(x) // true + * BigNumber(11.1, 2).isLessThan(11, 3) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + isLessThan(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is less than the value of `n`, otherwise returns + * `false`. + * + * ```ts + * (0.3 - 0.2) < 0.1 // true + * x = new BigNumber(0.3).minus(0.2) + * x.lt(0.1) // false + * BigNumber(0).lt(x) // true + * BigNumber(11.1, 2).lt(11, 3) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + lt(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is less than or equal to the value of `n`, + * otherwise returns `false`. + * + * ```ts + * 0.1 <= (0.3 - 0.2) // false + * x = new BigNumber(0.1) + * x.isLessThanOrEqualTo(BigNumber(0.3).minus(0.2)) // true + * BigNumber(-1).isLessThanOrEqualTo(x) // true + * BigNumber(10, 18).isLessThanOrEqualTo('i', 36) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + isLessThanOrEqualTo(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is less than or equal to the value of `n`, + * otherwise returns `false`. + * + * ```ts + * 0.1 <= (0.3 - 0.2) // false + * x = new BigNumber(0.1) + * x.lte(BigNumber(0.3).minus(0.2)) // true + * BigNumber(-1).lte(x) // true + * BigNumber(10, 18).lte('i', 36) // true + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + lte(n: BigNumber.Value, base?: number): boolean; + + /** + * Returns `true` if the value of this BigNumber is `NaN`, otherwise returns `false`. + * + * ```ts + * x = new BigNumber(NaN) + * x.isNaN() // true + * y = new BigNumber('Infinity') + * y.isNaN() // false + * ``` + */ + isNaN(): boolean; + + /** + * Returns `true` if the value of this BigNumber is negative, otherwise returns `false`. + * + * ```ts + * x = new BigNumber(-0) + * x.isNegative() // true + * y = new BigNumber(2) + * y.isNegative() // false + * ``` + */ + isNegative(): boolean; + + /** + * Returns `true` if the value of this BigNumber is positive, otherwise returns `false`. + * + * ```ts + * x = new BigNumber(-0) + * x.isPositive() // false + * y = new BigNumber(2) + * y.isPositive() // true + * ``` + */ + isPositive(): boolean; + + /** + * Returns `true` if the value of this BigNumber is zero or minus zero, otherwise returns `false`. + * + * ```ts + * x = new BigNumber(-0) + * x.isZero() // true + * ``` + */ + isZero(): boolean; + + /** + * Returns a BigNumber whose value is the value of this BigNumber minus `n`. + * + * The return value is always exact and unrounded. + * + * ```ts + * 0.3 - 0.1 // 0.19999999999999998 + * x = new BigNumber(0.3) + * x.minus(0.1) // '0.2' + * x.minus(0.6, 20) // '0' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + minus(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber modulo `n`, i.e. the integer + * remainder of dividing this BigNumber by `n`. + * + * The value returned, and in particular its sign, is dependent on the value of the `MODULO_MODE` + * setting of this BigNumber constructor. If it is 1 (default value), the result will have the + * same sign as this BigNumber, and it will match that of Javascript's `%` operator (within the + * limits of double precision) and BigDecimal's `remainder` method. + * + * The return value is always exact and unrounded. + * + * See `MODULO_MODE` for a description of the other modulo modes. + * + * ```ts + * 1 % 0.9 // 0.09999999999999998 + * x = new BigNumber(1) + * x.modulo(0.9) // '0.1' + * y = new BigNumber(33) + * y.modulo('a', 33) // '3' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + modulo(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber modulo `n`, i.e. the integer + * remainder of dividing this BigNumber by `n`. + * + * The value returned, and in particular its sign, is dependent on the value of the `MODULO_MODE` + * setting of this BigNumber constructor. If it is 1 (default value), the result will have the + * same sign as this BigNumber, and it will match that of Javascript's `%` operator (within the + * limits of double precision) and BigDecimal's `remainder` method. + * + * The return value is always exact and unrounded. + * + * See `MODULO_MODE` for a description of the other modulo modes. + * + * ```ts + * 1 % 0.9 // 0.09999999999999998 + * x = new BigNumber(1) + * x.mod(0.9) // '0.1' + * y = new BigNumber(33) + * y.mod('a', 33) // '3' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + mod(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber multiplied by `n`. + * + * The return value is always exact and unrounded. + * + * ```ts + * 0.6 * 3 // 1.7999999999999998 + * x = new BigNumber(0.6) + * y = x.multipliedBy(3) // '1.8' + * BigNumber('7e+500').multipliedBy(y) // '1.26e+501' + * x.multipliedBy('-a', 16) // '-6' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + multipliedBy(n: BigNumber.Value, base?: number) : BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber multiplied by `n`. + * + * The return value is always exact and unrounded. + * + * ```ts + * 0.6 * 3 // 1.7999999999999998 + * x = new BigNumber(0.6) + * y = x.times(3) // '1.8' + * BigNumber('7e+500').times(y) // '1.26e+501' + * x.times('-a', 16) // '-6' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + times(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber negated, i.e. multiplied by -1. + * + * ```ts + * x = new BigNumber(1.8) + * x.negated() // '-1.8' + * y = new BigNumber(-1.3) + * y.negated() // '1.3' + * ``` + */ + negated(): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber plus `n`. + * + * The return value is always exact and unrounded. + * + * ```ts + * 0.1 + 0.2 // 0.30000000000000004 + * x = new BigNumber(0.1) + * y = x.plus(0.2) // '0.3' + * BigNumber(0.7).plus(x).plus(y) // '1' + * x.plus('0.1', 8) // '0.225' + * ``` + * + * @param n A numeric value. + * @param [base] The base of n. + */ + plus(n: BigNumber.Value, base?: number): BigNumber; + + /** + * Returns the number of significant digits of the value of this BigNumber, or `null` if the value + * of this BigNumber is ±`Infinity` or `NaN`. + * + * If `includeZeros` is true then any trailing zeros of the integer part of the value of this + * BigNumber are counted as significant digits, otherwise they are not. + * + * Throws if `includeZeros` is invalid. + * + * ```ts + * x = new BigNumber(9876.54321) + * x.precision() // 9 + * y = new BigNumber(987000) + * y.precision(false) // 3 + * y.precision(true) // 6 + * ``` + * + * @param [includeZeros] Whether to include integer trailing zeros in the significant digit count. + */ + precision(includeZeros?: boolean): number; + + /** + * Returns a BigNumber whose value is the value of this BigNumber rounded to a precision of + * `significantDigits` significant digits using rounding mode `roundingMode`. + * + * If `roundingMode` is omitted or is `null` or `undefined`, `ROUNDING_MODE` will be used. + * + * Throws if `significantDigits` or `roundingMode` is invalid. + * + * ```ts + * x = new BigNumber(9876.54321) + * x.precision(6) // '9876.54' + * x.precision(6, BigNumber.ROUND_UP) // '9876.55' + * x.precision(2) // '9900' + * x.precision(2, 1) // '9800' + * x // '9876.54321' + * ``` + * + * @param significantDigits Significant digits, integer, 1 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + precision(significantDigits: number, roundingMode?: BigNumber.RoundingMode): BigNumber; + + /** + * Returns the number of significant digits of the value of this BigNumber, + * or `null` if the value of this BigNumber is ±`Infinity` or `NaN`. + * + * If `includeZeros` is true then any trailing zeros of the integer part of + * the value of this BigNumber are counted as significant digits, otherwise + * they are not. + * + * Throws if `includeZeros` is invalid. + * + * ```ts + * x = new BigNumber(9876.54321) + * x.sd() // 9 + * y = new BigNumber(987000) + * y.sd(false) // 3 + * y.sd(true) // 6 + * ``` + * + * @param [includeZeros] Whether to include integer trailing zeros in the significant digit count. + */ + sd(includeZeros?: boolean): number; + + /* + * Returns a BigNumber whose value is the value of this BigNumber rounded to a precision of + * `significantDigits` significant digits using rounding mode `roundingMode`. + * + * If `roundingMode` is omitted or is `null` or `undefined`, `ROUNDING_MODE` will be used. + * + * Throws if `significantDigits` or `roundingMode` is invalid. + * + * ```ts + * x = new BigNumber(9876.54321) + * x.sd(6) // '9876.54' + * x.sd(6, BigNumber.ROUND_UP) // '9876.55' + * x.sd(2) // '9900' + * x.sd(2, 1) // '9800' + * x // '9876.54321' + * ``` + * + * @param significantDigits Significant digits, integer, 1 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + sd(significantDigits: number, roundingMode?: BigNumber.RoundingMode): BigNumber; + + /** + * Returns a BigNumber whose value is the value of this BigNumber shifted by `n` places. + * + * The shift is of the decimal point, i.e. of powers of ten, and is to the left if `n` is negative + * or to the right if `n` is positive. + * + * The return value is always exact and unrounded. + * + * Throws if `n` is invalid. + * + * ```ts + * x = new BigNumber(1.23) + * x.shiftedBy(3) // '1230' + * x.shiftedBy(-3) // '0.00123' + * ``` + * + * @param n The shift value, integer, -9007199254740991 to 9007199254740991. + */ + shiftedBy(n: number): BigNumber; + + /** + * Returns a BigNumber whose value is the square root of the value of this BigNumber, rounded + * according to the current `DECIMAL_PLACES` and `ROUNDING_MODE` settings. + * + * The return value will be correctly rounded, i.e. rounded as if the result was first calculated + * to an infinite number of correct digits before rounding. + * + * ```ts + * x = new BigNumber(16) + * x.squareRoot() // '4' + * y = new BigNumber(3) + * y.squareRoot() // '1.73205080756887729353' + * ``` + */ + squareRoot(): BigNumber; + + /** + * Returns a BigNumber whose value is the square root of the value of this BigNumber, rounded + * according to the current `DECIMAL_PLACES` and `ROUNDING_MODE` settings. + * + * The return value will be correctly rounded, i.e. rounded as if the result was first calculated + * to an infinite number of correct digits before rounding. + * + * ```ts + * x = new BigNumber(16) + * x.sqrt() // '4' + * y = new BigNumber(3) + * y.sqrt() // '1.73205080756887729353' + * ``` + */ + sqrt(): BigNumber; + + /** + * Returns a string representing the value of this BigNumber in exponential notation rounded using + * rounding mode `roundingMode` to `decimalPlaces` decimal places, i.e with one digit before the + * decimal point and `decimalPlaces` digits after it. + * + * If the value of this BigNumber in exponential notation has fewer than `decimalPlaces` fraction + * digits, the return value will be appended with zeros accordingly. + * + * If `decimalPlaces` is omitted, or is `null` or `undefined`, the number of digits after the + * decimal point defaults to the minimum number of digits necessary to represent the value + * exactly. + * + * If `roundingMode` is omitted or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * Throws if `decimalPlaces` or `roundingMode` is invalid. + * + * ```ts + * x = 45.6 + * y = new BigNumber(x) + * x.toExponential() // '4.56e+1' + * y.toExponential() // '4.56e+1' + * x.toExponential(0) // '5e+1' + * y.toExponential(0) // '5e+1' + * x.toExponential(1) // '4.6e+1' + * y.toExponential(1) // '4.6e+1' + * y.toExponential(1, 1) // '4.5e+1' (ROUND_DOWN) + * x.toExponential(3) // '4.560e+1' + * y.toExponential(3) // '4.560e+1' + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + toExponential(decimalPlaces?: number, roundingMode?: BigNumber.RoundingMode): string; + + /** + * Returns a string representing the value of this BigNumber in normal (fixed-point) notation + * rounded to `decimalPlaces` decimal places using rounding mode `roundingMode`. + * + * If the value of this BigNumber in normal notation has fewer than `decimalPlaces` fraction + * digits, the return value will be appended with zeros accordingly. + * + * Unlike `Number.prototype.toFixed`, which returns exponential notation if a number is greater or + * equal to 10**21, this method will always return normal notation. + * + * If `decimalPlaces` is omitted or is `null` or `undefined`, the return value will be unrounded + * and in normal notation. This is also unlike `Number.prototype.toFixed`, which returns the value + * to zero decimal places. It is useful when normal notation is required and the current + * `EXPONENTIAL_AT` setting causes `toString` to return exponential notation. + * + * If `roundingMode` is omitted or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * Throws if `decimalPlaces` or `roundingMode` is invalid. + * + * ```ts + * x = 3.456 + * y = new BigNumber(x) + * x.toFixed() // '3' + * y.toFixed() // '3.456' + * y.toFixed(0) // '3' + * x.toFixed(2) // '3.46' + * y.toFixed(2) // '3.46' + * y.toFixed(2, 1) // '3.45' (ROUND_DOWN) + * x.toFixed(5) // '3.45600' + * y.toFixed(5) // '3.45600' + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + toFixed(decimalPlaces?: number, roundingMode?: BigNumber.RoundingMode): string; + + /** + * Returns a string representing the value of this BigNumber in normal (fixed-point) notation + * rounded to `decimalPlaces` decimal places using rounding mode `roundingMode`, and formatted + * according to the properties of the `FORMAT` object. + * + * The properties of the `FORMAT` object are shown in the examples below. + * + * If `decimalPlaces` is omitted or is `null` or `undefined`, then the return value is not + * rounded to a fixed number of decimal places. + * + * If `roundingMode` is omitted or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * Throws if `decimalPlaces` or `roundingMode` is invalid. + * + * ```ts + * format = { + * decimalSeparator: '.', + * groupSeparator: ',', + * groupSize: 3, + * secondaryGroupSize: 0, + * fractionGroupSeparator: ' ', + * fractionGroupSize: 0 + * } + * BigNumber.config({ FORMAT: format }) + * + * x = new BigNumber('123456789.123456789') + * x.toFormat() // '123,456,789.123456789' + * x.toFormat(1) // '123,456,789.1' + * + * format.groupSeparator = ' ' + * format.fractionGroupSize = 5 + * x.toFormat() // '123 456 789.12345 6789' + * + * BigNumber.config({ + * FORMAT: { + * decimalSeparator: ',', + * groupSeparator: '.', + * groupSize: 3, + * secondaryGroupSize: 2 + * } + * }) + * + * x.toFormat(6) // '12.34.56.789,123' + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + * @param [roundingMode] Rounding mode, integer, 0 to 8. + */ + toFormat(decimalPlaces?: number, roundingMode?: BigNumber.RoundingMode): string; + + /** + * Returns a string array representing the value of this BigNumber as a simple fraction with an + * integer numerator and an integer denominator. The denominator will be a positive non-zero value + * less than or equal to `max_denominator`. + * + * If a maximum denominator, `max_denominator`, is not specified, or is `null` or `undefined`, the + * denominator will be the lowest value necessary to represent the number exactly. + * + * Throws if `max_denominator` is invalid. + * + * ```ts + * x = new BigNumber(1.75) + * x.toFraction() // '7, 4' + * + * pi = new BigNumber('3.14159265358') + * pi.toFraction() // '157079632679,50000000000' + * pi.toFraction(100000) // '312689, 99532' + * pi.toFraction(10000) // '355, 113' + * pi.toFraction(100) // '311, 99' + * pi.toFraction(10) // '22, 7' + * pi.toFraction(1) // '3, 1' + * ``` + * + * @param [max_denominator] The maximum denominator, integer > 0, or Infinity. + */ + toFraction(max_denominator?: BigNumber.Value): BigNumber[]; + + /** + * As `valueOf`. + */ + toJSON(): string; + + /** + * Returns the value of this BigNumber as a JavaScript primitive number. + * + * Using the unary plus operator gives the same result. + * + * ```ts + * x = new BigNumber(456.789) + * x.toNumber() // 456.789 + * +x // 456.789 + * + * y = new BigNumber('45987349857634085409857349856430985') + * y.toNumber() // 4.598734985763409e+34 + * + * z = new BigNumber(-0) + * 1 / z.toNumber() // -Infinity + * 1 / +z // -Infinity + * ``` + */ + toNumber(): number; + + /** + * Returns a string representing the value of this BigNumber rounded to `significantDigits` + * significant digits using rounding mode `roundingMode`. + * + * If `significantDigits` is less than the number of digits necessary to represent the integer + * part of the value in normal (fixed-point) notation, then exponential notation is used. + * + * If `significantDigits` is omitted, or is `null` or `undefined`, then the return value is the + * same as `n.toString()`. + * + * If `roundingMode` is omitted or is `null` or `undefined`, `ROUNDING_MODE` is used. + * + * Throws if `significantDigits` or `roundingMode` is invalid. + * + * ```ts + * x = 45.6 + * y = new BigNumber(x) + * x.toPrecision() // '45.6' + * y.toPrecision() // '45.6' + * x.toPrecision(1) // '5e+1' + * y.toPrecision(1) // '5e+1' + * y.toPrecision(2, 0) // '4.6e+1' (ROUND_UP) + * y.toPrecision(2, 1) // '4.5e+1' (ROUND_DOWN) + * x.toPrecision(5) // '45.600' + * y.toPrecision(5) // '45.600' + * ``` + * + * @param [significantDigits] Significant digits, integer, 1 to 1e+9. + * @param [roundingMode] Rounding mode, integer 0 to 8. + */ + toPrecision(significantDigits?: number, roundingMode?: BigNumber.RoundingMode): string; + + /** + * Returns a string representing the value of this BigNumber in base `base`, or base 10 if `base` + * is omitted or is `null` or `undefined`. + * + * For bases above 10, and using the default base conversion alphabet (see `ALPHABET`), values + * from 10 to 35 are represented by a-z (the same as `Number.prototype.toString`). + * + * If a base is specified the value is rounded according to the current `DECIMAL_PLACES` and + * `ROUNDING_MODE` settings, otherwise it is not. + * + * If a base is not specified, and this BigNumber has a positive exponent that is equal to or + * greater than the positive component of the current `EXPONENTIAL_AT` setting, or a negative + * exponent equal to or less than the negative component of the setting, then exponential notation + * is returned. + * + * If `base` is `null` or `undefined` it is ignored. + * + * Throws if `base` is invalid. + * + * ```ts + * x = new BigNumber(750000) + * x.toString() // '750000' + * BigNumber.config({ EXPONENTIAL_AT: 5 }) + * x.toString() // '7.5e+5' + * + * y = new BigNumber(362.875) + * y.toString(2) // '101101010.111' + * y.toString(9) // '442.77777777777777777778' + * y.toString(32) // 'ba.s' + * + * BigNumber.config({ DECIMAL_PLACES: 4 }); + * z = new BigNumber('1.23456789') + * z.toString() // '1.23456789' + * z.toString(10) // '1.2346' + * ``` + * + * @param [base] The base, integer, 2 to 36 (or `ALPHABET.length`, see `ALPHABET`). + */ + toString(base?: number): string; + + /** + * As `toString`, but does not accept a base argument and includes the minus sign for negative + * zero. + * + * ``ts + * x = new BigNumber('-0') + * x.toString() // '0' + * x.valueOf() // '-0' + * y = new BigNumber('1.777e+457') + * y.valueOf() // '1.777e+457' + * ``` + */ + valueOf(): string; + + /** + * Returns a new independent BigNumber constructor with configuration as described by `object`, or + * with the default configuration if object is `null` or `undefined`. + * + * Throws if `object` is not an object. + * + * ```ts + * BigNumber.config({ DECIMAL_PLACES: 5 }) + * BN = BigNumber.clone({ DECIMAL_PLACES: 9 }) + * + * x = new BigNumber(1) + * y = new BN(1) + * + * x.div(3) // 0.33333 + * y.div(3) // 0.333333333 + * + * // BN = BigNumber.clone({ DECIMAL_PLACES: 9 }) is equivalent to: + * BN = BigNumber.clone() + * BN.config({ DECIMAL_PLACES: 9 }) + * ``` + * + * @param [object] The configuration object. + */ + static clone(object?: BigNumber.Config): BigNumber.Constructor; + + /** + * Configures the settings that apply to this BigNumber constructor. + * + * The configuration object, `object`, contains any number of the properties shown in the example + * below. + * + * Returns an object with the above properties and their current values. + * + * Throws if `object` is not an object, or if an invalid value is assigned to one or more of the + * properties. + * + * ```ts + * BigNumber.config({ + * DECIMAL_PLACES: 40, + * ROUNDING_MODE: BigNumber.ROUND_HALF_CEIL, + * EXPONENTIAL_AT: [-10, 20], + * RANGE: [-500, 500], + * CRYPTO: true, + * MODULO_MODE: BigNumber.ROUND_FLOOR, + * POW_PRECISION: 80, + * FORMAT: { + * groupSize: 3, + * groupSeparator: ' ', + * decimalSeparator: ',' + * }, + * ALPHABET: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' + * }); + * + * BigNumber.config().DECIMAL_PLACES // 40 + * ``` + * + * @param object The configuration object. + */ + static config(object: BigNumber.Config): BigNumber.Config; + + /** + * Returns `true` if `value` is a BigNumber instance, otherwise returns `false`. + * + * ```ts + * x = 42 + * y = new BigNumber(x) + * + * BigNumber.isBigNumber(x) // false + * y instanceof BigNumber // true + * BigNumber.isBigNumber(y) // true + * + * BN = BigNumber.clone(); + * z = new BN(x) + * z instanceof BigNumber // false + * BigNumber.isBigNumber(z) // true + * ``` + * + * @param value The value to test. + */ + static isBigNumber(value: any): boolean; + + /** + * + * Returns a BigNumber whose value is the maximum of the arguments. + * + * Accepts either an argument list or an array of values. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber('3257869345.0378653') + * BigNumber.maximum(4e9, x, '123456789.9') // '4000000000' + * + * arr = [12, '13', new BigNumber(14)] + * BigNumber.maximum(arr) // '14' + * ``` + * + * @param n A numeric value. + */ + static maximum(...n: BigNumber.Value[]): BigNumber; + + /** + * Returns a BigNumber whose value is the maximum of the arguments. + * + * Accepts either an argument list or an array of values. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber('3257869345.0378653') + * BigNumber.max(4e9, x, '123456789.9') // '4000000000' + * + * arr = [12, '13', new BigNumber(14)] + * BigNumber.max(arr) // '14' + * ``` + * + * @param n A numeric value. + */ + static max(...n: BigNumber.Value[]): BigNumber; + + /** + * Returns a BigNumber whose value is the minimum of the arguments. + * + * Accepts either an argument list or an array of values. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber('3257869345.0378653') + * BigNumber.minimum(4e9, x, '123456789.9') // '123456789.9' + * + * arr = [2, new BigNumber(-14), '-15.9999', -12] + * BigNumber.minimum(arr) // '-15.9999' + * ``` + * + * @param n A numeric value. + */ + static minimum(...n: BigNumber.Value[]): BigNumber; + + /** + * Returns a BigNumber whose value is the minimum of the arguments. + * + * Accepts either an argument list or an array of values. + * + * The return value is always exact and unrounded. + * + * ```ts + * x = new BigNumber('3257869345.0378653') + * BigNumber.min(4e9, x, '123456789.9') // '123456789.9' + * + * arr = [2, new BigNumber(-14), '-15.9999', -12] + * BigNumber.min(arr) // '-15.9999' + * ``` + * + * @param n A numeric value. + */ + static min(...n: BigNumber.Value[]): BigNumber; + + /** + * Returns a new BigNumber with a pseudo-random value equal to or greater than 0 and less than 1. + * + * The return value will have `decimalPlaces` decimal places, or less if trailing zeros are + * produced. If `decimalPlaces` is omitted, the current `DECIMAL_PLACES` setting will be used. + * + * Depending on the value of this BigNumber constructor's `CRYPTO` setting and the support for the + * `crypto` object in the host environment, the random digits of the return value are generated by + * either `Math.random` (fastest), `crypto.getRandomValues` (Web Cryptography API in recent + * browsers) or `crypto.randomBytes` (Node.js). + * + * If `CRYPTO` is true, i.e. one of the `crypto` methods is to be used, the value of a returned + * BigNumber should be cryptographically secure and statistically indistinguishable from a random + * value. + * + * Throws if `decimalPlaces` is invalid. + * + * ```ts + * BigNumber.config({ DECIMAL_PLACES: 10 }) + * BigNumber.random() // '0.4117936847' + * BigNumber.random(20) // '0.78193327636914089009' + * ``` + * + * @param [decimalPlaces] Decimal places, integer, 0 to 1e+9. + */ + static random(decimalPlaces?: number): BigNumber; + + /** + * Configures the settings that apply to this BigNumber constructor. + * + * The configuration object, `object`, contains any number of the properties shown in the example + * below. + * + * Returns an object with the above properties and their current values. + * + * Throws if `object` is not an object, or if an invalid value is assigned to one or more of the + * properties. + * + * ```ts + * BigNumber.set({ + * DECIMAL_PLACES: 40, + * ROUNDING_MODE: BigNumber.ROUND_HALF_CEIL, + * EXPONENTIAL_AT: [-10, 20], + * RANGE: [-500, 500], + * CRYPTO: true, + * MODULO_MODE: BigNumber.ROUND_FLOOR, + * POW_PRECISION: 80, + * FORMAT: { + * groupSize: 3, + * groupSeparator: ' ', + * decimalSeparator: ',' + * }, + * ALPHABET: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' + * }); + * + * BigNumber.set().DECIMAL_PLACES // 40 + * ``` + * + * @param object The configuration object. + */ + static set(object: BigNumber.Config): BigNumber.Config; + + /** + * Helps ES6 import. + */ + private static readonly default?: BigNumber.Constructor; + + /** + * Helps ES6 import. + */ + private static readonly BigNumber?: BigNumber.Constructor; + + /** + * Rounds away from zero. + */ + static readonly ROUND_UP: 0; + + /** + * Rounds towards zero. + */ + static readonly ROUND_DOWN: 1; + + /** + * Rounds towards Infinity. + */ + static readonly ROUND_CEIL: 2; + + /** + * Rounds towards -Infinity. + */ + static readonly ROUND_FLOOR: 3; + + /** + * Rounds towards nearest neighbour. If equidistant, rounds away from zero . + */ + static readonly ROUND_HALF_UP: 4; + + /** + * Rounds towards nearest neighbour. If equidistant, rounds towards zero. + */ + static readonly ROUND_HALF_DOWN: 5; + + /** + * Rounds towards nearest neighbour. If equidistant, rounds towards even neighbour. + */ + static readonly ROUND_HALF_EVEN: 6; + + /** + * Rounds towards nearest neighbour. If equidistant, rounds towards Infinity. + */ + static readonly ROUND_HALF_CEIL: 7; + + /** + * Rounds towards nearest neighbour. If equidistant, rounds towards -Infinity. + */ + static readonly ROUND_HALF_FLOOR: 8; + + /** + * See `MODULO_MODE`. + */ + static readonly EUCLID: 9; + + /** + * To aid in debugging, if a `BigNumber.DEBUG` property is `true` then an error will be thrown + * on an invalid `BigNumber.Value`. + * + * ```ts + * // No error, and BigNumber NaN is returned. + * new BigNumber('blurgh') // 'NaN' + * new BigNumber(9, 2) // 'NaN' + * BigNumber.DEBUG = true + * new BigNumber('blurgh') // '[BigNumber Error] Not a number' + * new BigNumber(9, 2) // '[BigNumber Error] Not a base 2 number' + * ``` + * + * An error will also be thrown if a `BigNumber.Value` is of type number with more than 15 + * significant digits, as calling `toString` or `valueOf` on such numbers may not result + * in the intended value. + * + * ```ts + * console.log(823456789123456.3) // 823456789123456.2 + * // No error, and the returned BigNumber does not have the same value as the number literal. + * new BigNumber(823456789123456.3) // '823456789123456.2' + * BigNumber.DEBUG = true + * new BigNumber(823456789123456.3) + * // '[BigNumber Error] Number primitive has more than 15 significant digits' + * ``` + * + */ + static DEBUG?: boolean; +} diff --git a/node_modules/bignumber.js/bignumber.js b/node_modules/bignumber.js/bignumber.js new file mode 100644 index 0000000..78bb97f --- /dev/null +++ b/node_modules/bignumber.js/bignumber.js @@ -0,0 +1,2814 @@ +;(function (globalObject) { + 'use strict'; + +/* + * bignumber.js v7.2.1 + * A JavaScript library for arbitrary-precision arithmetic. + * https://github.com/MikeMcl/bignumber.js + * Copyright (c) 2018 Michael Mclaughlin + * MIT Licensed. + * + * BigNumber.prototype methods | BigNumber methods + * | + * absoluteValue abs | clone + * comparedTo | config set + * decimalPlaces dp | DECIMAL_PLACES + * dividedBy div | ROUNDING_MODE + * dividedToIntegerBy idiv | EXPONENTIAL_AT + * exponentiatedBy pow | RANGE + * integerValue | CRYPTO + * isEqualTo eq | MODULO_MODE + * isFinite | POW_PRECISION + * isGreaterThan gt | FORMAT + * isGreaterThanOrEqualTo gte | ALPHABET + * isInteger | isBigNumber + * isLessThan lt | maximum max + * isLessThanOrEqualTo lte | minimum min + * isNaN | random + * isNegative | + * isPositive | + * isZero | + * minus | + * modulo mod | + * multipliedBy times | + * negated | + * plus | + * precision sd | + * shiftedBy | + * squareRoot sqrt | + * toExponential | + * toFixed | + * toFormat | + * toFraction | + * toJSON | + * toNumber | + * toPrecision | + * toString | + * valueOf | + * + */ + + + var BigNumber, + isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, + + mathceil = Math.ceil, + mathfloor = Math.floor, + + bignumberError = '[BigNumber Error] ', + tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ', + + BASE = 1e14, + LOG_BASE = 14, + MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1 + // MAX_INT32 = 0x7fffffff, // 2^31 - 1 + POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], + SQRT_BASE = 1e7, + + // EDITABLE + // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and + // the arguments to toExponential, toFixed, toFormat, and toPrecision. + MAX = 1E9; // 0 to MAX_INT32 + + + /* + * Create and return a BigNumber constructor. + */ + function clone(configObject) { + var div, convertBase, parseNumeric, + P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null }, + ONE = new BigNumber(1), + + + //----------------------------- EDITABLE CONFIG DEFAULTS ------------------------------- + + + // The default values below must be integers within the inclusive ranges stated. + // The values can also be changed at run-time using BigNumber.set. + + // The maximum number of decimal places for operations involving division. + DECIMAL_PLACES = 20, // 0 to MAX + + // The rounding mode used when rounding to the above decimal places, and when using + // toExponential, toFixed, toFormat and toPrecision, and round (default value). + // UP 0 Away from zero. + // DOWN 1 Towards zero. + // CEIL 2 Towards +Infinity. + // FLOOR 3 Towards -Infinity. + // HALF_UP 4 Towards nearest neighbour. If equidistant, up. + // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. + // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. + // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. + // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. + ROUNDING_MODE = 4, // 0 to 8 + + // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] + + // The exponent value at and beneath which toString returns exponential notation. + // Number type: -7 + TO_EXP_NEG = -7, // 0 to -MAX + + // The exponent value at and above which toString returns exponential notation. + // Number type: 21 + TO_EXP_POS = 21, // 0 to MAX + + // RANGE : [MIN_EXP, MAX_EXP] + + // The minimum exponent value, beneath which underflow to zero occurs. + // Number type: -324 (5e-324) + MIN_EXP = -1e7, // -1 to -MAX + + // The maximum exponent value, above which overflow to Infinity occurs. + // Number type: 308 (1.7976931348623157e+308) + // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow. + MAX_EXP = 1e7, // 1 to MAX + + // Whether to use cryptographically-secure random number generation, if available. + CRYPTO = false, // true or false + + // The modulo mode used when calculating the modulus: a mod n. + // The quotient (q = a / n) is calculated according to the corresponding rounding mode. + // The remainder (r) is calculated as: r = a - n * q. + // + // UP 0 The remainder is positive if the dividend is negative, else is negative. + // DOWN 1 The remainder has the same sign as the dividend. + // This modulo mode is commonly known as 'truncated division' and is + // equivalent to (a % n) in JavaScript. + // FLOOR 3 The remainder has the same sign as the divisor (Python %). + // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function. + // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). + // The remainder is always positive. + // + // The truncated division, floored division, Euclidian division and IEEE 754 remainder + // modes are commonly used for the modulus operation. + // Although the other rounding modes can also be used, they may not give useful results. + MODULO_MODE = 1, // 0 to 9 + + // The maximum number of significant digits of the result of the exponentiatedBy operation. + // If POW_PRECISION is 0, there will be unlimited significant digits. + POW_PRECISION = 0, // 0 to MAX + + // The format specification used by the BigNumber.prototype.toFormat method. + FORMAT = { + decimalSeparator: '.', + groupSeparator: ',', + groupSize: 3, + secondaryGroupSize: 0, + fractionGroupSeparator: '\xA0', // non-breaking space + fractionGroupSize: 0 + }, + + // The alphabet used for base conversion. + // It must be at least 2 characters long, with no '.' or repeated character. + // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' + ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz'; + + + //------------------------------------------------------------------------------------------ + + + // CONSTRUCTOR + + + /* + * The BigNumber constructor and exported function. + * Create and return a new instance of a BigNumber object. + * + * n {number|string|BigNumber} A numeric value. + * [b] {number} The base of n. Integer, 2 to ALPHABET.length inclusive. + */ + function BigNumber(n, b) { + var alphabet, c, caseChanged, e, i, isNum, len, str, + x = this; + + // Enable constructor usage without new. + if (!(x instanceof BigNumber)) { + + // Don't throw on constructor call without new (#81). + // '[BigNumber Error] Constructor call without new: {n}' + //throw Error(bignumberError + ' Constructor call without new: ' + n); + return new BigNumber(n, b); + } + + if (b == null) { + + // Duplicate. + if (n instanceof BigNumber) { + x.s = n.s; + x.e = n.e; + x.c = (n = n.c) ? n.slice() : n; + return; + } + + isNum = typeof n == 'number'; + + if (isNum && n * 0 == 0) { + + // Use `1 / n` to handle minus zero also. + x.s = 1 / n < 0 ? (n = -n, -1) : 1; + + // Faster path for integers. + if (n === ~~n) { + for (e = 0, i = n; i >= 10; i /= 10, e++); + x.e = e; + x.c = [n]; + return; + } + + str = n + ''; + } else { + if (!isNumeric.test(str = n + '')) return parseNumeric(x, str, isNum); + x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; + } + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + + // Exponential form? + if ((i = str.search(/e/i)) > 0) { + + // Determine exponent. + if (e < 0) e = i; + e += +str.slice(i + 1); + str = str.substring(0, i); + } else if (e < 0) { + + // Integer. + e = str.length; + } + + } else { + + // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + intCheck(b, 2, ALPHABET.length, 'Base'); + str = n + ''; + + // Allow exponential notation to be used with base 10 argument, while + // also rounding to DECIMAL_PLACES as with other bases. + if (b == 10) { + x = new BigNumber(n instanceof BigNumber ? n : str); + return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE); + } + + isNum = typeof n == 'number'; + + if (isNum) { + + // Avoid potential interpretation of Infinity and NaN as base 44+ values. + if (n * 0 != 0) return parseNumeric(x, str, isNum, b); + + x.s = 1 / n < 0 ? (str = str.slice(1), -1) : 1; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, '').length > 15) { + throw Error + (tooManyDigits + n); + } + + // Prevent later check for length on converted number. + isNum = false; + } else { + x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; + } + + alphabet = ALPHABET.slice(0, b); + e = i = 0; + + // Check that str is a valid base b number. + // Don't use RegExp so alphabet can contain special characters. + for (len = str.length; i < len; i++) { + if (alphabet.indexOf(c = str.charAt(i)) < 0) { + if (c == '.') { + + // If '.' is not the first character and it has not be found before. + if (i > e) { + e = len; + continue; + } + } else if (!caseChanged) { + + // Allow e.g. hexadecimal 'FF' as well as 'ff'. + if (str == str.toUpperCase() && (str = str.toLowerCase()) || + str == str.toLowerCase() && (str = str.toUpperCase())) { + caseChanged = true; + i = -1; + e = 0; + continue; + } + } + + return parseNumeric(x, n + '', isNum, b); + } + } + + str = convertBase(str, b, 10, x.s); + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + else e = str.length; + } + + // Determine leading zeros. + for (i = 0; str.charCodeAt(i) === 48; i++); + + // Determine trailing zeros. + for (len = str.length; str.charCodeAt(--len) === 48;); + + str = str.slice(i, ++len); + + if (str) { + len -= i; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (isNum && BigNumber.DEBUG && + len > 15 && (n > MAX_SAFE_INTEGER || n !== mathfloor(n))) { + throw Error + (tooManyDigits + (x.s * n)); + } + + e = e - i - 1; + + // Overflow? + if (e > MAX_EXP) { + + // Infinity. + x.c = x.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + x.c = [x.e = 0]; + } else { + x.e = e; + x.c = []; + + // Transform base + + // e is the base 10 exponent. + // i is where to slice str to get the first element of the coefficient array. + i = (e + 1) % LOG_BASE; + if (e < 0) i += LOG_BASE; + + if (i < len) { + if (i) x.c.push(+str.slice(0, i)); + + for (len -= LOG_BASE; i < len;) { + x.c.push(+str.slice(i, i += LOG_BASE)); + } + + str = str.slice(i); + i = LOG_BASE - str.length; + } else { + i -= len; + } + + for (; i--; str += '0'); + x.c.push(+str); + } + } else { + + // Zero. + x.c = [x.e = 0]; + } + } + + + // CONSTRUCTOR PROPERTIES + + + BigNumber.clone = clone; + + BigNumber.ROUND_UP = 0; + BigNumber.ROUND_DOWN = 1; + BigNumber.ROUND_CEIL = 2; + BigNumber.ROUND_FLOOR = 3; + BigNumber.ROUND_HALF_UP = 4; + BigNumber.ROUND_HALF_DOWN = 5; + BigNumber.ROUND_HALF_EVEN = 6; + BigNumber.ROUND_HALF_CEIL = 7; + BigNumber.ROUND_HALF_FLOOR = 8; + BigNumber.EUCLID = 9; + + + /* + * Configure infrequently-changing library-wide settings. + * + * Accept an object with the following optional properties (if the value of a property is + * a number, it must be an integer within the inclusive range stated): + * + * DECIMAL_PLACES {number} 0 to MAX + * ROUNDING_MODE {number} 0 to 8 + * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX] + * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX] + * CRYPTO {boolean} true or false + * MODULO_MODE {number} 0 to 9 + * POW_PRECISION {number} 0 to MAX + * ALPHABET {string} A string of two or more unique characters which does + * not contain '.'. + * FORMAT {object} An object with some of the following properties: + * decimalSeparator {string} + * groupSeparator {string} + * groupSize {number} + * secondaryGroupSize {number} + * fractionGroupSeparator {string} + * fractionGroupSize {number} + * + * (The values assigned to the above FORMAT object properties are not checked for validity.) + * + * E.g. + * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) + * + * Ignore properties/parameters set to null or undefined, except for ALPHABET. + * + * Return an object with the properties current values. + */ + BigNumber.config = BigNumber.set = function (obj) { + var p, v; + + if (obj != null) { + + if (typeof obj == 'object') { + + // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + DECIMAL_PLACES = v; + } + + // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. + // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) { + v = obj[p]; + intCheck(v, 0, 8, p); + ROUNDING_MODE = v; + } + + // EXPONENTIAL_AT {number|number[]} + // Integer, -MAX to MAX inclusive or + // [integer -MAX to 0 inclusive, 0 to MAX inclusive]. + // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) { + v = obj[p]; + if (isArray(v)) { + intCheck(v[0], -MAX, 0, p); + intCheck(v[1], 0, MAX, p); + TO_EXP_NEG = v[0]; + TO_EXP_POS = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v); + } + } + + // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or + // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. + // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}' + if (obj.hasOwnProperty(p = 'RANGE')) { + v = obj[p]; + if (isArray(v)) { + intCheck(v[0], -MAX, -1, p); + intCheck(v[1], 1, MAX, p); + MIN_EXP = v[0]; + MAX_EXP = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + if (v) { + MIN_EXP = -(MAX_EXP = v < 0 ? -v : v); + } else { + throw Error + (bignumberError + p + ' cannot be zero: ' + v); + } + } + } + + // CRYPTO {boolean} true or false. + // '[BigNumber Error] CRYPTO not true or false: {v}' + // '[BigNumber Error] crypto unavailable' + if (obj.hasOwnProperty(p = 'CRYPTO')) { + v = obj[p]; + if (v === !!v) { + if (v) { + if (typeof crypto != 'undefined' && crypto && + (crypto.getRandomValues || crypto.randomBytes)) { + CRYPTO = v; + } else { + CRYPTO = !v; + throw Error + (bignumberError + 'crypto unavailable'); + } + } else { + CRYPTO = v; + } + } else { + throw Error + (bignumberError + p + ' not true or false: ' + v); + } + } + + // MODULO_MODE {number} Integer, 0 to 9 inclusive. + // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'MODULO_MODE')) { + v = obj[p]; + intCheck(v, 0, 9, p); + MODULO_MODE = v; + } + + // POW_PRECISION {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'POW_PRECISION')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + POW_PRECISION = v; + } + + // FORMAT {object} + // '[BigNumber Error] FORMAT not an object: {v}' + if (obj.hasOwnProperty(p = 'FORMAT')) { + v = obj[p]; + if (typeof v == 'object') FORMAT = v; + else throw Error + (bignumberError + p + ' not an object: ' + v); + } + + // ALPHABET {string} + // '[BigNumber Error] ALPHABET invalid: {v}' + if (obj.hasOwnProperty(p = 'ALPHABET')) { + v = obj[p]; + + // Disallow if only one character, or contains '.' or a repeated character. + if (typeof v == 'string' && !/^.$|\.|(.).*\1/.test(v)) { + ALPHABET = v; + } else { + throw Error + (bignumberError + p + ' invalid: ' + v); + } + } + + } else { + + // '[BigNumber Error] Object expected: {v}' + throw Error + (bignumberError + 'Object expected: ' + obj); + } + } + + return { + DECIMAL_PLACES: DECIMAL_PLACES, + ROUNDING_MODE: ROUNDING_MODE, + EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], + RANGE: [MIN_EXP, MAX_EXP], + CRYPTO: CRYPTO, + MODULO_MODE: MODULO_MODE, + POW_PRECISION: POW_PRECISION, + FORMAT: FORMAT, + ALPHABET: ALPHABET + }; + }; + + + /* + * Return true if v is a BigNumber instance, otherwise return false. + * + * v {any} + */ + BigNumber.isBigNumber = function (v) { + return v instanceof BigNumber || v && v._isBigNumber === true || false; + }; + + + /* + * Return a new BigNumber whose value is the maximum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.maximum = BigNumber.max = function () { + return maxOrMin(arguments, P.lt); + }; + + + /* + * Return a new BigNumber whose value is the minimum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.minimum = BigNumber.min = function () { + return maxOrMin(arguments, P.gt); + }; + + + /* + * Return a new BigNumber with a random value equal to or greater than 0 and less than 1, + * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing + * zeros are produced). + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}' + * '[BigNumber Error] crypto unavailable' + */ + BigNumber.random = (function () { + var pow2_53 = 0x20000000000000; + + // Return a 53 bit integer n, where 0 <= n < 9007199254740992. + // Check if Math.random() produces more than 32 bits of randomness. + // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits. + // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1. + var random53bitInt = (Math.random() * pow2_53) & 0x1fffff + ? function () { return mathfloor(Math.random() * pow2_53); } + : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) + + (Math.random() * 0x800000 | 0); }; + + return function (dp) { + var a, b, e, k, v, + i = 0, + c = [], + rand = new BigNumber(ONE); + + if (dp == null) dp = DECIMAL_PLACES; + else intCheck(dp, 0, MAX); + + k = mathceil(dp / LOG_BASE); + + if (CRYPTO) { + + // Browsers supporting crypto.getRandomValues. + if (crypto.getRandomValues) { + + a = crypto.getRandomValues(new Uint32Array(k *= 2)); + + for (; i < k;) { + + // 53 bits: + // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) + // 11111 11111111 11111111 11111111 11100000 00000000 00000000 + // ((Math.pow(2, 32) - 1) >>> 11).toString(2) + // 11111 11111111 11111111 + // 0x20000 is 2^21. + v = a[i] * 0x20000 + (a[i + 1] >>> 11); + + // Rejection sampling: + // 0 <= v < 9007199254740992 + // Probability that v >= 9e15, is + // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 + if (v >= 9e15) { + b = crypto.getRandomValues(new Uint32Array(2)); + a[i] = b[0]; + a[i + 1] = b[1]; + } else { + + // 0 <= v <= 8999999999999999 + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 2; + } + } + i = k / 2; + + // Node.js supporting crypto.randomBytes. + } else if (crypto.randomBytes) { + + // buffer + a = crypto.randomBytes(k *= 7); + + for (; i < k;) { + + // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 + // 0x100000000 is 2^32, 0x1000000 is 2^24 + // 11111 11111111 11111111 11111111 11111111 11111111 11111111 + // 0 <= v < 9007199254740992 + v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) + + (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) + + (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6]; + + if (v >= 9e15) { + crypto.randomBytes(7).copy(a, i); + } else { + + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 7; + } + } + i = k / 7; + } else { + CRYPTO = false; + throw Error + (bignumberError + 'crypto unavailable'); + } + } + + // Use Math.random. + if (!CRYPTO) { + + for (; i < k;) { + v = random53bitInt(); + if (v < 9e15) c[i++] = v % 1e14; + } + } + + k = c[--i]; + dp %= LOG_BASE; + + // Convert trailing digits to zeros according to dp. + if (k && dp) { + v = POWS_TEN[LOG_BASE - dp]; + c[i] = mathfloor(k / v) * v; + } + + // Remove trailing elements which are zero. + for (; c[i] === 0; c.pop(), i--); + + // Zero? + if (i < 0) { + c = [e = 0]; + } else { + + // Remove leading elements which are zero and adjust exponent accordingly. + for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE); + + // Count the digits of the first element of c to determine leading zeros, and... + for (i = 1, v = c[0]; v >= 10; v /= 10, i++); + + // adjust the exponent accordingly. + if (i < LOG_BASE) e -= LOG_BASE - i; + } + + rand.e = e; + rand.c = c; + return rand; + }; + })(); + + + // PRIVATE FUNCTIONS + + + // Called by BigNumber and BigNumber.prototype.toString. + convertBase = (function () { + var decimal = '0123456789'; + + /* + * Convert string of baseIn to an array of numbers of baseOut. + * Eg. toBaseOut('255', 10, 16) returns [15, 15]. + * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5]. + */ + function toBaseOut(str, baseIn, baseOut, alphabet) { + var j, + arr = [0], + arrL, + i = 0, + len = str.length; + + for (; i < len;) { + for (arrL = arr.length; arrL--; arr[arrL] *= baseIn); + + arr[0] += alphabet.indexOf(str.charAt(i++)); + + for (j = 0; j < arr.length; j++) { + + if (arr[j] > baseOut - 1) { + if (arr[j + 1] == null) arr[j + 1] = 0; + arr[j + 1] += arr[j] / baseOut | 0; + arr[j] %= baseOut; + } + } + } + + return arr.reverse(); + } + + // Convert a numeric string of baseIn to a numeric string of baseOut. + // If the caller is toString, we are converting from base 10 to baseOut. + // If the caller is BigNumber, we are converting from baseIn to base 10. + return function (str, baseIn, baseOut, sign, callerIsToString) { + var alphabet, d, e, k, r, x, xc, y, + i = str.indexOf('.'), + dp = DECIMAL_PLACES, + rm = ROUNDING_MODE; + + // Non-integer. + if (i >= 0) { + k = POW_PRECISION; + + // Unlimited precision. + POW_PRECISION = 0; + str = str.replace('.', ''); + y = new BigNumber(baseIn); + x = y.pow(str.length - i); + POW_PRECISION = k; + + // Convert str as if an integer, then restore the fraction part by dividing the + // result by its base raised to a power. + + y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'), + 10, baseOut, decimal); + y.e = y.c.length; + } + + // Convert the number as integer. + + xc = toBaseOut(str, baseIn, baseOut, callerIsToString + ? (alphabet = ALPHABET, decimal) + : (alphabet = decimal, ALPHABET)); + + // xc now represents str as an integer and converted to baseOut. e is the exponent. + e = k = xc.length; + + // Remove trailing zeros. + for (; xc[--k] == 0; xc.pop()); + + // Zero? + if (!xc[0]) return alphabet.charAt(0); + + // Does str represent an integer? If so, no need for the division. + if (i < 0) { + --e; + } else { + x.c = xc; + x.e = e; + + // The sign is needed for correct rounding. + x.s = sign; + x = div(x, y, dp, rm, baseOut); + xc = x.c; + r = x.r; + e = x.e; + } + + // xc now represents str converted to baseOut. + + // THe index of the rounding digit. + d = e + dp + 1; + + // The rounding digit: the digit to the right of the digit that may be rounded up. + i = xc[d]; + + // Look at the rounding digits and mode to determine whether to round up. + + k = baseOut / 2; + r = r || d < 0 || xc[d + 1] != null; + + r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 || + rm == (x.s < 0 ? 8 : 7)); + + // If the index of the rounding digit is not greater than zero, or xc represents + // zero, then the result of the base conversion is zero or, if rounding up, a value + // such as 0.00001. + if (d < 1 || !xc[0]) { + + // 1^-dp or 0 + str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) + : alphabet.charAt(0); + } else { + + // Truncate xc to the required number of decimal places. + xc.length = d; + + // Round up? + if (r) { + + // Rounding up may mean the previous digit has to be rounded up and so on. + for (--baseOut; ++xc[--d] > baseOut;) { + xc[d] = 0; + + if (!d) { + ++e; + xc = [1].concat(xc); + } + } + } + + // Determine trailing zeros. + for (k = xc.length; !xc[--k];); + + // E.g. [4, 11, 15] becomes 4bf. + for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++])); + + // Add leading zeros, decimal point and trailing zeros as required. + str = toFixedPoint(str, e, alphabet.charAt(0)); + } + + // The caller will add the sign. + return str; + }; + })(); + + + // Perform division in the specified base. Called by div and convertBase. + div = (function () { + + // Assume non-zero x and k. + function multiply(x, k, base) { + var m, temp, xlo, xhi, + carry = 0, + i = x.length, + klo = k % SQRT_BASE, + khi = k / SQRT_BASE | 0; + + for (x = x.slice(); i--;) { + xlo = x[i] % SQRT_BASE; + xhi = x[i] / SQRT_BASE | 0; + m = khi * xlo + xhi * klo; + temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry; + carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi; + x[i] = temp % base; + } + + if (carry) x = [carry].concat(x); + + return x; + } + + function compare(a, b, aL, bL) { + var i, cmp; + + if (aL != bL) { + cmp = aL > bL ? 1 : -1; + } else { + + for (i = cmp = 0; i < aL; i++) { + + if (a[i] != b[i]) { + cmp = a[i] > b[i] ? 1 : -1; + break; + } + } + } + + return cmp; + } + + function subtract(a, b, aL, base) { + var i = 0; + + // Subtract b from a. + for (; aL--;) { + a[aL] -= i; + i = a[aL] < b[aL] ? 1 : 0; + a[aL] = i * base + a[aL] - b[aL]; + } + + // Remove leading zeros. + for (; !a[0] && a.length > 1; a.splice(0, 1)); + } + + // x: dividend, y: divisor. + return function (x, y, dp, rm, base) { + var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, + yL, yz, + s = x.s == y.s ? 1 : -1, + xc = x.c, + yc = y.c; + + // Either NaN, Infinity or 0? + if (!xc || !xc[0] || !yc || !yc[0]) { + + return new BigNumber( + + // Return NaN if either NaN, or both Infinity or 0. + !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : + + // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. + xc && xc[0] == 0 || !yc ? s * 0 : s / 0 + ); + } + + q = new BigNumber(s); + qc = q.c = []; + e = x.e - y.e; + s = dp + e + 1; + + if (!base) { + base = BASE; + e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE); + s = s / LOG_BASE | 0; + } + + // Result exponent may be one less then the current value of e. + // The coefficients of the BigNumbers from convertBase may have trailing zeros. + for (i = 0; yc[i] == (xc[i] || 0); i++); + + if (yc[i] > (xc[i] || 0)) e--; + + if (s < 0) { + qc.push(1); + more = true; + } else { + xL = xc.length; + yL = yc.length; + i = 0; + s += 2; + + // Normalise xc and yc so highest order digit of yc is >= base / 2. + + n = mathfloor(base / (yc[0] + 1)); + + // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1. + // if (n > 1 || n++ == 1 && yc[0] < base / 2) { + if (n > 1) { + yc = multiply(yc, n, base); + xc = multiply(xc, n, base); + yL = yc.length; + xL = xc.length; + } + + xi = yL; + rem = xc.slice(0, yL); + remL = rem.length; + + // Add zeros to make remainder as long as divisor. + for (; remL < yL; rem[remL++] = 0); + yz = yc.slice(); + yz = [0].concat(yz); + yc0 = yc[0]; + if (yc[1] >= base / 2) yc0++; + // Not necessary, but to prevent trial digit n > base, when using base 3. + // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15; + + do { + n = 0; + + // Compare divisor and remainder. + cmp = compare(yc, rem, yL, remL); + + // If divisor < remainder. + if (cmp < 0) { + + // Calculate trial digit, n. + + rem0 = rem[0]; + if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); + + // n is how many times the divisor goes into the current remainder. + n = mathfloor(rem0 / yc0); + + // Algorithm: + // product = divisor multiplied by trial digit (n). + // Compare product and remainder. + // If product is greater than remainder: + // Subtract divisor from product, decrement trial digit. + // Subtract product from remainder. + // If product was less than remainder at the last compare: + // Compare new remainder and divisor. + // If remainder is greater than divisor: + // Subtract divisor from remainder, increment trial digit. + + if (n > 1) { + + // n may be > base only when base is 3. + if (n >= base) n = base - 1; + + // product = divisor * trial digit. + prod = multiply(yc, n, base); + prodL = prod.length; + remL = rem.length; + + // Compare product and remainder. + // If product > remainder then trial digit n too high. + // n is 1 too high about 5% of the time, and is not known to have + // ever been more than 1 too high. + while (compare(prod, rem, prodL, remL) == 1) { + n--; + + // Subtract divisor from product. + subtract(prod, yL < prodL ? yz : yc, prodL, base); + prodL = prod.length; + cmp = 1; + } + } else { + + // n is 0 or 1, cmp is -1. + // If n is 0, there is no need to compare yc and rem again below, + // so change cmp to 1 to avoid it. + // If n is 1, leave cmp as -1, so yc and rem are compared again. + if (n == 0) { + + // divisor < remainder, so n must be at least 1. + cmp = n = 1; + } + + // product = divisor + prod = yc.slice(); + prodL = prod.length; + } + + if (prodL < remL) prod = [0].concat(prod); + + // Subtract product from remainder. + subtract(rem, prod, remL, base); + remL = rem.length; + + // If product was < remainder. + if (cmp == -1) { + + // Compare divisor and new remainder. + // If divisor < new remainder, subtract divisor from remainder. + // Trial digit n too low. + // n is 1 too low about 5% of the time, and very rarely 2 too low. + while (compare(yc, rem, yL, remL) < 1) { + n++; + + // Subtract divisor from remainder. + subtract(rem, yL < remL ? yz : yc, remL, base); + remL = rem.length; + } + } + } else if (cmp === 0) { + n++; + rem = [0]; + } // else cmp === 1 and n will be 0 + + // Add the next digit, n, to the result array. + qc[i++] = n; + + // Update the remainder. + if (rem[0]) { + rem[remL++] = xc[xi] || 0; + } else { + rem = [xc[xi]]; + remL = 1; + } + } while ((xi++ < xL || rem[0] != null) && s--); + + more = rem[0] != null; + + // Leading zero? + if (!qc[0]) qc.splice(0, 1); + } + + if (base == BASE) { + + // To calculate q.e, first get the number of digits of qc[0]. + for (i = 1, s = qc[0]; s >= 10; s /= 10, i++); + + round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more); + + // Caller is convertBase. + } else { + q.e = e; + q.r = +more; + } + + return q; + }; + })(); + + + /* + * Return a string representing the value of BigNumber n in fixed-point or exponential + * notation rounded to the specified decimal places or significant digits. + * + * n: a BigNumber. + * i: the index of the last digit required (i.e. the digit that may be rounded up). + * rm: the rounding mode. + * id: 1 (toExponential) or 2 (toPrecision). + */ + function format(n, i, rm, id) { + var c0, e, ne, len, str; + + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + if (!n.c) return n.toString(); + + c0 = n.c[0]; + ne = n.e; + + if (i == null) { + str = coeffToString(n.c); + str = id == 1 || id == 2 && ne <= TO_EXP_NEG + ? toExponential(str, ne) + : toFixedPoint(str, ne, '0'); + } else { + n = round(new BigNumber(n), i, rm); + + // n.e may have changed if the value was rounded up. + e = n.e; + + str = coeffToString(n.c); + len = str.length; + + // toPrecision returns exponential notation if the number of significant digits + // specified is less than the number of digits necessary to represent the integer + // part of the value in fixed-point notation. + + // Exponential notation. + if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) { + + // Append zeros? + for (; len < i; str += '0', len++); + str = toExponential(str, e); + + // Fixed-point notation. + } else { + i -= ne; + str = toFixedPoint(str, e, '0'); + + // Append zeros? + if (e + 1 > len) { + if (--i > 0) for (str += '.'; i--; str += '0'); + } else { + i += e - len; + if (i > 0) { + if (e + 1 == len) str += '.'; + for (; i--; str += '0'); + } + } + } + } + + return n.s < 0 && c0 ? '-' + str : str; + } + + + // Handle BigNumber.max and BigNumber.min. + function maxOrMin(args, method) { + var m, n, + i = 0; + + if (isArray(args[0])) args = args[0]; + m = new BigNumber(args[0]); + + for (; ++i < args.length;) { + n = new BigNumber(args[i]); + + // If any number is NaN, return NaN. + if (!n.s) { + m = n; + break; + } else if (method.call(m, n)) { + m = n; + } + } + + return m; + } + + + /* + * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. + * Called by minus, plus and times. + */ + function normalise(n, c, e) { + var i = 1, + j = c.length; + + // Remove trailing zeros. + for (; !c[--j]; c.pop()); + + // Calculate the base 10 exponent. First get the number of digits of c[0]. + for (j = c[0]; j >= 10; j /= 10, i++); + + // Overflow? + if ((e = i + e * LOG_BASE - 1) > MAX_EXP) { + + // Infinity. + n.c = n.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + n.c = [n.e = 0]; + } else { + n.e = e; + n.c = c; + } + + return n; + } + + + // Handle values that fail the validity test in BigNumber. + parseNumeric = (function () { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, + dotAfter = /^([^.]+)\.$/, + dotBefore = /^\.([^.]+)$/, + isInfinityOrNaN = /^-?(Infinity|NaN)$/, + whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; + + return function (x, str, isNum, b) { + var base, + s = isNum ? str : str.replace(whitespaceOrPlus, ''); + + // No exception on ±Infinity or NaN. + if (isInfinityOrNaN.test(s)) { + x.s = isNaN(s) ? null : s < 0 ? -1 : 1; + x.c = x.e = null; + } else { + if (!isNum) { + + // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i + s = s.replace(basePrefix, function (m, p1, p2) { + base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8; + return !b || b == base ? p1 : m; + }); + + if (b) { + base = b; + + // E.g. '1.' to '1', '.1' to '0.1' + s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1'); + } + + if (str != s) return new BigNumber(s, base); + } + + // '[BigNumber Error] Not a number: {n}' + // '[BigNumber Error] Not a base {b} number: {n}' + if (BigNumber.DEBUG) { + throw Error + (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str); + } + + // NaN + x.c = x.e = x.s = null; + } + } + })(); + + + /* + * Round x to sd significant digits using rounding mode rm. Check for over/under-flow. + * If r is truthy, it is known that there are more digits after the rounding digit. + */ + function round(x, sd, rm, r) { + var d, i, j, k, n, ni, rd, + xc = x.c, + pows10 = POWS_TEN; + + // if x is not Infinity or NaN... + if (xc) { + + // rd is the rounding digit, i.e. the digit after the digit that may be rounded up. + // n is a base 1e14 number, the value of the element of array x.c containing rd. + // ni is the index of n within x.c. + // d is the number of digits of n. + // i is the index of rd within n including leading zeros. + // j is the actual index of rd within n (if < 0, rd is a leading zero). + out: { + + // Get the number of digits of the first element of xc. + for (d = 1, k = xc[0]; k >= 10; k /= 10, d++); + i = sd - d; + + // If the rounding digit is in the first element of xc... + if (i < 0) { + i += LOG_BASE; + j = sd; + n = xc[ni = 0]; + + // Get the rounding digit at index j of n. + rd = n / pows10[d - j - 1] % 10 | 0; + } else { + ni = mathceil((i + 1) / LOG_BASE); + + if (ni >= xc.length) { + + if (r) { + + // Needed by sqrt. + for (; xc.length <= ni; xc.push(0)); + n = rd = 0; + d = 1; + i %= LOG_BASE; + j = i - LOG_BASE + 1; + } else { + break out; + } + } else { + n = k = xc[ni]; + + // Get the number of digits of n. + for (d = 1; k >= 10; k /= 10, d++); + + // Get the index of rd within n. + i %= LOG_BASE; + + // Get the index of rd within n, adjusted for leading zeros. + // The number of leading zeros of n is given by LOG_BASE - d. + j = i - LOG_BASE + d; + + // Get the rounding digit at index j of n. + rd = j < 0 ? 0 : n / pows10[d - j - 1] % 10 | 0; + } + } + + r = r || sd < 0 || + + // Are there any non-zero digits after the rounding digit? + // The expression n % pows10[d - j - 1] returns all digits of n to the right + // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. + xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]); + + r = rm < 4 + ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && + + // Check whether the digit to the left of the rounding digit is odd. + ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 || + rm == (x.s < 0 ? 8 : 7)); + + if (sd < 1 || !xc[0]) { + xc.length = 0; + + if (r) { + + // Convert sd to decimal places. + sd -= x.e + 1; + + // 1, 0.1, 0.01, 0.001, 0.0001 etc. + xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; + x.e = -sd || 0; + } else { + + // Zero. + xc[0] = x.e = 0; + } + + return x; + } + + // Remove excess digits. + if (i == 0) { + xc.length = ni; + k = 1; + ni--; + } else { + xc.length = ni + 1; + k = pows10[LOG_BASE - i]; + + // E.g. 56700 becomes 56000 if 7 is the rounding digit. + // j > 0 means i > number of leading zeros of n. + xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0; + } + + // Round up? + if (r) { + + for (; ;) { + + // If the digit to be rounded up is in the first element of xc... + if (ni == 0) { + + // i will be the length of xc[0] before k is added. + for (i = 1, j = xc[0]; j >= 10; j /= 10, i++); + j = xc[0] += k; + for (k = 1; j >= 10; j /= 10, k++); + + // if i != k the length has increased. + if (i != k) { + x.e++; + if (xc[0] == BASE) xc[0] = 1; + } + + break; + } else { + xc[ni] += k; + if (xc[ni] != BASE) break; + xc[ni--] = 0; + k = 1; + } + } + } + + // Remove trailing zeros. + for (i = xc.length; xc[--i] === 0; xc.pop()); + } + + // Overflow? Infinity. + if (x.e > MAX_EXP) { + x.c = x.e = null; + + // Underflow? Zero. + } else if (x.e < MIN_EXP) { + x.c = [x.e = 0]; + } + } + + return x; + } + + + // PROTOTYPE/INSTANCE METHODS + + + /* + * Return a new BigNumber whose value is the absolute value of this BigNumber. + */ + P.absoluteValue = P.abs = function () { + var x = new BigNumber(this); + if (x.s < 0) x.s = 1; + return x; + }; + + + /* + * Return + * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b), + * -1 if the value of this BigNumber is less than the value of BigNumber(y, b), + * 0 if they have the same value, + * or null if the value of either is NaN. + */ + P.comparedTo = function (y, b) { + return compare(this, new BigNumber(y, b)); + }; + + + /* + * If dp is undefined or null or true or false, return the number of decimal places of the + * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * + * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * [dp] {number} Decimal places: integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.decimalPlaces = P.dp = function (dp, rm) { + var c, n, v, + x = this; + + if (dp != null) { + intCheck(dp, 0, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), dp + x.e + 1, rm); + } + + if (!(c = x.c)) return null; + n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; + + // Subtract the number of trailing zeros of the last number. + if (v = c[v]) for (; v % 10 == 0; v /= 10, n--); + if (n < 0) n = 0; + + return n; + }; + + + /* + * n / 0 = I + * n / N = N + * n / I = 0 + * 0 / n = 0 + * 0 / 0 = N + * 0 / N = N + * 0 / I = 0 + * N / n = N + * N / 0 = N + * N / N = N + * N / I = N + * I / n = I + * I / 0 = I + * I / N = N + * I / I = N + * + * Return a new BigNumber whose value is the value of this BigNumber divided by the value of + * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.dividedBy = P.div = function (y, b) { + return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE); + }; + + + /* + * Return a new BigNumber whose value is the integer part of dividing the value of this + * BigNumber by the value of BigNumber(y, b). + */ + P.dividedToIntegerBy = P.idiv = function (y, b) { + return div(this, new BigNumber(y, b), 0, 1); + }; + + + /* + * Return a BigNumber whose value is the value of this BigNumber exponentiated by n. + * + * If m is present, return the result modulo m. + * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE. + * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE. + * + * The modular power operation works efficiently when x, n, and m are integers, otherwise it + * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0. + * + * n {number|string|BigNumber} The exponent. An integer. + * [m] {number|string|BigNumber} The modulus. + * + * '[BigNumber Error] Exponent not an integer: {n}' + */ + P.exponentiatedBy = P.pow = function (n, m) { + var half, isModExp, k, more, nIsBig, nIsNeg, nIsOdd, y, + x = this; + + n = new BigNumber(n); + + // Allow NaN and ±Infinity, but not other non-integers. + if (n.c && !n.isInteger()) { + throw Error + (bignumberError + 'Exponent not an integer: ' + n); + } + + if (m != null) m = new BigNumber(m); + + // Exponent of MAX_SAFE_INTEGER is 15. + nIsBig = n.e > 14; + + // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0. + if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) { + + // The sign of the result of pow when x is negative depends on the evenness of n. + // If +n overflows to ±Infinity, the evenness of n would be not be known. + y = new BigNumber(Math.pow(+x.valueOf(), nIsBig ? 2 - isOdd(n) : +n)); + return m ? y.mod(m) : y; + } + + nIsNeg = n.s < 0; + + if (m) { + + // x % m returns NaN if abs(m) is zero, or m is NaN. + if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN); + + isModExp = !nIsNeg && x.isInteger() && m.isInteger(); + + if (isModExp) x = x.mod(m); + + // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15. + // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15. + } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 + // [1, 240000000] + ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7 + // [80000000000000] [99999750000000] + : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) { + + // If x is negative and n is odd, k = -0, else k = 0. + k = x.s < 0 && isOdd(n) ? -0 : 0; + + // If x >= 1, k = ±Infinity. + if (x.e > -1) k = 1 / k; + + // If n is negative return ±0, else return ±Infinity. + return new BigNumber(nIsNeg ? 1 / k : k); + + } else if (POW_PRECISION) { + + // Truncating each coefficient array to a length of k after each multiplication + // equates to truncating significant digits to POW_PRECISION + [28, 41], + // i.e. there will be a minimum of 28 guard digits retained. + k = mathceil(POW_PRECISION / LOG_BASE + 2); + } + + if (nIsBig) { + half = new BigNumber(0.5); + nIsOdd = isOdd(n); + } else { + nIsOdd = n % 2; + } + + if (nIsNeg) n.s = 1; + + y = new BigNumber(ONE); + + // Performs 54 loop iterations for n of 9007199254740991. + for (; ;) { + + if (nIsOdd) { + y = y.times(x); + if (!y.c) break; + + if (k) { + if (y.c.length > k) y.c.length = k; + } else if (isModExp) { + y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m)); + } + } + + if (nIsBig) { + n = n.times(half); + round(n, n.e + 1, 1); + if (!n.c[0]) break; + nIsBig = n.e > 14; + nIsOdd = isOdd(n); + } else { + n = mathfloor(n / 2); + if (!n) break; + nIsOdd = n % 2; + } + + x = x.times(x); + + if (k) { + if (x.c && x.c.length > k) x.c.length = k; + } else if (isModExp) { + x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m)); + } + } + + if (isModExp) return y; + if (nIsNeg) y = ONE.div(y); + + return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer + * using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}' + */ + P.integerValue = function (rm) { + var n = new BigNumber(this); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + return round(n, n.e + 1, rm); + }; + + + /* + * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), + * otherwise return false. + */ + P.isEqualTo = P.eq = function (y, b) { + return compare(this, new BigNumber(y, b)) === 0; + }; + + + /* + * Return true if the value of this BigNumber is a finite number, otherwise return false. + */ + P.isFinite = function () { + return !!this.c; + }; + + + /* + * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isGreaterThan = P.gt = function (y, b) { + return compare(this, new BigNumber(y, b)) > 0; + }; + + + /* + * Return true if the value of this BigNumber is greater than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isGreaterThanOrEqualTo = P.gte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0; + + }; + + + /* + * Return true if the value of this BigNumber is an integer, otherwise return false. + */ + P.isInteger = function () { + return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; + }; + + + /* + * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isLessThan = P.lt = function (y, b) { + return compare(this, new BigNumber(y, b)) < 0; + }; + + + /* + * Return true if the value of this BigNumber is less than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isLessThanOrEqualTo = P.lte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0; + }; + + + /* + * Return true if the value of this BigNumber is NaN, otherwise return false. + */ + P.isNaN = function () { + return !this.s; + }; + + + /* + * Return true if the value of this BigNumber is negative, otherwise return false. + */ + P.isNegative = function () { + return this.s < 0; + }; + + + /* + * Return true if the value of this BigNumber is positive, otherwise return false. + */ + P.isPositive = function () { + return this.s > 0; + }; + + + /* + * Return true if the value of this BigNumber is 0 or -0, otherwise return false. + */ + P.isZero = function () { + return !!this.c && this.c[0] == 0; + }; + + + /* + * n - 0 = n + * n - N = N + * n - I = -I + * 0 - n = -n + * 0 - 0 = 0 + * 0 - N = N + * 0 - I = -I + * N - n = N + * N - 0 = N + * N - N = N + * N - I = N + * I - n = I + * I - 0 = I + * I - N = N + * I - I = N + * + * Return a new BigNumber whose value is the value of this BigNumber minus the value of + * BigNumber(y, b). + */ + P.minus = function (y, b) { + var i, j, t, xLTy, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.plus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Either Infinity? + if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN); + + // Either zero? + if (!xc[0] || !yc[0]) { + + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x : + + // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity + ROUNDING_MODE == 3 ? -0 : 0); + } + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Determine which is the bigger number. + if (a = xe - ye) { + + if (xLTy = a < 0) { + a = -a; + t = xc; + } else { + ye = xe; + t = yc; + } + + t.reverse(); + + // Prepend zeros to equalise exponents. + for (b = a; b--; t.push(0)); + t.reverse(); + } else { + + // Exponents equal. Check digit by digit. + j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b; + + for (a = b = 0; b < j; b++) { + + if (xc[b] != yc[b]) { + xLTy = xc[b] < yc[b]; + break; + } + } + } + + // x < y? Point xc to the array of the bigger number. + if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s; + + b = (j = yc.length) - (i = xc.length); + + // Append zeros to xc if shorter. + // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. + if (b > 0) for (; b--; xc[i++] = 0); + b = BASE - 1; + + // Subtract yc from xc. + for (; j > a;) { + + if (xc[--j] < yc[j]) { + for (i = j; i && !xc[--i]; xc[i] = b); + --xc[i]; + xc[j] += BASE; + } + + xc[j] -= yc[j]; + } + + // Remove leading zeros and adjust exponent accordingly. + for (; xc[0] == 0; xc.splice(0, 1), --ye); + + // Zero? + if (!xc[0]) { + + // Following IEEE 754 (2008) 6.3, + // n - n = +0 but n - n = -0 when rounding towards -Infinity. + y.s = ROUNDING_MODE == 3 ? -1 : 1; + y.c = [y.e = 0]; + return y; + } + + // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity + // for finite x and y. + return normalise(y, xc, ye); + }; + + + /* + * n % 0 = N + * n % N = N + * n % I = n + * 0 % n = 0 + * -0 % n = -0 + * 0 % 0 = N + * 0 % N = N + * 0 % I = 0 + * N % n = N + * N % 0 = N + * N % N = N + * N % I = N + * I % n = N + * I % 0 = N + * I % N = N + * I % I = N + * + * Return a new BigNumber whose value is the value of this BigNumber modulo the value of + * BigNumber(y, b). The result depends on the value of MODULO_MODE. + */ + P.modulo = P.mod = function (y, b) { + var q, s, + x = this; + + y = new BigNumber(y, b); + + // Return NaN if x is Infinity or NaN, or y is NaN or zero. + if (!x.c || !y.s || y.c && !y.c[0]) { + return new BigNumber(NaN); + + // Return x if y is Infinity or x is zero. + } else if (!y.c || x.c && !x.c[0]) { + return new BigNumber(x); + } + + if (MODULO_MODE == 9) { + + // Euclidian division: q = sign(y) * floor(x / abs(y)) + // r = x - qy where 0 <= r < abs(y) + s = y.s; + y.s = 1; + q = div(x, y, 0, 3); + y.s = s; + q.s *= s; + } else { + q = div(x, y, 0, MODULO_MODE); + } + + y = x.minus(q.times(y)); + + // To match JavaScript %, ensure sign of zero is sign of dividend. + if (!y.c[0] && MODULO_MODE == 1) y.s = x.s; + + return y; + }; + + + /* + * n * 0 = 0 + * n * N = N + * n * I = I + * 0 * n = 0 + * 0 * 0 = 0 + * 0 * N = N + * 0 * I = N + * N * n = N + * N * 0 = N + * N * N = N + * N * I = N + * I * n = I + * I * 0 = N + * I * N = N + * I * I = I + * + * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value + * of BigNumber(y, b). + */ + P.multipliedBy = P.times = function (y, b) { + var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, + base, sqrtBase, + x = this, + xc = x.c, + yc = (y = new BigNumber(y, b)).c; + + // Either NaN, ±Infinity or ±0? + if (!xc || !yc || !xc[0] || !yc[0]) { + + // Return NaN if either is NaN, or one is 0 and the other is Infinity. + if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { + y.c = y.e = y.s = null; + } else { + y.s *= x.s; + + // Return ±Infinity if either is ±Infinity. + if (!xc || !yc) { + y.c = y.e = null; + + // Return ±0 if either is ±0. + } else { + y.c = [0]; + y.e = 0; + } + } + + return y; + } + + e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE); + y.s *= x.s; + xcL = xc.length; + ycL = yc.length; + + // Ensure xc points to longer array and xcL to its length. + if (xcL < ycL) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i; + + // Initialise the result array with zeros. + for (i = xcL + ycL, zc = []; i--; zc.push(0)); + + base = BASE; + sqrtBase = SQRT_BASE; + + for (i = ycL; --i >= 0;) { + c = 0; + ylo = yc[i] % sqrtBase; + yhi = yc[i] / sqrtBase | 0; + + for (k = xcL, j = i + k; j > i;) { + xlo = xc[--k] % sqrtBase; + xhi = xc[k] / sqrtBase | 0; + m = yhi * xlo + xhi * ylo; + xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c; + c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi; + zc[j--] = xlo % base; + } + + zc[j] = c; + } + + if (c) { + ++e; + } else { + zc.splice(0, 1); + } + + return normalise(y, zc, e); + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber negated, + * i.e. multiplied by -1. + */ + P.negated = function () { + var x = new BigNumber(this); + x.s = -x.s || null; + return x; + }; + + + /* + * n + 0 = n + * n + N = N + * n + I = I + * 0 + n = n + * 0 + 0 = 0 + * 0 + N = N + * 0 + I = I + * N + n = N + * N + 0 = N + * N + N = N + * N + I = N + * I + n = I + * I + 0 = I + * I + N = N + * I + I = I + * + * Return a new BigNumber whose value is the value of this BigNumber plus the value of + * BigNumber(y, b). + */ + P.plus = function (y, b) { + var t, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.minus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Return ±Infinity if either ±Infinity. + if (!xc || !yc) return new BigNumber(a / 0); + + // Either zero? + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0); + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. + if (a = xe - ye) { + if (a > 0) { + ye = xe; + t = yc; + } else { + a = -a; + t = xc; + } + + t.reverse(); + for (; a--; t.push(0)); + t.reverse(); + } + + a = xc.length; + b = yc.length; + + // Point xc to the longer array, and b to the shorter length. + if (a - b < 0) t = yc, yc = xc, xc = t, b = a; + + // Only start adding at yc.length - 1 as the further digits of xc can be ignored. + for (a = 0; b;) { + a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0; + xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; + } + + if (a) { + xc = [a].concat(xc); + ++ye; + } + + // No need to check for zero, as +x + +y != 0 && -x + -y != 0 + // ye = MAX_EXP + 1 possible + return normalise(y, xc, ye); + }; + + + /* + * If sd is undefined or null or true or false, return the number of significant digits of + * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * If sd is true include integer-part trailing zeros in the count. + * + * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive. + * boolean: whether to count integer-part trailing zeros: true or false. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.precision = P.sd = function (sd, rm) { + var c, n, v, + x = this; + + if (sd != null && sd !== !!sd) { + intCheck(sd, 1, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), sd, rm); + } + + if (!(c = x.c)) return null; + v = c.length - 1; + n = v * LOG_BASE + 1; + + if (v = c[v]) { + + // Subtract the number of trailing zeros of the last element. + for (; v % 10 == 0; v /= 10, n--); + + // Add the number of digits of the first element. + for (v = c[0]; v >= 10; v /= 10, n++); + } + + if (sd && x.e + 1 > n) n = x.e + 1; + + return n; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber shifted by k places + * (powers of 10). Shift to the right if n > 0, and to the left if n < 0. + * + * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}' + */ + P.shiftedBy = function (k) { + intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); + return this.times('1e' + k); + }; + + + /* + * sqrt(-n) = N + * sqrt(N) = N + * sqrt(-I) = N + * sqrt(I) = I + * sqrt(0) = 0 + * sqrt(-0) = -0 + * + * Return a new BigNumber whose value is the square root of the value of this BigNumber, + * rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.squareRoot = P.sqrt = function () { + var m, n, r, rep, t, + x = this, + c = x.c, + s = x.s, + e = x.e, + dp = DECIMAL_PLACES + 4, + half = new BigNumber('0.5'); + + // Negative/NaN/Infinity/zero? + if (s !== 1 || !c || !c[0]) { + return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0); + } + + // Initial estimate. + s = Math.sqrt(+x); + + // Math.sqrt underflow/overflow? + // Pass x to Math.sqrt as integer, then adjust the exponent of the result. + if (s == 0 || s == 1 / 0) { + n = coeffToString(c); + if ((n.length + e) % 2 == 0) n += '0'; + s = Math.sqrt(n); + e = bitFloor((e + 1) / 2) - (e < 0 || e % 2); + + if (s == 1 / 0) { + n = '1e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } + + r = new BigNumber(n); + } else { + r = new BigNumber(s + ''); + } + + // Check for zero. + // r could be zero if MIN_EXP is changed after the this value was created. + // This would cause a division by zero (x/t) and hence Infinity below, which would cause + // coeffToString to throw. + if (r.c[0]) { + e = r.e; + s = e + dp; + if (s < 3) s = 0; + + // Newton-Raphson iteration. + for (; ;) { + t = r; + r = half.times(t.plus(div(x, t, dp, 1))); + + if (coeffToString(t.c ).slice(0, s) === (n = + coeffToString(r.c)).slice(0, s)) { + + // The exponent of r may here be one less than the final result exponent, + // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits + // are indexed correctly. + if (r.e < e) --s; + n = n.slice(s - 3, s + 1); + + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits + // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the + // iteration. + if (n == '9999' || !rep && n == '4999') { + + // On the first iteration only, check to see if rounding up gives the + // exact result as the nines may infinitely repeat. + if (!rep) { + round(t, t.e + DECIMAL_PLACES + 2, 0); + + if (t.times(t).eq(x)) { + r = t; + break; + } + } + + dp += 4; + s += 4; + rep = 1; + } else { + + // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact + // result. If not, then there are further digits and m will be truthy. + if (!+n || !+n.slice(1) && n.charAt(0) == '5') { + + // Truncate to the first rounding digit. + round(r, r.e + DECIMAL_PLACES + 2, 1); + m = !r.times(r).eq(x); + } + + break; + } + } + } + } + + return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m); + }; + + + /* + * Return a string representing the value of this BigNumber in exponential notation and + * rounded using ROUNDING_MODE to dp fixed decimal places. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toExponential = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp++; + } + return format(this, dp, rm, 1); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounding + * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', + * but e.g. (-0.00001).toFixed(0) is '-0'. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toFixed = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp = dp + this.e + 1; + } + return format(this, dp, rm); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounded + * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties + * of the FORMAT object (see BigNumber.set). + * + * FORMAT = { + * decimalSeparator : '.', + * groupSeparator : ',', + * groupSize : 3, + * secondaryGroupSize : 0, + * fractionGroupSeparator : '\xA0', // non-breaking space + * fractionGroupSize : 0 + * }; + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toFormat = function (dp, rm) { + var str = this.toFixed(dp, rm); + + if (this.c) { + var i, + arr = str.split('.'), + g1 = +FORMAT.groupSize, + g2 = +FORMAT.secondaryGroupSize, + groupSeparator = FORMAT.groupSeparator, + intPart = arr[0], + fractionPart = arr[1], + isNeg = this.s < 0, + intDigits = isNeg ? intPart.slice(1) : intPart, + len = intDigits.length; + + if (g2) i = g1, g1 = g2, g2 = i, len -= i; + + if (g1 > 0 && len > 0) { + i = len % g1 || g1; + intPart = intDigits.substr(0, i); + + for (; i < len; i += g1) { + intPart += groupSeparator + intDigits.substr(i, g1); + } + + if (g2 > 0) intPart += groupSeparator + intDigits.slice(i); + if (isNeg) intPart = '-' + intPart; + } + + str = fractionPart + ? intPart + FORMAT.decimalSeparator + ((g2 = +FORMAT.fractionGroupSize) + ? fractionPart.replace(new RegExp('\\d{' + g2 + '}\\B', 'g'), + '$&' + FORMAT.fractionGroupSeparator) + : fractionPart) + : intPart; + } + + return str; + }; + + + /* + * Return a string array representing the value of this BigNumber as a simple fraction with + * an integer numerator and an integer denominator. The denominator will be a positive + * non-zero value less than or equal to the specified maximum denominator. If a maximum + * denominator is not specified, the denominator will be the lowest value necessary to + * represent the number exactly. + * + * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator. + * + * '[BigNumber Error] Argument {not an integer|out of range} : {md}' + */ + P.toFraction = function (md) { + var arr, d, d0, d1, d2, e, exp, n, n0, n1, q, s, + x = this, + xc = x.c; + + if (md != null) { + n = new BigNumber(md); + + // Throw if md is less than one or is not an integer, unless it is Infinity. + if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) { + throw Error + (bignumberError + 'Argument ' + + (n.isInteger() ? 'out of range: ' : 'not an integer: ') + md); + } + } + + if (!xc) return x.toString(); + + d = new BigNumber(ONE); + n1 = d0 = new BigNumber(ONE); + d1 = n0 = new BigNumber(ONE); + s = coeffToString(xc); + + // Determine initial denominator. + // d is a power of 10 and the minimum max denominator that specifies the value exactly. + e = d.e = s.length - x.e - 1; + d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; + md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n; + + exp = MAX_EXP; + MAX_EXP = 1 / 0; + n = new BigNumber(s); + + // n0 = d1 = 0 + n0.c[0] = 0; + + for (; ;) { + q = div(n, d, 0, 1); + d2 = d0.plus(q.times(d1)); + if (d2.comparedTo(md) == 1) break; + d0 = d1; + d1 = d2; + n1 = n0.plus(q.times(d2 = n1)); + n0 = d2; + d = n.minus(q.times(d2 = d)); + n = d2; + } + + d2 = div(md.minus(d0), d1, 0, 1); + n0 = n0.plus(d2.times(n1)); + d0 = d0.plus(d2.times(d1)); + n0.s = n1.s = x.s; + e *= 2; + + // Determine which fraction is closer to x, n0/d0 or n1/d1 + arr = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo( + div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 + ? [n1.toString(), d1.toString()] + : [n0.toString(), d0.toString()]; + + MAX_EXP = exp; + return arr; + }; + + + /* + * Return the value of this BigNumber converted to a number primitive. + */ + P.toNumber = function () { + return +this; + }; + + + /* + * Return a string representing the value of this BigNumber rounded to sd significant digits + * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits + * necessary to represent the integer part of the value in fixed-point notation, then use + * exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.toPrecision = function (sd, rm) { + if (sd != null) intCheck(sd, 1, MAX); + return format(this, sd, rm, 2); + }; + + + /* + * Return a string representing the value of this BigNumber in base b, or base 10 if b is + * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and + * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent + * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than + * TO_EXP_NEG, return exponential notation. + * + * [b] {number} Integer, 2 to ALPHABET.length inclusive. + * + * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + */ + P.toString = function (b) { + var str, + n = this, + s = n.s, + e = n.e; + + // Infinity or NaN? + if (e === null) { + + if (s) { + str = 'Infinity'; + if (s < 0) str = '-' + str; + } else { + str = 'NaN'; + } + } else { + str = coeffToString(n.c); + + if (b == null) { + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(str, e) + : toFixedPoint(str, e, '0'); + } else { + intCheck(b, 2, ALPHABET.length, 'Base'); + str = convertBase(toFixedPoint(str, e, '0'), 10, b, s, true); + } + + if (s < 0 && n.c[0]) str = '-' + str; + } + + return str; + }; + + + /* + * Return as toString, but do not accept a base argument, and include the minus sign for + * negative zero. + */ + P.valueOf = P.toJSON = function () { + var str, + n = this, + e = n.e; + + if (e === null) return n.toString(); + + str = coeffToString(n.c); + + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(str, e) + : toFixedPoint(str, e, '0'); + + return n.s < 0 ? '-' + str : str; + }; + + + P._isBigNumber = true; + + if (configObject != null) BigNumber.set(configObject); + + return BigNumber; + } + + + // PRIVATE HELPER FUNCTIONS + + + function bitFloor(n) { + var i = n | 0; + return n > 0 || n === i ? i : i - 1; + } + + + // Return a coefficient array as a string of base 10 digits. + function coeffToString(a) { + var s, z, + i = 1, + j = a.length, + r = a[0] + ''; + + for (; i < j;) { + s = a[i++] + ''; + z = LOG_BASE - s.length; + for (; z--; s = '0' + s); + r += s; + } + + // Determine trailing zeros. + for (j = r.length; r.charCodeAt(--j) === 48;); + return r.slice(0, j + 1 || 1); + } + + + // Compare the value of BigNumbers x and y. + function compare(x, y) { + var a, b, + xc = x.c, + yc = y.c, + i = x.s, + j = y.s, + k = x.e, + l = y.e; + + // Either NaN? + if (!i || !j) return null; + + a = xc && !xc[0]; + b = yc && !yc[0]; + + // Either zero? + if (a || b) return a ? b ? 0 : -j : i; + + // Signs differ? + if (i != j) return i; + + a = i < 0; + b = k == l; + + // Either Infinity? + if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1; + + // Compare exponents. + if (!b) return k > l ^ a ? 1 : -1; + + j = (k = xc.length) < (l = yc.length) ? k : l; + + // Compare digit by digit. + for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1; + + // Compare lengths. + return k == l ? 0 : k > l ^ a ? 1 : -1; + } + + + /* + * Check that n is a primitive number, an integer, and in range, otherwise throw. + */ + function intCheck(n, min, max, name) { + if (n < min || n > max || n !== (n < 0 ? mathceil(n) : mathfloor(n))) { + throw Error + (bignumberError + (name || 'Argument') + (typeof n == 'number' + ? n < min || n > max ? ' out of range: ' : ' not an integer: ' + : ' not a primitive number: ') + n); + } + } + + + function isArray(obj) { + return Object.prototype.toString.call(obj) == '[object Array]'; + } + + + // Assumes finite n. + function isOdd(n) { + var k = n.c.length - 1; + return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0; + } + + + function toExponential(str, e) { + return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) + + (e < 0 ? 'e' : 'e+') + e; + } + + + function toFixedPoint(str, e, z) { + var len, zs; + + // Negative exponent? + if (e < 0) { + + // Prepend zeros. + for (zs = z + '.'; ++e; zs += z); + str = zs + str; + + // Positive exponent + } else { + len = str.length; + + // Append zeros. + if (++e > len) { + for (zs = z, e -= len; --e; zs += z); + str += zs; + } else if (e < len) { + str = str.slice(0, e) + '.' + str.slice(e); + } + } + + return str; + } + + + // EXPORT + + + BigNumber = clone(); + BigNumber['default'] = BigNumber.BigNumber = BigNumber; + + // AMD. + if (typeof define == 'function' && define.amd) { + define(function () { return BigNumber; }); + + // Node.js and other environments that support module.exports. + } else if (typeof module != 'undefined' && module.exports) { + module.exports = BigNumber; + + // Browser. + } else { + if (!globalObject) { + globalObject = typeof self != 'undefined' && self ? self : window; + } + + globalObject.BigNumber = BigNumber; + } +})(this); diff --git a/node_modules/bignumber.js/bignumber.js.map b/node_modules/bignumber.js/bignumber.js.map new file mode 100644 index 0000000..fcf56f7 --- /dev/null +++ b/node_modules/bignumber.js/bignumber.js.map @@ -0,0 +1 @@ +{"version":3,"file":"bignumber.min.js","sources":["bignumber.js"],"names":["globalObject","clone","configObject","BigNumber","n","b","alphabet","c","caseChanged","e","i","isNum","len","str","x","this","s","slice","isNumeric","test","parseNumeric","charCodeAt","indexOf","replace","search","substring","length","intCheck","ALPHABET","round","DECIMAL_PLACES","ROUNDING_MODE","DEBUG","Error","tooManyDigits","charAt","toUpperCase","toLowerCase","convertBase","MAX_SAFE_INTEGER","mathfloor","MAX_EXP","MIN_EXP","LOG_BASE","push","format","rm","id","c0","ne","toString","coeffToString","TO_EXP_NEG","toExponential","toFixedPoint","maxOrMin","args","method","m","isArray","call","normalise","j","pop","sd","r","d","k","ni","rd","xc","pows10","POWS_TEN","out","mathceil","BASE","div","P","prototype","constructor","valueOf","ONE","TO_EXP_POS","CRYPTO","MODULO_MODE","POW_PRECISION","FORMAT","decimalSeparator","groupSeparator","groupSize","secondaryGroupSize","fractionGroupSeparator","fractionGroupSize","ROUND_UP","ROUND_DOWN","ROUND_CEIL","ROUND_FLOOR","ROUND_HALF_UP","ROUND_HALF_DOWN","ROUND_HALF_EVEN","ROUND_HALF_CEIL","ROUND_HALF_FLOOR","EUCLID","config","set","obj","p","v","bignumberError","hasOwnProperty","MAX","crypto","getRandomValues","randomBytes","EXPONENTIAL_AT","RANGE","isBigNumber","_isBigNumber","maximum","max","arguments","lt","minimum","min","gt","random","pow2_53","random53bitInt","Math","dp","a","rand","Uint32Array","copy","splice","toBaseOut","baseIn","baseOut","arrL","arr","reverse","decimal","sign","callerIsToString","y","pow","concat","multiply","base","temp","xlo","xhi","carry","klo","SQRT_BASE","khi","compare","aL","bL","cmp","subtract","more","prod","prodL","q","qc","rem","remL","rem0","xi","xL","yc0","yL","yz","yc","NaN","bitFloor","basePrefix","dotAfter","dotBefore","isInfinityOrNaN","whitespaceOrPlus","isNaN","p1","p2","absoluteValue","abs","comparedTo","decimalPlaces","dividedBy","dividedToIntegerBy","idiv","exponentiatedBy","half","isModExp","nIsBig","nIsNeg","nIsOdd","isInteger","isOdd","mod","times","integerValue","isEqualTo","eq","isFinite","isGreaterThan","isGreaterThanOrEqualTo","gte","isLessThan","isLessThanOrEqualTo","lte","isNegative","isPositive","isZero","minus","t","xLTy","plus","xe","ye","modulo","multipliedBy","xcL","ycL","ylo","yhi","zc","sqrtBase","negated","precision","shiftedBy","squareRoot","sqrt","rep","toFixed","toFormat","split","g1","g2","intPart","fractionPart","isNeg","intDigits","substr","RegExp","toFraction","md","d0","d1","d2","exp","n0","n1","toNumber","toPrecision","toJSON","z","l","name","Object","zs","ceil","floor","define","amd","module","exports","self","window"],"mappings":"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"} \ No newline at end of file diff --git a/node_modules/bignumber.js/bignumber.min.js b/node_modules/bignumber.js/bignumber.min.js new file mode 100644 index 0000000..5f60c0c --- /dev/null +++ b/node_modules/bignumber.js/bignumber.min.js @@ -0,0 +1,3 @@ +/* bignumber.js v7.2.1 https://github.com/MikeMcl/bignumber.js/LICENCE */ +!function(e){"use strict";function r(e){function l(e,r){var n,t,i,s,f,u,c,h,p=this;if(!(p instanceof l))return new l(e,r);if(null==r){if(e instanceof l)return p.s=e.s,p.e=e.e,void(p.c=(e=e.c)?e.slice():e);if(u="number"==typeof e,u&&0*e==0){if(p.s=0>1/e?(e=-e,-1):1,e===~~e){for(s=0,f=e;f>=10;f/=10,s++);return p.e=s,void(p.c=[e])}h=e+""}else{if(!a.test(h=e+""))return _(p,h,u);p.s=45==h.charCodeAt(0)?(h=h.slice(1),-1):1}(s=h.indexOf("."))>-1&&(h=h.replace(".","")),(f=h.search(/e/i))>0?(0>s&&(s=f),s+=+h.slice(f+1),h=h.substring(0,f)):0>s&&(s=h.length)}else{if(o(r,2,q.length,"Base"),h=e+"",10==r)return p=new l(e instanceof l?e:h),R(p,B+p.e+1,U);if(u="number"==typeof e){if(0*e!=0)return _(p,h,u,r);if(p.s=0>1/e?(h=h.slice(1),-1):1,l.DEBUG&&h.replace(/^0\.0*|\./,"").length>15)throw Error(w+e);u=!1}else p.s=45===h.charCodeAt(0)?(h=h.slice(1),-1):1;for(n=q.slice(0,r),s=f=0,c=h.length;c>f;f++)if(n.indexOf(t=h.charAt(f))<0){if("."==t){if(f>s){s=c;continue}}else if(!i&&(h==h.toUpperCase()&&(h=h.toLowerCase())||h==h.toLowerCase()&&(h=h.toUpperCase()))){i=!0,f=-1,s=0;continue}return _(p,e+"",u,r)}h=P(h,r,10,p.s),(s=h.indexOf("."))>-1?h=h.replace(".",""):s=h.length}for(f=0;48===h.charCodeAt(f);f++);for(c=h.length;48===h.charCodeAt(--c););if(h=h.slice(f,++c)){if(c-=f,u&&l.DEBUG&&c>15&&(e>v||e!==g(e)))throw Error(w+p.s*e);if(s=s-f-1,s>C)p.c=p.e=null;else if(x>s)p.c=[p.e=0];else{if(p.e=s,p.c=[],f=(s+1)%m,0>s&&(f+=m),c>f){for(f&&p.c.push(+h.slice(0,f)),c-=m;c>f;)p.c.push(+h.slice(f,f+=m));h=h.slice(f),f=m-h.length}else f-=c;for(;f--;h+="0");p.c.push(+h)}}else p.c=[p.e=0]}function E(e,r,n,i){var s,f,a,h,g;if(null==n?n=U:o(n,0,8),!e.c)return e.toString();if(s=e.c[0],a=e.e,null==r)g=t(e.c),g=1==i||2==i&&I>=a?u(g,a):c(g,a,"0");else if(e=R(new l(e),r,n),f=e.e,g=t(e.c),h=g.length,1==i||2==i&&(f>=r||I>=f)){for(;r>h;g+="0",h++);g=u(g,f)}else if(r-=a,g=c(g,f,"0"),f+1>h){if(--r>0)for(g+=".";r--;g+="0");}else if(r+=f-h,r>0)for(f+1==h&&(g+=".");r--;g+="0");return e.s<0&&s?"-"+g:g}function b(e,r){var n,t,i=0;for(s(e[0])&&(e=e[0]),n=new l(e[0]);++i=10;i/=10,t++);return(n=t+n*m-1)>C?e.c=e.e=null:x>n?e.c=[e.e=0]:(e.e=n,e.c=r),e}function R(e,r,n,t){var i,o,s,f,u,c,l,a=e.c,p=O;if(a){e:{for(i=1,f=a[0];f>=10;f/=10,i++);if(o=r-i,0>o)o+=m,s=r,u=a[c=0],l=u/p[i-s-1]%10|0;else if(c=h((o+1)/m),c>=a.length){if(!t)break e;for(;a.length<=c;a.push(0));u=l=0,i=1,o%=m,s=o-m+1}else{for(u=f=a[c],i=1;f>=10;f/=10,i++);o%=m,s=o-m+i,l=0>s?0:u/p[i-s-1]%10|0}if(t=t||0>r||null!=a[c+1]||(0>s?u:u%p[i-s-1]),t=4>n?(l||t)&&(0==n||n==(e.s<0?3:2)):l>5||5==l&&(4==n||t||6==n&&(o>0?s>0?u/p[i-s]:0:a[c-1])%10&1||n==(e.s<0?8:7)),1>r||!a[0])return a.length=0,t?(r-=e.e+1,a[0]=p[(m-r%m)%m],e.e=-r||0):a[0]=e.e=0,e;if(0==o?(a.length=c,f=1,c--):(a.length=c+1,f=p[m-o],a[c]=s>0?g(u/p[i-s]%p[s])*f:0),t)for(;;){if(0==c){for(o=1,s=a[0];s>=10;s/=10,o++);for(s=a[0]+=f,f=1;s>=10;s/=10,f++);o!=f&&(e.e++,a[0]==d&&(a[0]=1));break}if(a[c]+=f,a[c]!=d)break;a[c--]=0,f=1}for(o=a.length;0===a[--o];a.pop());}e.e>C?e.c=e.e=null:e.en?-n:n))),e.hasOwnProperty(r="RANGE"))if(n=e[r],s(n))o(n[0],-y,-1,r),o(n[1],1,y,r),x=n[0],C=n[1];else{if(o(n,-y,y,r),!n)throw Error(p+r+" cannot be zero: "+n);x=-(C=0>n?-n:n)}if(e.hasOwnProperty(r="CRYPTO")){if(n=e[r],n!==!!n)throw Error(p+r+" not true or false: "+n);if(n){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw M=!n,Error(p+"crypto unavailable");M=n}else M=n}if(e.hasOwnProperty(r="MODULO_MODE")&&(n=e[r],o(n,0,9,r),G=n),e.hasOwnProperty(r="POW_PRECISION")&&(n=e[r],o(n,0,y,r),F=n),e.hasOwnProperty(r="FORMAT")){if(n=e[r],"object"!=typeof n)throw Error(p+r+" not an object: "+n);k=n}if(e.hasOwnProperty(r="ALPHABET")){if(n=e[r],"string"!=typeof n||/^.$|\.|(.).*\1/.test(n))throw Error(p+r+" invalid: "+n);q=n}}return{DECIMAL_PLACES:B,ROUNDING_MODE:U,EXPONENTIAL_AT:[I,T],RANGE:[x,C],CRYPTO:M,MODULO_MODE:G,POW_PRECISION:F,FORMAT:k,ALPHABET:q}},l.isBigNumber=function(e){return e instanceof l||e&&e._isBigNumber===!0||!1},l.maximum=l.max=function(){return b(arguments,D.lt)},l.minimum=l.min=function(){return b(arguments,D.gt)},l.random=function(){var e=9007199254740992,r=Math.random()*e&2097151?function(){return g(Math.random()*e)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)};return function(e){var n,t,i,s,f,u=0,c=[],a=new l(L);if(null==e?e=B:o(e,0,y),s=h(e/m),M)if(crypto.getRandomValues){for(n=crypto.getRandomValues(new Uint32Array(s*=2));s>u;)f=131072*n[u]+(n[u+1]>>>11),f>=9e15?(t=crypto.getRandomValues(new Uint32Array(2)),n[u]=t[0],n[u+1]=t[1]):(c.push(f%1e14),u+=2);u=s/2}else{if(!crypto.randomBytes)throw M=!1,Error(p+"crypto unavailable");for(n=crypto.randomBytes(s*=7);s>u;)f=281474976710656*(31&n[u])+1099511627776*n[u+1]+4294967296*n[u+2]+16777216*n[u+3]+(n[u+4]<<16)+(n[u+5]<<8)+n[u+6],f>=9e15?crypto.randomBytes(7).copy(n,u):(c.push(f%1e14),u+=7);u=s/7}if(!M)for(;s>u;)f=r(),9e15>f&&(c[u++]=f%1e14);for(s=c[--u],e%=m,s&&e&&(f=O[m-e],c[u]=g(s/f)*f);0===c[u];c.pop(),u--);if(0>u)c=[i=0];else{for(i=-1;0===c[0];c.splice(0,1),i-=m);for(u=1,f=c[0];f>=10;f/=10,u++);m>u&&(i-=m-u)}return a.e=i,a.c=c,a}}(),P=function(){function e(e,r,n,t){for(var i,o,s=[0],f=0,u=e.length;u>f;){for(o=s.length;o--;s[o]*=r);for(s[0]+=t.indexOf(e.charAt(f++)),i=0;in-1&&(null==s[i+1]&&(s[i+1]=0),s[i+1]+=s[i]/n|0,s[i]%=n)}return s.reverse()}var r="0123456789";return function(n,i,o,s,f){var u,a,h,g,p,w,d,m,v=n.indexOf("."),O=B,N=U;for(v>=0&&(g=F,F=0,n=n.replace(".",""),m=new l(i),w=m.pow(n.length-v),F=g,m.c=e(c(t(w.c),w.e,"0"),10,o,r),m.e=m.c.length),d=e(n,i,o,f?(u=q,r):(u=r,q)),h=g=d.length;0==d[--g];d.pop());if(!d[0])return u.charAt(0);if(0>v?--h:(w.c=d,w.e=h,w.s=s,w=S(w,m,O,N,o),d=w.c,p=w.r,h=w.e),a=h+O+1,v=d[a],g=o/2,p=p||0>a||null!=d[a+1],p=4>N?(null!=v||p)&&(0==N||N==(w.s<0?3:2)):v>g||v==g&&(4==N||p||6==N&&1&d[a-1]||N==(w.s<0?8:7)),1>a||!d[0])n=p?c(u.charAt(1),-O,u.charAt(0)):u.charAt(0);else{if(d.length=a,p)for(--o;++d[--a]>o;)d[a]=0,a||(++h,d=[1].concat(d));for(g=d.length;!d[--g];);for(v=0,n="";g>=v;n+=u.charAt(d[v++]));n=c(n,h,u.charAt(0))}return n}}(),S=function(){function e(e,r,n){var t,i,o,s,f=0,u=e.length,c=r%N,l=r/N|0;for(e=e.slice();u--;)o=e[u]%N,s=e[u]/N|0,t=l*o+s*c,i=c*o+t%N*N+f,f=(i/n|0)+(t/N|0)+l*s,e[u]=i%n;return f&&(e=[f].concat(e)),e}function r(e,r,n,t){var i,o;if(n!=t)o=n>t?1:-1;else for(i=o=0;n>i;i++)if(e[i]!=r[i]){o=e[i]>r[i]?1:-1;break}return o}function t(e,r,n,t){for(var i=0;n--;)e[n]-=i,i=e[n]1;e.splice(0,1));}return function(i,o,s,f,u){var c,a,h,p,w,v,O,N,y,E,b,A,S,P,_,D,L,B=i.s==o.s?1:-1,U=i.c,I=o.c;if(!(U&&U[0]&&I&&I[0]))return new l(i.s&&o.s&&(U?!I||U[0]!=I[0]:I)?U&&0==U[0]||!I?0*B:B/0:NaN);for(N=new l(B),y=N.c=[],a=i.e-o.e,B=s+a+1,u||(u=d,a=n(i.e/m)-n(o.e/m),B=B/m|0),h=0;I[h]==(U[h]||0);h++);if(I[h]>(U[h]||0)&&a--,0>B)y.push(1),p=!0;else{for(P=U.length,D=I.length,h=0,B+=2,w=g(u/(I[0]+1)),w>1&&(I=e(I,w,u),U=e(U,w,u),D=I.length,P=U.length),S=D,E=U.slice(0,D),b=E.length;D>b;E[b++]=0);L=I.slice(),L=[0].concat(L),_=I[0],I[1]>=u/2&&_++;do{if(w=0,c=r(I,E,D,b),0>c){if(A=E[0],D!=b&&(A=A*u+(E[1]||0)),w=g(A/_),w>1)for(w>=u&&(w=u-1),v=e(I,w,u),O=v.length,b=E.length;1==r(v,E,O,b);)w--,t(v,O>D?L:I,O,u),O=v.length,c=1;else 0==w&&(c=w=1),v=I.slice(),O=v.length;if(b>O&&(v=[0].concat(v)),t(E,v,b,u),b=E.length,-1==c)for(;r(I,E,D,b)<1;)w++,t(E,b>D?L:I,b,u),b=E.length}else 0===c&&(w++,E=[0]);y[h++]=w,E[0]?E[b++]=U[S]||0:(E=[U[S]],b=1)}while((S++=10;B/=10,h++);R(N,s+(N.e=h+a*m-1)+1,f,p)}else N.e=a,N.r=+p;return N}}(),_=function(){var e=/^(-?)0([xbo])(?=\w[\w.]*$)/i,r=/^([^.]+)\.$/,n=/^\.([^.]+)$/,t=/^-?(Infinity|NaN)$/,i=/^\s*\+(?=[\w.])|^\s+|\s+$/g;return function(o,s,f,u){var c,a=f?s:s.replace(i,"");if(t.test(a))o.s=isNaN(a)?null:0>a?-1:1,o.c=o.e=null;else{if(!f&&(a=a.replace(e,function(e,r,n){return c="x"==(n=n.toLowerCase())?16:"b"==n?2:8,u&&u!=c?e:r}),u&&(c=u,a=a.replace(r,"$1").replace(n,"0.$1")),s!=a))return new l(a,c);if(l.DEBUG)throw Error(p+"Not a"+(u?" base "+u:"")+" number: "+s);o.c=o.e=o.s=null}}}(),D.absoluteValue=D.abs=function(){var e=new l(this);return e.s<0&&(e.s=1),e},D.comparedTo=function(e,r){return i(this,new l(e,r))},D.decimalPlaces=D.dp=function(e,r){var t,i,s,f=this;if(null!=e)return o(e,0,y),null==r?r=U:o(r,0,8),R(new l(f),e+f.e+1,r);if(!(t=f.c))return null;if(i=((s=t.length-1)-n(this.e/m))*m,s=t[s])for(;s%10==0;s/=10,i--);return 0>i&&(i=0),i},D.dividedBy=D.div=function(e,r){return S(this,new l(e,r),B,U)},D.dividedToIntegerBy=D.idiv=function(e,r){return S(this,new l(e,r),0,1)},D.exponentiatedBy=D.pow=function(e,r){var n,t,i,o,s,u,c,a,w=this;if(e=new l(e),e.c&&!e.isInteger())throw Error(p+"Exponent not an integer: "+e);if(null!=r&&(r=new l(r)),s=e.e>14,!w.c||!w.c[0]||1==w.c[0]&&!w.e&&1==w.c.length||!e.c||!e.c[0])return a=new l(Math.pow(+w.valueOf(),s?2-f(e):+e)),r?a.mod(r):a;if(u=e.s<0,r){if(r.c?!r.c[0]:!r.s)return new l(NaN);t=!u&&w.isInteger()&&r.isInteger(),t&&(w=w.mod(r))}else{if(e.e>9&&(w.e>0||w.e<-1||(0==w.e?w.c[0]>1||s&&w.c[1]>=24e7:w.c[0]<8e13||s&&w.c[0]<=9999975e7)))return i=w.s<0&&f(e)?-0:0,w.e>-1&&(i=1/i),new l(u?1/i:i);F&&(i=h(F/m+2))}for(s?(n=new l(.5),c=f(e)):c=e%2,u&&(e.s=1),a=new l(L);;){if(c){if(a=a.times(w),!a.c)break;i?a.c.length>i&&(a.c.length=i):t&&(a=a.mod(r))}if(s){if(e=e.times(n),R(e,e.e+1,1),!e.c[0])break;s=e.e>14,c=f(e)}else{if(e=g(e/2),!e)break;c=e%2}w=w.times(w),i?w.c&&w.c.length>i&&(w.c.length=i):t&&(w=w.mod(r))}return t?a:(u&&(a=L.div(a)),r?a.mod(r):i?R(a,F,U,o):a)},D.integerValue=function(e){var r=new l(this);return null==e?e=U:o(e,0,8),R(r,r.e+1,e)},D.isEqualTo=D.eq=function(e,r){return 0===i(this,new l(e,r))},D.isFinite=function(){return!!this.c},D.isGreaterThan=D.gt=function(e,r){return i(this,new l(e,r))>0},D.isGreaterThanOrEqualTo=D.gte=function(e,r){return 1===(r=i(this,new l(e,r)))||0===r},D.isInteger=function(){return!!this.c&&n(this.e/m)>this.c.length-2},D.isLessThan=D.lt=function(e,r){return i(this,new l(e,r))<0},D.isLessThanOrEqualTo=D.lte=function(e,r){return-1===(r=i(this,new l(e,r)))||0===r},D.isNaN=function(){return!this.s},D.isNegative=function(){return this.s<0},D.isPositive=function(){return this.s>0},D.isZero=function(){return!!this.c&&0==this.c[0]},D.minus=function(e,r){var t,i,o,s,f=this,u=f.s;if(e=new l(e,r),r=e.s,!u||!r)return new l(NaN);if(u!=r)return e.s=-r,f.plus(e);var c=f.e/m,a=e.e/m,h=f.c,g=e.c;if(!c||!a){if(!h||!g)return h?(e.s=-r,e):new l(g?f:NaN);if(!h[0]||!g[0])return g[0]?(e.s=-r,e):new l(h[0]?f:3==U?-0:0)}if(c=n(c),a=n(a),h=h.slice(),u=c-a){for((s=0>u)?(u=-u,o=h):(a=c,o=g),o.reverse(),r=u;r--;o.push(0));o.reverse()}else for(i=(s=(u=h.length)<(r=g.length))?u:r,u=r=0;i>r;r++)if(h[r]!=g[r]){s=h[r]0)for(;r--;h[t++]=0);for(r=d-1;i>u;){if(h[--i]c&&(v=b,b=R,R=v,o=c,c=g,g=o),o=c+g,v=[];o--;v.push(0));for(O=d,y=N,o=g;--o>=0;){for(t=0,p=R[o]%y,w=R[o]/y|0,f=c,s=o+f;s>o;)a=b[--f]%y,h=b[f]/y|0,u=w*a+h*p,a=p*a+u%y*y+v[s]+t,t=(a/O|0)+(u/y|0)+w*h,v[s--]=a%O;v[s]=t}return t?++i:v.splice(0,1),A(e,v,i)},D.negated=function(){var e=new l(this);return e.s=-e.s||null,e},D.plus=function(e,r){var t,i=this,o=i.s;if(e=new l(e,r),r=e.s,!o||!r)return new l(NaN);if(o!=r)return e.s=-r,i.minus(e);var s=i.e/m,f=e.e/m,u=i.c,c=e.c;if(!s||!f){if(!u||!c)return new l(o/0);if(!u[0]||!c[0])return c[0]?e:new l(u[0]?i:0*o)}if(s=n(s),f=n(f),u=u.slice(),o=s-f){for(o>0?(f=s,t=c):(o=-o,t=u),t.reverse();o--;t.push(0));t.reverse()}for(o=u.length,r=c.length,0>o-r&&(t=c,c=u,u=t,r=o),o=0;r;)o=(u[--r]=u[r]+c[r]+o)/d|0,u[r]=d===u[r]?0:u[r]%d;return o&&(u=[o].concat(u),++f),A(e,u,f)},D.precision=D.sd=function(e,r){var n,t,i,s=this;if(null!=e&&e!==!!e)return o(e,1,y),null==r?r=U:o(r,0,8),R(new l(s),e,r);if(!(n=s.c))return null;if(i=n.length-1,t=i*m+1,i=n[i]){for(;i%10==0;i/=10,t--);for(i=n[0];i>=10;i/=10,t++);}return e&&s.e+1>t&&(t=s.e+1),t},D.shiftedBy=function(e){return o(e,-v,v),this.times("1e"+e)},D.squareRoot=D.sqrt=function(){var e,r,i,o,s,f=this,u=f.c,c=f.s,a=f.e,h=B+4,g=new l("0.5");if(1!==c||!u||!u[0])return new l(!c||0>c&&(!u||u[0])?NaN:u?f:1/0);if(c=Math.sqrt(+f),0==c||c==1/0?(r=t(u),(r.length+a)%2==0&&(r+="0"),c=Math.sqrt(r),a=n((a+1)/2)-(0>a||a%2),c==1/0?r="1e"+a:(r=c.toExponential(),r=r.slice(0,r.indexOf("e")+1)+a),i=new l(r)):i=new l(c+""),i.c[0])for(a=i.e,c=a+h,3>c&&(c=0);;)if(s=i,i=g.times(s.plus(S(f,s,h,1))),t(s.c).slice(0,c)===(r=t(i.c)).slice(0,c)){if(i.e0&&h>0){for(t=h%o||o,u=a.substr(0,t);h>t;t+=o)u+=f+a.substr(t,o);s>0&&(u+=f+a.slice(t)),l&&(u="-"+u)}n=c?u+k.decimalSeparator+((s=+k.fractionGroupSize)?c.replace(new RegExp("\\d{"+s+"}\\B","g"),"$&"+k.fractionGroupSeparator):c):u}return n},D.toFraction=function(e){var r,n,i,o,s,f,u,c,a,h,g,w,d=this,v=d.c;if(null!=e&&(c=new l(e),!c.isInteger()&&(c.c||1!==c.s)||c.lt(L)))throw Error(p+"Argument "+(c.isInteger()?"out of range: ":"not an integer: ")+e);if(!v)return d.toString();for(n=new l(L),h=i=new l(L),o=a=new l(L),w=t(v),f=n.e=w.length-d.e-1,n.c[0]=O[(u=f%m)<0?m+u:u],e=!e||c.comparedTo(n)>0?f>0?n:h:c,u=C,C=1/0,c=new l(w),a.c[0]=0;g=S(c,n,0,1),s=i.plus(g.times(o)),1!=s.comparedTo(e);)i=o,o=s,h=a.plus(g.times(s=h)),a=s,n=c.minus(g.times(s=n)),c=s;return s=S(e.minus(i),o,0,1),a=a.plus(s.times(h)),i=i.plus(s.times(o)),a.s=h.s=d.s,f*=2,r=S(h,o,f,U).minus(d).abs().comparedTo(S(a,i,f,U).minus(d).abs())<1?[h.toString(),o.toString()]:[a.toString(),i.toString()],C=u,r},D.toNumber=function(){return+this},D.toPrecision=function(e,r){return null!=e&&o(e,1,y),E(this,e,r,2)},D.toString=function(e){var r,n=this,i=n.s,s=n.e;return null===s?i?(r="Infinity",0>i&&(r="-"+r)):r="NaN":(r=t(n.c),null==e?r=I>=s||s>=T?u(r,s):c(r,s,"0"):(o(e,2,q.length,"Base"),r=P(c(r,s,"0"),10,e,i,!0)),0>i&&n.c[0]&&(r="-"+r)),r},D.valueOf=D.toJSON=function(){var e,r=this,n=r.e;return null===n?r.toString():(e=t(r.c),e=I>=n||n>=T?u(e,n):c(e,n,"0"),r.s<0?"-"+e:e)},D._isBigNumber=!0,null!=e&&l.set(e),l}function n(e){var r=0|e;return e>0||e===r?r:r-1}function t(e){for(var r,n,t=1,i=e.length,o=e[0]+"";i>t;){for(r=e[t++]+"",n=m-r.length;n--;r="0"+r);o+=r}for(i=o.length;48===o.charCodeAt(--i););return o.slice(0,i+1||1)}function i(e,r){var n,t,i=e.c,o=r.c,s=e.s,f=r.s,u=e.e,c=r.e;if(!s||!f)return null;if(n=i&&!i[0],t=o&&!o[0],n||t)return n?t?0:-f:s;if(s!=f)return s;if(n=0>s,t=u==c,!i||!o)return t?0:!i^n?1:-1;if(!t)return u>c^n?1:-1;for(f=(u=i.length)<(c=o.length)?u:c,s=0;f>s;s++)if(i[s]!=o[s])return i[s]>o[s]^n?1:-1;return u==c?0:u>c^n?1:-1}function o(e,r,n,t){if(r>e||e>n||e!==(0>e?h(e):g(e)))throw Error(p+(t||"Argument")+("number"==typeof e?r>e||e>n?" out of range: ":" not an integer: ":" not a primitive number: ")+e)}function s(e){return"[object Array]"==Object.prototype.toString.call(e)}function f(e){var r=e.c.length-1;return n(e.e/m)==r&&e.c[r]%2!=0}function u(e,r){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(0>r?"e":"e+")+r}function c(e,r,n){var t,i;if(0>r){for(i=n+".";++r;i+=n);e=i+e}else if(t=e.length,++r>t){for(i=n,r-=t;--r;i+=n);e+=i}else t>r&&(e=e.slice(0,r)+"."+e.slice(r));return e}var l,a=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,h=Math.ceil,g=Math.floor,p="[BigNumber Error] ",w=p+"Number primitive has more than 15 significant digits: ",d=1e14,m=14,v=9007199254740991,O=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],N=1e7,y=1e9;l=r(),l["default"]=l.BigNumber=l,"function"==typeof define&&define.amd?define(function(){return l}):"undefined"!=typeof module&&module.exports?module.exports=l:(e||(e="undefined"!=typeof self&&self?self:window),e.BigNumber=l)}(this); +//# sourceMappingURL=bignumber.js.map \ No newline at end of file diff --git a/node_modules/bignumber.js/bignumber.mjs b/node_modules/bignumber.js/bignumber.mjs new file mode 100644 index 0000000..826b910 --- /dev/null +++ b/node_modules/bignumber.js/bignumber.mjs @@ -0,0 +1,2793 @@ +/* + * bignumber.js v7.2.1 + * A JavaScript library for arbitrary-precision arithmetic. + * https://github.com/MikeMcl/bignumber.js + * Copyright (c) 2018 Michael Mclaughlin + * MIT Licensed. + * + * BigNumber.prototype methods | BigNumber methods + * | + * absoluteValue abs | clone + * comparedTo | config set + * decimalPlaces dp | DECIMAL_PLACES + * dividedBy div | ROUNDING_MODE + * dividedToIntegerBy idiv | EXPONENTIAL_AT + * exponentiatedBy pow | RANGE + * integerValue | CRYPTO + * isEqualTo eq | MODULO_MODE + * isFinite | POW_PRECISION + * isGreaterThan gt | FORMAT + * isGreaterThanOrEqualTo gte | ALPHABET + * isInteger | isBigNumber + * isLessThan lt | maximum max + * isLessThanOrEqualTo lte | minimum min + * isNaN | random + * isNegative | + * isPositive | + * isZero | + * minus | + * modulo mod | + * multipliedBy times | + * negated | + * plus | + * precision sd | + * shiftedBy | + * squareRoot sqrt | + * toExponential | + * toFixed | + * toFormat | + * toFraction | + * toJSON | + * toNumber | + * toPrecision | + * toString | + * valueOf | + * + */ + + +var isNumeric = /^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i, + + mathceil = Math.ceil, + mathfloor = Math.floor, + + bignumberError = '[BigNumber Error] ', + tooManyDigits = bignumberError + 'Number primitive has more than 15 significant digits: ', + + BASE = 1e14, + LOG_BASE = 14, + MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1 + // MAX_INT32 = 0x7fffffff, // 2^31 - 1 + POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13], + SQRT_BASE = 1e7, + + // EDITABLE + // The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and + // the arguments to toExponential, toFixed, toFormat, and toPrecision. + MAX = 1E9; // 0 to MAX_INT32 + + +/* + * Create and return a BigNumber constructor. + */ +function clone(configObject) { + var div, convertBase, parseNumeric, + P = BigNumber.prototype = { constructor: BigNumber, toString: null, valueOf: null }, + ONE = new BigNumber(1), + + + //----------------------------- EDITABLE CONFIG DEFAULTS ------------------------------- + + + // The default values below must be integers within the inclusive ranges stated. + // The values can also be changed at run-time using BigNumber.set. + + // The maximum number of decimal places for operations involving division. + DECIMAL_PLACES = 20, // 0 to MAX + + // The rounding mode used when rounding to the above decimal places, and when using + // toExponential, toFixed, toFormat and toPrecision, and round (default value). + // UP 0 Away from zero. + // DOWN 1 Towards zero. + // CEIL 2 Towards +Infinity. + // FLOOR 3 Towards -Infinity. + // HALF_UP 4 Towards nearest neighbour. If equidistant, up. + // HALF_DOWN 5 Towards nearest neighbour. If equidistant, down. + // HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour. + // HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity. + // HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity. + ROUNDING_MODE = 4, // 0 to 8 + + // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] + + // The exponent value at and beneath which toString returns exponential notation. + // Number type: -7 + TO_EXP_NEG = -7, // 0 to -MAX + + // The exponent value at and above which toString returns exponential notation. + // Number type: 21 + TO_EXP_POS = 21, // 0 to MAX + + // RANGE : [MIN_EXP, MAX_EXP] + + // The minimum exponent value, beneath which underflow to zero occurs. + // Number type: -324 (5e-324) + MIN_EXP = -1e7, // -1 to -MAX + + // The maximum exponent value, above which overflow to Infinity occurs. + // Number type: 308 (1.7976931348623157e+308) + // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow. + MAX_EXP = 1e7, // 1 to MAX + + // Whether to use cryptographically-secure random number generation, if available. + CRYPTO = false, // true or false + + // The modulo mode used when calculating the modulus: a mod n. + // The quotient (q = a / n) is calculated according to the corresponding rounding mode. + // The remainder (r) is calculated as: r = a - n * q. + // + // UP 0 The remainder is positive if the dividend is negative, else is negative. + // DOWN 1 The remainder has the same sign as the dividend. + // This modulo mode is commonly known as 'truncated division' and is + // equivalent to (a % n) in JavaScript. + // FLOOR 3 The remainder has the same sign as the divisor (Python %). + // HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function. + // EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). + // The remainder is always positive. + // + // The truncated division, floored division, Euclidian division and IEEE 754 remainder + // modes are commonly used for the modulus operation. + // Although the other rounding modes can also be used, they may not give useful results. + MODULO_MODE = 1, // 0 to 9 + + // The maximum number of significant digits of the result of the exponentiatedBy operation. + // If POW_PRECISION is 0, there will be unlimited significant digits. + POW_PRECISION = 0, // 0 to MAX + + // The format specification used by the BigNumber.prototype.toFormat method. + FORMAT = { + decimalSeparator: '.', + groupSeparator: ',', + groupSize: 3, + secondaryGroupSize: 0, + fractionGroupSeparator: '\xA0', // non-breaking space + fractionGroupSize: 0 + }, + + // The alphabet used for base conversion. + // It must be at least 2 characters long, with no '.' or repeated character. + // '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_' + ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz'; + + + //------------------------------------------------------------------------------------------ + + + // CONSTRUCTOR + + + /* + * The BigNumber constructor and exported function. + * Create and return a new instance of a BigNumber object. + * + * n {number|string|BigNumber} A numeric value. + * [b] {number} The base of n. Integer, 2 to ALPHABET.length inclusive. + */ + function BigNumber(n, b) { + var alphabet, c, caseChanged, e, i, isNum, len, str, + x = this; + + // Enable constructor usage without new. + if (!(x instanceof BigNumber)) { + + // Don't throw on constructor call without new (#81). + // '[BigNumber Error] Constructor call without new: {n}' + //throw Error(bignumberError + ' Constructor call without new: ' + n); + return new BigNumber(n, b); + } + + if (b == null) { + + // Duplicate. + if (n instanceof BigNumber) { + x.s = n.s; + x.e = n.e; + x.c = (n = n.c) ? n.slice() : n; + return; + } + + isNum = typeof n == 'number'; + + if (isNum && n * 0 == 0) { + + // Use `1 / n` to handle minus zero also. + x.s = 1 / n < 0 ? (n = -n, -1) : 1; + + // Faster path for integers. + if (n === ~~n) { + for (e = 0, i = n; i >= 10; i /= 10, e++); + x.e = e; + x.c = [n]; + return; + } + + str = n + ''; + } else { + if (!isNumeric.test(str = n + '')) return parseNumeric(x, str, isNum); + x.s = str.charCodeAt(0) == 45 ? (str = str.slice(1), -1) : 1; + } + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + + // Exponential form? + if ((i = str.search(/e/i)) > 0) { + + // Determine exponent. + if (e < 0) e = i; + e += +str.slice(i + 1); + str = str.substring(0, i); + } else if (e < 0) { + + // Integer. + e = str.length; + } + + } else { + + // '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + intCheck(b, 2, ALPHABET.length, 'Base'); + str = n + ''; + + // Allow exponential notation to be used with base 10 argument, while + // also rounding to DECIMAL_PLACES as with other bases. + if (b == 10) { + x = new BigNumber(n instanceof BigNumber ? n : str); + return round(x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE); + } + + isNum = typeof n == 'number'; + + if (isNum) { + + // Avoid potential interpretation of Infinity and NaN as base 44+ values. + if (n * 0 != 0) return parseNumeric(x, str, isNum, b); + + x.s = 1 / n < 0 ? (str = str.slice(1), -1) : 1; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (BigNumber.DEBUG && str.replace(/^0\.0*|\./, '').length > 15) { + throw Error + (tooManyDigits + n); + } + + // Prevent later check for length on converted number. + isNum = false; + } else { + x.s = str.charCodeAt(0) === 45 ? (str = str.slice(1), -1) : 1; + } + + alphabet = ALPHABET.slice(0, b); + e = i = 0; + + // Check that str is a valid base b number. + // Don't use RegExp so alphabet can contain special characters. + for (len = str.length; i < len; i++) { + if (alphabet.indexOf(c = str.charAt(i)) < 0) { + if (c == '.') { + + // If '.' is not the first character and it has not be found before. + if (i > e) { + e = len; + continue; + } + } else if (!caseChanged) { + + // Allow e.g. hexadecimal 'FF' as well as 'ff'. + if (str == str.toUpperCase() && (str = str.toLowerCase()) || + str == str.toLowerCase() && (str = str.toUpperCase())) { + caseChanged = true; + i = -1; + e = 0; + continue; + } + } + + return parseNumeric(x, n + '', isNum, b); + } + } + + str = convertBase(str, b, 10, x.s); + + // Decimal point? + if ((e = str.indexOf('.')) > -1) str = str.replace('.', ''); + else e = str.length; + } + + // Determine leading zeros. + for (i = 0; str.charCodeAt(i) === 48; i++); + + // Determine trailing zeros. + for (len = str.length; str.charCodeAt(--len) === 48;); + + str = str.slice(i, ++len); + + if (str) { + len -= i; + + // '[BigNumber Error] Number primitive has more than 15 significant digits: {n}' + if (isNum && BigNumber.DEBUG && + len > 15 && (n > MAX_SAFE_INTEGER || n !== mathfloor(n))) { + throw Error + (tooManyDigits + (x.s * n)); + } + + e = e - i - 1; + + // Overflow? + if (e > MAX_EXP) { + + // Infinity. + x.c = x.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + x.c = [x.e = 0]; + } else { + x.e = e; + x.c = []; + + // Transform base + + // e is the base 10 exponent. + // i is where to slice str to get the first element of the coefficient array. + i = (e + 1) % LOG_BASE; + if (e < 0) i += LOG_BASE; + + if (i < len) { + if (i) x.c.push(+str.slice(0, i)); + + for (len -= LOG_BASE; i < len;) { + x.c.push(+str.slice(i, i += LOG_BASE)); + } + + str = str.slice(i); + i = LOG_BASE - str.length; + } else { + i -= len; + } + + for (; i--; str += '0'); + x.c.push(+str); + } + } else { + + // Zero. + x.c = [x.e = 0]; + } + } + + + // CONSTRUCTOR PROPERTIES + + + BigNumber.clone = clone; + + BigNumber.ROUND_UP = 0; + BigNumber.ROUND_DOWN = 1; + BigNumber.ROUND_CEIL = 2; + BigNumber.ROUND_FLOOR = 3; + BigNumber.ROUND_HALF_UP = 4; + BigNumber.ROUND_HALF_DOWN = 5; + BigNumber.ROUND_HALF_EVEN = 6; + BigNumber.ROUND_HALF_CEIL = 7; + BigNumber.ROUND_HALF_FLOOR = 8; + BigNumber.EUCLID = 9; + + + /* + * Configure infrequently-changing library-wide settings. + * + * Accept an object with the following optional properties (if the value of a property is + * a number, it must be an integer within the inclusive range stated): + * + * DECIMAL_PLACES {number} 0 to MAX + * ROUNDING_MODE {number} 0 to 8 + * EXPONENTIAL_AT {number|number[]} -MAX to MAX or [-MAX to 0, 0 to MAX] + * RANGE {number|number[]} -MAX to MAX (not zero) or [-MAX to -1, 1 to MAX] + * CRYPTO {boolean} true or false + * MODULO_MODE {number} 0 to 9 + * POW_PRECISION {number} 0 to MAX + * ALPHABET {string} A string of two or more unique characters which does + * not contain '.'. + * FORMAT {object} An object with some of the following properties: + * decimalSeparator {string} + * groupSeparator {string} + * groupSize {number} + * secondaryGroupSize {number} + * fractionGroupSeparator {string} + * fractionGroupSize {number} + * + * (The values assigned to the above FORMAT object properties are not checked for validity.) + * + * E.g. + * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) + * + * Ignore properties/parameters set to null or undefined, except for ALPHABET. + * + * Return an object with the properties current values. + */ + BigNumber.config = BigNumber.set = function (obj) { + var p, v; + + if (obj != null) { + + if (typeof obj == 'object') { + + // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] DECIMAL_PLACES {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'DECIMAL_PLACES')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + DECIMAL_PLACES = v; + } + + // ROUNDING_MODE {number} Integer, 0 to 8 inclusive. + // '[BigNumber Error] ROUNDING_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'ROUNDING_MODE')) { + v = obj[p]; + intCheck(v, 0, 8, p); + ROUNDING_MODE = v; + } + + // EXPONENTIAL_AT {number|number[]} + // Integer, -MAX to MAX inclusive or + // [integer -MAX to 0 inclusive, 0 to MAX inclusive]. + // '[BigNumber Error] EXPONENTIAL_AT {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'EXPONENTIAL_AT')) { + v = obj[p]; + if (isArray(v)) { + intCheck(v[0], -MAX, 0, p); + intCheck(v[1], 0, MAX, p); + TO_EXP_NEG = v[0]; + TO_EXP_POS = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + TO_EXP_NEG = -(TO_EXP_POS = v < 0 ? -v : v); + } + } + + // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or + // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive]. + // '[BigNumber Error] RANGE {not a primitive number|not an integer|out of range|cannot be zero}: {v}' + if (obj.hasOwnProperty(p = 'RANGE')) { + v = obj[p]; + if (isArray(v)) { + intCheck(v[0], -MAX, -1, p); + intCheck(v[1], 1, MAX, p); + MIN_EXP = v[0]; + MAX_EXP = v[1]; + } else { + intCheck(v, -MAX, MAX, p); + if (v) { + MIN_EXP = -(MAX_EXP = v < 0 ? -v : v); + } else { + throw Error + (bignumberError + p + ' cannot be zero: ' + v); + } + } + } + + // CRYPTO {boolean} true or false. + // '[BigNumber Error] CRYPTO not true or false: {v}' + // '[BigNumber Error] crypto unavailable' + if (obj.hasOwnProperty(p = 'CRYPTO')) { + v = obj[p]; + if (v === !!v) { + if (v) { + if (typeof crypto != 'undefined' && crypto && + (crypto.getRandomValues || crypto.randomBytes)) { + CRYPTO = v; + } else { + CRYPTO = !v; + throw Error + (bignumberError + 'crypto unavailable'); + } + } else { + CRYPTO = v; + } + } else { + throw Error + (bignumberError + p + ' not true or false: ' + v); + } + } + + // MODULO_MODE {number} Integer, 0 to 9 inclusive. + // '[BigNumber Error] MODULO_MODE {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'MODULO_MODE')) { + v = obj[p]; + intCheck(v, 0, 9, p); + MODULO_MODE = v; + } + + // POW_PRECISION {number} Integer, 0 to MAX inclusive. + // '[BigNumber Error] POW_PRECISION {not a primitive number|not an integer|out of range}: {v}' + if (obj.hasOwnProperty(p = 'POW_PRECISION')) { + v = obj[p]; + intCheck(v, 0, MAX, p); + POW_PRECISION = v; + } + + // FORMAT {object} + // '[BigNumber Error] FORMAT not an object: {v}' + if (obj.hasOwnProperty(p = 'FORMAT')) { + v = obj[p]; + if (typeof v == 'object') FORMAT = v; + else throw Error + (bignumberError + p + ' not an object: ' + v); + } + + // ALPHABET {string} + // '[BigNumber Error] ALPHABET invalid: {v}' + if (obj.hasOwnProperty(p = 'ALPHABET')) { + v = obj[p]; + + // Disallow if only one character, or contains '.' or a repeated character. + if (typeof v == 'string' && !/^.$|\.|(.).*\1/.test(v)) { + ALPHABET = v; + } else { + throw Error + (bignumberError + p + ' invalid: ' + v); + } + } + + } else { + + // '[BigNumber Error] Object expected: {v}' + throw Error + (bignumberError + 'Object expected: ' + obj); + } + } + + return { + DECIMAL_PLACES: DECIMAL_PLACES, + ROUNDING_MODE: ROUNDING_MODE, + EXPONENTIAL_AT: [TO_EXP_NEG, TO_EXP_POS], + RANGE: [MIN_EXP, MAX_EXP], + CRYPTO: CRYPTO, + MODULO_MODE: MODULO_MODE, + POW_PRECISION: POW_PRECISION, + FORMAT: FORMAT, + ALPHABET: ALPHABET + }; + }; + + + /* + * Return true if v is a BigNumber instance, otherwise return false. + * + * v {any} + */ + BigNumber.isBigNumber = function (v) { + return v instanceof BigNumber || v && v._isBigNumber === true || false; + }; + + + /* + * Return a new BigNumber whose value is the maximum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.maximum = BigNumber.max = function () { + return maxOrMin(arguments, P.lt); + }; + + + /* + * Return a new BigNumber whose value is the minimum of the arguments. + * + * arguments {number|string|BigNumber} + */ + BigNumber.minimum = BigNumber.min = function () { + return maxOrMin(arguments, P.gt); + }; + + + /* + * Return a new BigNumber with a random value equal to or greater than 0 and less than 1, + * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing + * zeros are produced). + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp}' + * '[BigNumber Error] crypto unavailable' + */ + BigNumber.random = (function () { + var pow2_53 = 0x20000000000000; + + // Return a 53 bit integer n, where 0 <= n < 9007199254740992. + // Check if Math.random() produces more than 32 bits of randomness. + // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits. + // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1. + var random53bitInt = (Math.random() * pow2_53) & 0x1fffff + ? function () { return mathfloor(Math.random() * pow2_53); } + : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) + + (Math.random() * 0x800000 | 0); }; + + return function (dp) { + var a, b, e, k, v, + i = 0, + c = [], + rand = new BigNumber(ONE); + + if (dp == null) dp = DECIMAL_PLACES; + else intCheck(dp, 0, MAX); + + k = mathceil(dp / LOG_BASE); + + if (CRYPTO) { + + // Browsers supporting crypto.getRandomValues. + if (crypto.getRandomValues) { + + a = crypto.getRandomValues(new Uint32Array(k *= 2)); + + for (; i < k;) { + + // 53 bits: + // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2) + // 11111 11111111 11111111 11111111 11100000 00000000 00000000 + // ((Math.pow(2, 32) - 1) >>> 11).toString(2) + // 11111 11111111 11111111 + // 0x20000 is 2^21. + v = a[i] * 0x20000 + (a[i + 1] >>> 11); + + // Rejection sampling: + // 0 <= v < 9007199254740992 + // Probability that v >= 9e15, is + // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 + if (v >= 9e15) { + b = crypto.getRandomValues(new Uint32Array(2)); + a[i] = b[0]; + a[i + 1] = b[1]; + } else { + + // 0 <= v <= 8999999999999999 + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 2; + } + } + i = k / 2; + + // Node.js supporting crypto.randomBytes. + } else if (crypto.randomBytes) { + + // buffer + a = crypto.randomBytes(k *= 7); + + for (; i < k;) { + + // 0x1000000000000 is 2^48, 0x10000000000 is 2^40 + // 0x100000000 is 2^32, 0x1000000 is 2^24 + // 11111 11111111 11111111 11111111 11111111 11111111 11111111 + // 0 <= v < 9007199254740992 + v = ((a[i] & 31) * 0x1000000000000) + (a[i + 1] * 0x10000000000) + + (a[i + 2] * 0x100000000) + (a[i + 3] * 0x1000000) + + (a[i + 4] << 16) + (a[i + 5] << 8) + a[i + 6]; + + if (v >= 9e15) { + crypto.randomBytes(7).copy(a, i); + } else { + + // 0 <= (v % 1e14) <= 99999999999999 + c.push(v % 1e14); + i += 7; + } + } + i = k / 7; + } else { + CRYPTO = false; + throw Error + (bignumberError + 'crypto unavailable'); + } + } + + // Use Math.random. + if (!CRYPTO) { + + for (; i < k;) { + v = random53bitInt(); + if (v < 9e15) c[i++] = v % 1e14; + } + } + + k = c[--i]; + dp %= LOG_BASE; + + // Convert trailing digits to zeros according to dp. + if (k && dp) { + v = POWS_TEN[LOG_BASE - dp]; + c[i] = mathfloor(k / v) * v; + } + + // Remove trailing elements which are zero. + for (; c[i] === 0; c.pop(), i--); + + // Zero? + if (i < 0) { + c = [e = 0]; + } else { + + // Remove leading elements which are zero and adjust exponent accordingly. + for (e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE); + + // Count the digits of the first element of c to determine leading zeros, and... + for (i = 1, v = c[0]; v >= 10; v /= 10, i++); + + // adjust the exponent accordingly. + if (i < LOG_BASE) e -= LOG_BASE - i; + } + + rand.e = e; + rand.c = c; + return rand; + }; + })(); + + + // PRIVATE FUNCTIONS + + + // Called by BigNumber and BigNumber.prototype.toString. + convertBase = (function () { + var decimal = '0123456789'; + + /* + * Convert string of baseIn to an array of numbers of baseOut. + * Eg. toBaseOut('255', 10, 16) returns [15, 15]. + * Eg. toBaseOut('ff', 16, 10) returns [2, 5, 5]. + */ + function toBaseOut(str, baseIn, baseOut, alphabet) { + var j, + arr = [0], + arrL, + i = 0, + len = str.length; + + for (; i < len;) { + for (arrL = arr.length; arrL--; arr[arrL] *= baseIn); + + arr[0] += alphabet.indexOf(str.charAt(i++)); + + for (j = 0; j < arr.length; j++) { + + if (arr[j] > baseOut - 1) { + if (arr[j + 1] == null) arr[j + 1] = 0; + arr[j + 1] += arr[j] / baseOut | 0; + arr[j] %= baseOut; + } + } + } + + return arr.reverse(); + } + + // Convert a numeric string of baseIn to a numeric string of baseOut. + // If the caller is toString, we are converting from base 10 to baseOut. + // If the caller is BigNumber, we are converting from baseIn to base 10. + return function (str, baseIn, baseOut, sign, callerIsToString) { + var alphabet, d, e, k, r, x, xc, y, + i = str.indexOf('.'), + dp = DECIMAL_PLACES, + rm = ROUNDING_MODE; + + // Non-integer. + if (i >= 0) { + k = POW_PRECISION; + + // Unlimited precision. + POW_PRECISION = 0; + str = str.replace('.', ''); + y = new BigNumber(baseIn); + x = y.pow(str.length - i); + POW_PRECISION = k; + + // Convert str as if an integer, then restore the fraction part by dividing the + // result by its base raised to a power. + + y.c = toBaseOut(toFixedPoint(coeffToString(x.c), x.e, '0'), + 10, baseOut, decimal); + y.e = y.c.length; + } + + // Convert the number as integer. + + xc = toBaseOut(str, baseIn, baseOut, callerIsToString + ? (alphabet = ALPHABET, decimal) + : (alphabet = decimal, ALPHABET)); + + // xc now represents str as an integer and converted to baseOut. e is the exponent. + e = k = xc.length; + + // Remove trailing zeros. + for (; xc[--k] == 0; xc.pop()); + + // Zero? + if (!xc[0]) return alphabet.charAt(0); + + // Does str represent an integer? If so, no need for the division. + if (i < 0) { + --e; + } else { + x.c = xc; + x.e = e; + + // The sign is needed for correct rounding. + x.s = sign; + x = div(x, y, dp, rm, baseOut); + xc = x.c; + r = x.r; + e = x.e; + } + + // xc now represents str converted to baseOut. + + // THe index of the rounding digit. + d = e + dp + 1; + + // The rounding digit: the digit to the right of the digit that may be rounded up. + i = xc[d]; + + // Look at the rounding digits and mode to determine whether to round up. + + k = baseOut / 2; + r = r || d < 0 || xc[d + 1] != null; + + r = rm < 4 ? (i != null || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : i > k || i == k &&(rm == 4 || r || rm == 6 && xc[d - 1] & 1 || + rm == (x.s < 0 ? 8 : 7)); + + // If the index of the rounding digit is not greater than zero, or xc represents + // zero, then the result of the base conversion is zero or, if rounding up, a value + // such as 0.00001. + if (d < 1 || !xc[0]) { + + // 1^-dp or 0 + str = r ? toFixedPoint(alphabet.charAt(1), -dp, alphabet.charAt(0)) + : alphabet.charAt(0); + } else { + + // Truncate xc to the required number of decimal places. + xc.length = d; + + // Round up? + if (r) { + + // Rounding up may mean the previous digit has to be rounded up and so on. + for (--baseOut; ++xc[--d] > baseOut;) { + xc[d] = 0; + + if (!d) { + ++e; + xc = [1].concat(xc); + } + } + } + + // Determine trailing zeros. + for (k = xc.length; !xc[--k];); + + // E.g. [4, 11, 15] becomes 4bf. + for (i = 0, str = ''; i <= k; str += alphabet.charAt(xc[i++])); + + // Add leading zeros, decimal point and trailing zeros as required. + str = toFixedPoint(str, e, alphabet.charAt(0)); + } + + // The caller will add the sign. + return str; + }; + })(); + + + // Perform division in the specified base. Called by div and convertBase. + div = (function () { + + // Assume non-zero x and k. + function multiply(x, k, base) { + var m, temp, xlo, xhi, + carry = 0, + i = x.length, + klo = k % SQRT_BASE, + khi = k / SQRT_BASE | 0; + + for (x = x.slice(); i--;) { + xlo = x[i] % SQRT_BASE; + xhi = x[i] / SQRT_BASE | 0; + m = khi * xlo + xhi * klo; + temp = klo * xlo + ((m % SQRT_BASE) * SQRT_BASE) + carry; + carry = (temp / base | 0) + (m / SQRT_BASE | 0) + khi * xhi; + x[i] = temp % base; + } + + if (carry) x = [carry].concat(x); + + return x; + } + + function compare(a, b, aL, bL) { + var i, cmp; + + if (aL != bL) { + cmp = aL > bL ? 1 : -1; + } else { + + for (i = cmp = 0; i < aL; i++) { + + if (a[i] != b[i]) { + cmp = a[i] > b[i] ? 1 : -1; + break; + } + } + } + + return cmp; + } + + function subtract(a, b, aL, base) { + var i = 0; + + // Subtract b from a. + for (; aL--;) { + a[aL] -= i; + i = a[aL] < b[aL] ? 1 : 0; + a[aL] = i * base + a[aL] - b[aL]; + } + + // Remove leading zeros. + for (; !a[0] && a.length > 1; a.splice(0, 1)); + } + + // x: dividend, y: divisor. + return function (x, y, dp, rm, base) { + var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0, + yL, yz, + s = x.s == y.s ? 1 : -1, + xc = x.c, + yc = y.c; + + // Either NaN, Infinity or 0? + if (!xc || !xc[0] || !yc || !yc[0]) { + + return new BigNumber( + + // Return NaN if either NaN, or both Infinity or 0. + !x.s || !y.s || (xc ? yc && xc[0] == yc[0] : !yc) ? NaN : + + // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0. + xc && xc[0] == 0 || !yc ? s * 0 : s / 0 + ); + } + + q = new BigNumber(s); + qc = q.c = []; + e = x.e - y.e; + s = dp + e + 1; + + if (!base) { + base = BASE; + e = bitFloor(x.e / LOG_BASE) - bitFloor(y.e / LOG_BASE); + s = s / LOG_BASE | 0; + } + + // Result exponent may be one less then the current value of e. + // The coefficients of the BigNumbers from convertBase may have trailing zeros. + for (i = 0; yc[i] == (xc[i] || 0); i++); + + if (yc[i] > (xc[i] || 0)) e--; + + if (s < 0) { + qc.push(1); + more = true; + } else { + xL = xc.length; + yL = yc.length; + i = 0; + s += 2; + + // Normalise xc and yc so highest order digit of yc is >= base / 2. + + n = mathfloor(base / (yc[0] + 1)); + + // Not necessary, but to handle odd bases where yc[0] == (base / 2) - 1. + // if (n > 1 || n++ == 1 && yc[0] < base / 2) { + if (n > 1) { + yc = multiply(yc, n, base); + xc = multiply(xc, n, base); + yL = yc.length; + xL = xc.length; + } + + xi = yL; + rem = xc.slice(0, yL); + remL = rem.length; + + // Add zeros to make remainder as long as divisor. + for (; remL < yL; rem[remL++] = 0); + yz = yc.slice(); + yz = [0].concat(yz); + yc0 = yc[0]; + if (yc[1] >= base / 2) yc0++; + // Not necessary, but to prevent trial digit n > base, when using base 3. + // else if (base == 3 && yc0 == 1) yc0 = 1 + 1e-15; + + do { + n = 0; + + // Compare divisor and remainder. + cmp = compare(yc, rem, yL, remL); + + // If divisor < remainder. + if (cmp < 0) { + + // Calculate trial digit, n. + + rem0 = rem[0]; + if (yL != remL) rem0 = rem0 * base + (rem[1] || 0); + + // n is how many times the divisor goes into the current remainder. + n = mathfloor(rem0 / yc0); + + // Algorithm: + // product = divisor multiplied by trial digit (n). + // Compare product and remainder. + // If product is greater than remainder: + // Subtract divisor from product, decrement trial digit. + // Subtract product from remainder. + // If product was less than remainder at the last compare: + // Compare new remainder and divisor. + // If remainder is greater than divisor: + // Subtract divisor from remainder, increment trial digit. + + if (n > 1) { + + // n may be > base only when base is 3. + if (n >= base) n = base - 1; + + // product = divisor * trial digit. + prod = multiply(yc, n, base); + prodL = prod.length; + remL = rem.length; + + // Compare product and remainder. + // If product > remainder then trial digit n too high. + // n is 1 too high about 5% of the time, and is not known to have + // ever been more than 1 too high. + while (compare(prod, rem, prodL, remL) == 1) { + n--; + + // Subtract divisor from product. + subtract(prod, yL < prodL ? yz : yc, prodL, base); + prodL = prod.length; + cmp = 1; + } + } else { + + // n is 0 or 1, cmp is -1. + // If n is 0, there is no need to compare yc and rem again below, + // so change cmp to 1 to avoid it. + // If n is 1, leave cmp as -1, so yc and rem are compared again. + if (n == 0) { + + // divisor < remainder, so n must be at least 1. + cmp = n = 1; + } + + // product = divisor + prod = yc.slice(); + prodL = prod.length; + } + + if (prodL < remL) prod = [0].concat(prod); + + // Subtract product from remainder. + subtract(rem, prod, remL, base); + remL = rem.length; + + // If product was < remainder. + if (cmp == -1) { + + // Compare divisor and new remainder. + // If divisor < new remainder, subtract divisor from remainder. + // Trial digit n too low. + // n is 1 too low about 5% of the time, and very rarely 2 too low. + while (compare(yc, rem, yL, remL) < 1) { + n++; + + // Subtract divisor from remainder. + subtract(rem, yL < remL ? yz : yc, remL, base); + remL = rem.length; + } + } + } else if (cmp === 0) { + n++; + rem = [0]; + } // else cmp === 1 and n will be 0 + + // Add the next digit, n, to the result array. + qc[i++] = n; + + // Update the remainder. + if (rem[0]) { + rem[remL++] = xc[xi] || 0; + } else { + rem = [xc[xi]]; + remL = 1; + } + } while ((xi++ < xL || rem[0] != null) && s--); + + more = rem[0] != null; + + // Leading zero? + if (!qc[0]) qc.splice(0, 1); + } + + if (base == BASE) { + + // To calculate q.e, first get the number of digits of qc[0]. + for (i = 1, s = qc[0]; s >= 10; s /= 10, i++); + + round(q, dp + (q.e = i + e * LOG_BASE - 1) + 1, rm, more); + + // Caller is convertBase. + } else { + q.e = e; + q.r = +more; + } + + return q; + }; + })(); + + + /* + * Return a string representing the value of BigNumber n in fixed-point or exponential + * notation rounded to the specified decimal places or significant digits. + * + * n: a BigNumber. + * i: the index of the last digit required (i.e. the digit that may be rounded up). + * rm: the rounding mode. + * id: 1 (toExponential) or 2 (toPrecision). + */ + function format(n, i, rm, id) { + var c0, e, ne, len, str; + + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + if (!n.c) return n.toString(); + + c0 = n.c[0]; + ne = n.e; + + if (i == null) { + str = coeffToString(n.c); + str = id == 1 || id == 2 && ne <= TO_EXP_NEG + ? toExponential(str, ne) + : toFixedPoint(str, ne, '0'); + } else { + n = round(new BigNumber(n), i, rm); + + // n.e may have changed if the value was rounded up. + e = n.e; + + str = coeffToString(n.c); + len = str.length; + + // toPrecision returns exponential notation if the number of significant digits + // specified is less than the number of digits necessary to represent the integer + // part of the value in fixed-point notation. + + // Exponential notation. + if (id == 1 || id == 2 && (i <= e || e <= TO_EXP_NEG)) { + + // Append zeros? + for (; len < i; str += '0', len++); + str = toExponential(str, e); + + // Fixed-point notation. + } else { + i -= ne; + str = toFixedPoint(str, e, '0'); + + // Append zeros? + if (e + 1 > len) { + if (--i > 0) for (str += '.'; i--; str += '0'); + } else { + i += e - len; + if (i > 0) { + if (e + 1 == len) str += '.'; + for (; i--; str += '0'); + } + } + } + } + + return n.s < 0 && c0 ? '-' + str : str; + } + + + // Handle BigNumber.max and BigNumber.min. + function maxOrMin(args, method) { + var m, n, + i = 0; + + if (isArray(args[0])) args = args[0]; + m = new BigNumber(args[0]); + + for (; ++i < args.length;) { + n = new BigNumber(args[i]); + + // If any number is NaN, return NaN. + if (!n.s) { + m = n; + break; + } else if (method.call(m, n)) { + m = n; + } + } + + return m; + } + + + /* + * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. + * Called by minus, plus and times. + */ + function normalise(n, c, e) { + var i = 1, + j = c.length; + + // Remove trailing zeros. + for (; !c[--j]; c.pop()); + + // Calculate the base 10 exponent. First get the number of digits of c[0]. + for (j = c[0]; j >= 10; j /= 10, i++); + + // Overflow? + if ((e = i + e * LOG_BASE - 1) > MAX_EXP) { + + // Infinity. + n.c = n.e = null; + + // Underflow? + } else if (e < MIN_EXP) { + + // Zero. + n.c = [n.e = 0]; + } else { + n.e = e; + n.c = c; + } + + return n; + } + + + // Handle values that fail the validity test in BigNumber. + parseNumeric = (function () { + var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i, + dotAfter = /^([^.]+)\.$/, + dotBefore = /^\.([^.]+)$/, + isInfinityOrNaN = /^-?(Infinity|NaN)$/, + whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g; + + return function (x, str, isNum, b) { + var base, + s = isNum ? str : str.replace(whitespaceOrPlus, ''); + + // No exception on ±Infinity or NaN. + if (isInfinityOrNaN.test(s)) { + x.s = isNaN(s) ? null : s < 0 ? -1 : 1; + x.c = x.e = null; + } else { + if (!isNum) { + + // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i + s = s.replace(basePrefix, function (m, p1, p2) { + base = (p2 = p2.toLowerCase()) == 'x' ? 16 : p2 == 'b' ? 2 : 8; + return !b || b == base ? p1 : m; + }); + + if (b) { + base = b; + + // E.g. '1.' to '1', '.1' to '0.1' + s = s.replace(dotAfter, '$1').replace(dotBefore, '0.$1'); + } + + if (str != s) return new BigNumber(s, base); + } + + // '[BigNumber Error] Not a number: {n}' + // '[BigNumber Error] Not a base {b} number: {n}' + if (BigNumber.DEBUG) { + throw Error + (bignumberError + 'Not a' + (b ? ' base ' + b : '') + ' number: ' + str); + } + + // NaN + x.c = x.e = x.s = null; + } + } + })(); + + + /* + * Round x to sd significant digits using rounding mode rm. Check for over/under-flow. + * If r is truthy, it is known that there are more digits after the rounding digit. + */ + function round(x, sd, rm, r) { + var d, i, j, k, n, ni, rd, + xc = x.c, + pows10 = POWS_TEN; + + // if x is not Infinity or NaN... + if (xc) { + + // rd is the rounding digit, i.e. the digit after the digit that may be rounded up. + // n is a base 1e14 number, the value of the element of array x.c containing rd. + // ni is the index of n within x.c. + // d is the number of digits of n. + // i is the index of rd within n including leading zeros. + // j is the actual index of rd within n (if < 0, rd is a leading zero). + out: { + + // Get the number of digits of the first element of xc. + for (d = 1, k = xc[0]; k >= 10; k /= 10, d++); + i = sd - d; + + // If the rounding digit is in the first element of xc... + if (i < 0) { + i += LOG_BASE; + j = sd; + n = xc[ni = 0]; + + // Get the rounding digit at index j of n. + rd = n / pows10[d - j - 1] % 10 | 0; + } else { + ni = mathceil((i + 1) / LOG_BASE); + + if (ni >= xc.length) { + + if (r) { + + // Needed by sqrt. + for (; xc.length <= ni; xc.push(0)); + n = rd = 0; + d = 1; + i %= LOG_BASE; + j = i - LOG_BASE + 1; + } else { + break out; + } + } else { + n = k = xc[ni]; + + // Get the number of digits of n. + for (d = 1; k >= 10; k /= 10, d++); + + // Get the index of rd within n. + i %= LOG_BASE; + + // Get the index of rd within n, adjusted for leading zeros. + // The number of leading zeros of n is given by LOG_BASE - d. + j = i - LOG_BASE + d; + + // Get the rounding digit at index j of n. + rd = j < 0 ? 0 : n / pows10[d - j - 1] % 10 | 0; + } + } + + r = r || sd < 0 || + + // Are there any non-zero digits after the rounding digit? + // The expression n % pows10[d - j - 1] returns all digits of n to the right + // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714. + xc[ni + 1] != null || (j < 0 ? n : n % pows10[d - j - 1]); + + r = rm < 4 + ? (rd || r) && (rm == 0 || rm == (x.s < 0 ? 3 : 2)) + : rd > 5 || rd == 5 && (rm == 4 || r || rm == 6 && + + // Check whether the digit to the left of the rounding digit is odd. + ((i > 0 ? j > 0 ? n / pows10[d - j] : 0 : xc[ni - 1]) % 10) & 1 || + rm == (x.s < 0 ? 8 : 7)); + + if (sd < 1 || !xc[0]) { + xc.length = 0; + + if (r) { + + // Convert sd to decimal places. + sd -= x.e + 1; + + // 1, 0.1, 0.01, 0.001, 0.0001 etc. + xc[0] = pows10[(LOG_BASE - sd % LOG_BASE) % LOG_BASE]; + x.e = -sd || 0; + } else { + + // Zero. + xc[0] = x.e = 0; + } + + return x; + } + + // Remove excess digits. + if (i == 0) { + xc.length = ni; + k = 1; + ni--; + } else { + xc.length = ni + 1; + k = pows10[LOG_BASE - i]; + + // E.g. 56700 becomes 56000 if 7 is the rounding digit. + // j > 0 means i > number of leading zeros of n. + xc[ni] = j > 0 ? mathfloor(n / pows10[d - j] % pows10[j]) * k : 0; + } + + // Round up? + if (r) { + + for (; ;) { + + // If the digit to be rounded up is in the first element of xc... + if (ni == 0) { + + // i will be the length of xc[0] before k is added. + for (i = 1, j = xc[0]; j >= 10; j /= 10, i++); + j = xc[0] += k; + for (k = 1; j >= 10; j /= 10, k++); + + // if i != k the length has increased. + if (i != k) { + x.e++; + if (xc[0] == BASE) xc[0] = 1; + } + + break; + } else { + xc[ni] += k; + if (xc[ni] != BASE) break; + xc[ni--] = 0; + k = 1; + } + } + } + + // Remove trailing zeros. + for (i = xc.length; xc[--i] === 0; xc.pop()); + } + + // Overflow? Infinity. + if (x.e > MAX_EXP) { + x.c = x.e = null; + + // Underflow? Zero. + } else if (x.e < MIN_EXP) { + x.c = [x.e = 0]; + } + } + + return x; + } + + + // PROTOTYPE/INSTANCE METHODS + + + /* + * Return a new BigNumber whose value is the absolute value of this BigNumber. + */ + P.absoluteValue = P.abs = function () { + var x = new BigNumber(this); + if (x.s < 0) x.s = 1; + return x; + }; + + + /* + * Return + * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b), + * -1 if the value of this BigNumber is less than the value of BigNumber(y, b), + * 0 if they have the same value, + * or null if the value of either is NaN. + */ + P.comparedTo = function (y, b) { + return compare(this, new BigNumber(y, b)); + }; + + + /* + * If dp is undefined or null or true or false, return the number of decimal places of the + * value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * + * Otherwise, if dp is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of dp decimal places using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * [dp] {number} Decimal places: integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.decimalPlaces = P.dp = function (dp, rm) { + var c, n, v, + x = this; + + if (dp != null) { + intCheck(dp, 0, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), dp + x.e + 1, rm); + } + + if (!(c = x.c)) return null; + n = ((v = c.length - 1) - bitFloor(this.e / LOG_BASE)) * LOG_BASE; + + // Subtract the number of trailing zeros of the last number. + if (v = c[v]) for (; v % 10 == 0; v /= 10, n--); + if (n < 0) n = 0; + + return n; + }; + + + /* + * n / 0 = I + * n / N = N + * n / I = 0 + * 0 / n = 0 + * 0 / 0 = N + * 0 / N = N + * 0 / I = 0 + * N / n = N + * N / 0 = N + * N / N = N + * N / I = N + * I / n = I + * I / 0 = I + * I / N = N + * I / I = N + * + * Return a new BigNumber whose value is the value of this BigNumber divided by the value of + * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.dividedBy = P.div = function (y, b) { + return div(this, new BigNumber(y, b), DECIMAL_PLACES, ROUNDING_MODE); + }; + + + /* + * Return a new BigNumber whose value is the integer part of dividing the value of this + * BigNumber by the value of BigNumber(y, b). + */ + P.dividedToIntegerBy = P.idiv = function (y, b) { + return div(this, new BigNumber(y, b), 0, 1); + }; + + + /* + * Return a BigNumber whose value is the value of this BigNumber exponentiated by n. + * + * If m is present, return the result modulo m. + * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE. + * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using ROUNDING_MODE. + * + * The modular power operation works efficiently when x, n, and m are integers, otherwise it + * is equivalent to calculating x.exponentiatedBy(n).modulo(m) with a POW_PRECISION of 0. + * + * n {number|string|BigNumber} The exponent. An integer. + * [m] {number|string|BigNumber} The modulus. + * + * '[BigNumber Error] Exponent not an integer: {n}' + */ + P.exponentiatedBy = P.pow = function (n, m) { + var half, isModExp, k, more, nIsBig, nIsNeg, nIsOdd, y, + x = this; + + n = new BigNumber(n); + + // Allow NaN and ±Infinity, but not other non-integers. + if (n.c && !n.isInteger()) { + throw Error + (bignumberError + 'Exponent not an integer: ' + n); + } + + if (m != null) m = new BigNumber(m); + + // Exponent of MAX_SAFE_INTEGER is 15. + nIsBig = n.e > 14; + + // If x is NaN, ±Infinity, ±0 or ±1, or n is ±Infinity, NaN or ±0. + if (!x.c || !x.c[0] || x.c[0] == 1 && !x.e && x.c.length == 1 || !n.c || !n.c[0]) { + + // The sign of the result of pow when x is negative depends on the evenness of n. + // If +n overflows to ±Infinity, the evenness of n would be not be known. + y = new BigNumber(Math.pow(+x.valueOf(), nIsBig ? 2 - isOdd(n) : +n)); + return m ? y.mod(m) : y; + } + + nIsNeg = n.s < 0; + + if (m) { + + // x % m returns NaN if abs(m) is zero, or m is NaN. + if (m.c ? !m.c[0] : !m.s) return new BigNumber(NaN); + + isModExp = !nIsNeg && x.isInteger() && m.isInteger(); + + if (isModExp) x = x.mod(m); + + // Overflow to ±Infinity: >=2**1e10 or >=1.0000024**1e15. + // Underflow to ±0: <=0.79**1e10 or <=0.9999975**1e15. + } else if (n.e > 9 && (x.e > 0 || x.e < -1 || (x.e == 0 + // [1, 240000000] + ? x.c[0] > 1 || nIsBig && x.c[1] >= 24e7 + // [80000000000000] [99999750000000] + : x.c[0] < 8e13 || nIsBig && x.c[0] <= 9999975e7))) { + + // If x is negative and n is odd, k = -0, else k = 0. + k = x.s < 0 && isOdd(n) ? -0 : 0; + + // If x >= 1, k = ±Infinity. + if (x.e > -1) k = 1 / k; + + // If n is negative return ±0, else return ±Infinity. + return new BigNumber(nIsNeg ? 1 / k : k); + + } else if (POW_PRECISION) { + + // Truncating each coefficient array to a length of k after each multiplication + // equates to truncating significant digits to POW_PRECISION + [28, 41], + // i.e. there will be a minimum of 28 guard digits retained. + k = mathceil(POW_PRECISION / LOG_BASE + 2); + } + + if (nIsBig) { + half = new BigNumber(0.5); + nIsOdd = isOdd(n); + } else { + nIsOdd = n % 2; + } + + if (nIsNeg) n.s = 1; + + y = new BigNumber(ONE); + + // Performs 54 loop iterations for n of 9007199254740991. + for (; ;) { + + if (nIsOdd) { + y = y.times(x); + if (!y.c) break; + + if (k) { + if (y.c.length > k) y.c.length = k; + } else if (isModExp) { + y = y.mod(m); //y = y.minus(div(y, m, 0, MODULO_MODE).times(m)); + } + } + + if (nIsBig) { + n = n.times(half); + round(n, n.e + 1, 1); + if (!n.c[0]) break; + nIsBig = n.e > 14; + nIsOdd = isOdd(n); + } else { + n = mathfloor(n / 2); + if (!n) break; + nIsOdd = n % 2; + } + + x = x.times(x); + + if (k) { + if (x.c && x.c.length > k) x.c.length = k; + } else if (isModExp) { + x = x.mod(m); //x = x.minus(div(x, m, 0, MODULO_MODE).times(m)); + } + } + + if (isModExp) return y; + if (nIsNeg) y = ONE.div(y); + + return m ? y.mod(m) : k ? round(y, POW_PRECISION, ROUNDING_MODE, more) : y; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber rounded to an integer + * using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {rm}' + */ + P.integerValue = function (rm) { + var n = new BigNumber(this); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + return round(n, n.e + 1, rm); + }; + + + /* + * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), + * otherwise return false. + */ + P.isEqualTo = P.eq = function (y, b) { + return compare(this, new BigNumber(y, b)) === 0; + }; + + + /* + * Return true if the value of this BigNumber is a finite number, otherwise return false. + */ + P.isFinite = function () { + return !!this.c; + }; + + + /* + * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isGreaterThan = P.gt = function (y, b) { + return compare(this, new BigNumber(y, b)) > 0; + }; + + + /* + * Return true if the value of this BigNumber is greater than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isGreaterThanOrEqualTo = P.gte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === 1 || b === 0; + + }; + + + /* + * Return true if the value of this BigNumber is an integer, otherwise return false. + */ + P.isInteger = function () { + return !!this.c && bitFloor(this.e / LOG_BASE) > this.c.length - 2; + }; + + + /* + * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), + * otherwise return false. + */ + P.isLessThan = P.lt = function (y, b) { + return compare(this, new BigNumber(y, b)) < 0; + }; + + + /* + * Return true if the value of this BigNumber is less than or equal to the value of + * BigNumber(y, b), otherwise return false. + */ + P.isLessThanOrEqualTo = P.lte = function (y, b) { + return (b = compare(this, new BigNumber(y, b))) === -1 || b === 0; + }; + + + /* + * Return true if the value of this BigNumber is NaN, otherwise return false. + */ + P.isNaN = function () { + return !this.s; + }; + + + /* + * Return true if the value of this BigNumber is negative, otherwise return false. + */ + P.isNegative = function () { + return this.s < 0; + }; + + + /* + * Return true if the value of this BigNumber is positive, otherwise return false. + */ + P.isPositive = function () { + return this.s > 0; + }; + + + /* + * Return true if the value of this BigNumber is 0 or -0, otherwise return false. + */ + P.isZero = function () { + return !!this.c && this.c[0] == 0; + }; + + + /* + * n - 0 = n + * n - N = N + * n - I = -I + * 0 - n = -n + * 0 - 0 = 0 + * 0 - N = N + * 0 - I = -I + * N - n = N + * N - 0 = N + * N - N = N + * N - I = N + * I - n = I + * I - 0 = I + * I - N = N + * I - I = N + * + * Return a new BigNumber whose value is the value of this BigNumber minus the value of + * BigNumber(y, b). + */ + P.minus = function (y, b) { + var i, j, t, xLTy, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.plus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Either Infinity? + if (!xc || !yc) return xc ? (y.s = -b, y) : new BigNumber(yc ? x : NaN); + + // Either zero? + if (!xc[0] || !yc[0]) { + + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + return yc[0] ? (y.s = -b, y) : new BigNumber(xc[0] ? x : + + // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity + ROUNDING_MODE == 3 ? -0 : 0); + } + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Determine which is the bigger number. + if (a = xe - ye) { + + if (xLTy = a < 0) { + a = -a; + t = xc; + } else { + ye = xe; + t = yc; + } + + t.reverse(); + + // Prepend zeros to equalise exponents. + for (b = a; b--; t.push(0)); + t.reverse(); + } else { + + // Exponents equal. Check digit by digit. + j = (xLTy = (a = xc.length) < (b = yc.length)) ? a : b; + + for (a = b = 0; b < j; b++) { + + if (xc[b] != yc[b]) { + xLTy = xc[b] < yc[b]; + break; + } + } + } + + // x < y? Point xc to the array of the bigger number. + if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s; + + b = (j = yc.length) - (i = xc.length); + + // Append zeros to xc if shorter. + // No need to add zeros to yc if shorter as subtract only needs to start at yc.length. + if (b > 0) for (; b--; xc[i++] = 0); + b = BASE - 1; + + // Subtract yc from xc. + for (; j > a;) { + + if (xc[--j] < yc[j]) { + for (i = j; i && !xc[--i]; xc[i] = b); + --xc[i]; + xc[j] += BASE; + } + + xc[j] -= yc[j]; + } + + // Remove leading zeros and adjust exponent accordingly. + for (; xc[0] == 0; xc.splice(0, 1), --ye); + + // Zero? + if (!xc[0]) { + + // Following IEEE 754 (2008) 6.3, + // n - n = +0 but n - n = -0 when rounding towards -Infinity. + y.s = ROUNDING_MODE == 3 ? -1 : 1; + y.c = [y.e = 0]; + return y; + } + + // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity + // for finite x and y. + return normalise(y, xc, ye); + }; + + + /* + * n % 0 = N + * n % N = N + * n % I = n + * 0 % n = 0 + * -0 % n = -0 + * 0 % 0 = N + * 0 % N = N + * 0 % I = 0 + * N % n = N + * N % 0 = N + * N % N = N + * N % I = N + * I % n = N + * I % 0 = N + * I % N = N + * I % I = N + * + * Return a new BigNumber whose value is the value of this BigNumber modulo the value of + * BigNumber(y, b). The result depends on the value of MODULO_MODE. + */ + P.modulo = P.mod = function (y, b) { + var q, s, + x = this; + + y = new BigNumber(y, b); + + // Return NaN if x is Infinity or NaN, or y is NaN or zero. + if (!x.c || !y.s || y.c && !y.c[0]) { + return new BigNumber(NaN); + + // Return x if y is Infinity or x is zero. + } else if (!y.c || x.c && !x.c[0]) { + return new BigNumber(x); + } + + if (MODULO_MODE == 9) { + + // Euclidian division: q = sign(y) * floor(x / abs(y)) + // r = x - qy where 0 <= r < abs(y) + s = y.s; + y.s = 1; + q = div(x, y, 0, 3); + y.s = s; + q.s *= s; + } else { + q = div(x, y, 0, MODULO_MODE); + } + + y = x.minus(q.times(y)); + + // To match JavaScript %, ensure sign of zero is sign of dividend. + if (!y.c[0] && MODULO_MODE == 1) y.s = x.s; + + return y; + }; + + + /* + * n * 0 = 0 + * n * N = N + * n * I = I + * 0 * n = 0 + * 0 * 0 = 0 + * 0 * N = N + * 0 * I = N + * N * n = N + * N * 0 = N + * N * N = N + * N * I = N + * I * n = I + * I * 0 = N + * I * N = N + * I * I = I + * + * Return a new BigNumber whose value is the value of this BigNumber multiplied by the value + * of BigNumber(y, b). + */ + P.multipliedBy = P.times = function (y, b) { + var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, + base, sqrtBase, + x = this, + xc = x.c, + yc = (y = new BigNumber(y, b)).c; + + // Either NaN, ±Infinity or ±0? + if (!xc || !yc || !xc[0] || !yc[0]) { + + // Return NaN if either is NaN, or one is 0 and the other is Infinity. + if (!x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc) { + y.c = y.e = y.s = null; + } else { + y.s *= x.s; + + // Return ±Infinity if either is ±Infinity. + if (!xc || !yc) { + y.c = y.e = null; + + // Return ±0 if either is ±0. + } else { + y.c = [0]; + y.e = 0; + } + } + + return y; + } + + e = bitFloor(x.e / LOG_BASE) + bitFloor(y.e / LOG_BASE); + y.s *= x.s; + xcL = xc.length; + ycL = yc.length; + + // Ensure xc points to longer array and xcL to its length. + if (xcL < ycL) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i; + + // Initialise the result array with zeros. + for (i = xcL + ycL, zc = []; i--; zc.push(0)); + + base = BASE; + sqrtBase = SQRT_BASE; + + for (i = ycL; --i >= 0;) { + c = 0; + ylo = yc[i] % sqrtBase; + yhi = yc[i] / sqrtBase | 0; + + for (k = xcL, j = i + k; j > i;) { + xlo = xc[--k] % sqrtBase; + xhi = xc[k] / sqrtBase | 0; + m = yhi * xlo + xhi * ylo; + xlo = ylo * xlo + ((m % sqrtBase) * sqrtBase) + zc[j] + c; + c = (xlo / base | 0) + (m / sqrtBase | 0) + yhi * xhi; + zc[j--] = xlo % base; + } + + zc[j] = c; + } + + if (c) { + ++e; + } else { + zc.splice(0, 1); + } + + return normalise(y, zc, e); + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber negated, + * i.e. multiplied by -1. + */ + P.negated = function () { + var x = new BigNumber(this); + x.s = -x.s || null; + return x; + }; + + + /* + * n + 0 = n + * n + N = N + * n + I = I + * 0 + n = n + * 0 + 0 = 0 + * 0 + N = N + * 0 + I = I + * N + n = N + * N + 0 = N + * N + N = N + * N + I = N + * I + n = I + * I + 0 = I + * I + N = N + * I + I = I + * + * Return a new BigNumber whose value is the value of this BigNumber plus the value of + * BigNumber(y, b). + */ + P.plus = function (y, b) { + var t, + x = this, + a = x.s; + + y = new BigNumber(y, b); + b = y.s; + + // Either NaN? + if (!a || !b) return new BigNumber(NaN); + + // Signs differ? + if (a != b) { + y.s = -b; + return x.minus(y); + } + + var xe = x.e / LOG_BASE, + ye = y.e / LOG_BASE, + xc = x.c, + yc = y.c; + + if (!xe || !ye) { + + // Return ±Infinity if either ±Infinity. + if (!xc || !yc) return new BigNumber(a / 0); + + // Either zero? + // Return y if y is non-zero, x if x is non-zero, or zero if both are zero. + if (!xc[0] || !yc[0]) return yc[0] ? y : new BigNumber(xc[0] ? x : a * 0); + } + + xe = bitFloor(xe); + ye = bitFloor(ye); + xc = xc.slice(); + + // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. + if (a = xe - ye) { + if (a > 0) { + ye = xe; + t = yc; + } else { + a = -a; + t = xc; + } + + t.reverse(); + for (; a--; t.push(0)); + t.reverse(); + } + + a = xc.length; + b = yc.length; + + // Point xc to the longer array, and b to the shorter length. + if (a - b < 0) t = yc, yc = xc, xc = t, b = a; + + // Only start adding at yc.length - 1 as the further digits of xc can be ignored. + for (a = 0; b;) { + a = (xc[--b] = xc[b] + yc[b] + a) / BASE | 0; + xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; + } + + if (a) { + xc = [a].concat(xc); + ++ye; + } + + // No need to check for zero, as +x + +y != 0 && -x + -y != 0 + // ye = MAX_EXP + 1 possible + return normalise(y, xc, ye); + }; + + + /* + * If sd is undefined or null or true or false, return the number of significant digits of + * the value of this BigNumber, or null if the value of this BigNumber is ±Infinity or NaN. + * If sd is true include integer-part trailing zeros in the count. + * + * Otherwise, if sd is a number, return a new BigNumber whose value is the value of this + * BigNumber rounded to a maximum of sd significant digits using rounding mode rm, or + * ROUNDING_MODE if rm is omitted. + * + * sd {number|boolean} number: significant digits: integer, 1 to MAX inclusive. + * boolean: whether to count integer-part trailing zeros: true or false. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.precision = P.sd = function (sd, rm) { + var c, n, v, + x = this; + + if (sd != null && sd !== !!sd) { + intCheck(sd, 1, MAX); + if (rm == null) rm = ROUNDING_MODE; + else intCheck(rm, 0, 8); + + return round(new BigNumber(x), sd, rm); + } + + if (!(c = x.c)) return null; + v = c.length - 1; + n = v * LOG_BASE + 1; + + if (v = c[v]) { + + // Subtract the number of trailing zeros of the last element. + for (; v % 10 == 0; v /= 10, n--); + + // Add the number of digits of the first element. + for (v = c[0]; v >= 10; v /= 10, n++); + } + + if (sd && x.e + 1 > n) n = x.e + 1; + + return n; + }; + + + /* + * Return a new BigNumber whose value is the value of this BigNumber shifted by k places + * (powers of 10). Shift to the right if n > 0, and to the left if n < 0. + * + * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {k}' + */ + P.shiftedBy = function (k) { + intCheck(k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER); + return this.times('1e' + k); + }; + + + /* + * sqrt(-n) = N + * sqrt(N) = N + * sqrt(-I) = N + * sqrt(I) = I + * sqrt(0) = 0 + * sqrt(-0) = -0 + * + * Return a new BigNumber whose value is the square root of the value of this BigNumber, + * rounded according to DECIMAL_PLACES and ROUNDING_MODE. + */ + P.squareRoot = P.sqrt = function () { + var m, n, r, rep, t, + x = this, + c = x.c, + s = x.s, + e = x.e, + dp = DECIMAL_PLACES + 4, + half = new BigNumber('0.5'); + + // Negative/NaN/Infinity/zero? + if (s !== 1 || !c || !c[0]) { + return new BigNumber(!s || s < 0 && (!c || c[0]) ? NaN : c ? x : 1 / 0); + } + + // Initial estimate. + s = Math.sqrt(+x); + + // Math.sqrt underflow/overflow? + // Pass x to Math.sqrt as integer, then adjust the exponent of the result. + if (s == 0 || s == 1 / 0) { + n = coeffToString(c); + if ((n.length + e) % 2 == 0) n += '0'; + s = Math.sqrt(n); + e = bitFloor((e + 1) / 2) - (e < 0 || e % 2); + + if (s == 1 / 0) { + n = '1e' + e; + } else { + n = s.toExponential(); + n = n.slice(0, n.indexOf('e') + 1) + e; + } + + r = new BigNumber(n); + } else { + r = new BigNumber(s + ''); + } + + // Check for zero. + // r could be zero if MIN_EXP is changed after the this value was created. + // This would cause a division by zero (x/t) and hence Infinity below, which would cause + // coeffToString to throw. + if (r.c[0]) { + e = r.e; + s = e + dp; + if (s < 3) s = 0; + + // Newton-Raphson iteration. + for (; ;) { + t = r; + r = half.times(t.plus(div(x, t, dp, 1))); + + if (coeffToString(t.c ).slice(0, s) === (n = + coeffToString(r.c)).slice(0, s)) { + + // The exponent of r may here be one less than the final result exponent, + // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits + // are indexed correctly. + if (r.e < e) --s; + n = n.slice(s - 3, s + 1); + + // The 4th rounding digit may be in error by -1 so if the 4 rounding digits + // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the + // iteration. + if (n == '9999' || !rep && n == '4999') { + + // On the first iteration only, check to see if rounding up gives the + // exact result as the nines may infinitely repeat. + if (!rep) { + round(t, t.e + DECIMAL_PLACES + 2, 0); + + if (t.times(t).eq(x)) { + r = t; + break; + } + } + + dp += 4; + s += 4; + rep = 1; + } else { + + // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact + // result. If not, then there are further digits and m will be truthy. + if (!+n || !+n.slice(1) && n.charAt(0) == '5') { + + // Truncate to the first rounding digit. + round(r, r.e + DECIMAL_PLACES + 2, 1); + m = !r.times(r).eq(x); + } + + break; + } + } + } + } + + return round(r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m); + }; + + + /* + * Return a string representing the value of this BigNumber in exponential notation and + * rounded using ROUNDING_MODE to dp fixed decimal places. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toExponential = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp++; + } + return format(this, dp, rm, 1); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounding + * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted. + * + * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', + * but e.g. (-0.00001).toFixed(0) is '-0'. + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toFixed = function (dp, rm) { + if (dp != null) { + intCheck(dp, 0, MAX); + dp = dp + this.e + 1; + } + return format(this, dp, rm); + }; + + + /* + * Return a string representing the value of this BigNumber in fixed-point notation rounded + * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties + * of the FORMAT object (see BigNumber.set). + * + * FORMAT = { + * decimalSeparator : '.', + * groupSeparator : ',', + * groupSize : 3, + * secondaryGroupSize : 0, + * fractionGroupSeparator : '\xA0', // non-breaking space + * fractionGroupSize : 0 + * }; + * + * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {dp|rm}' + */ + P.toFormat = function (dp, rm) { + var str = this.toFixed(dp, rm); + + if (this.c) { + var i, + arr = str.split('.'), + g1 = +FORMAT.groupSize, + g2 = +FORMAT.secondaryGroupSize, + groupSeparator = FORMAT.groupSeparator, + intPart = arr[0], + fractionPart = arr[1], + isNeg = this.s < 0, + intDigits = isNeg ? intPart.slice(1) : intPart, + len = intDigits.length; + + if (g2) i = g1, g1 = g2, g2 = i, len -= i; + + if (g1 > 0 && len > 0) { + i = len % g1 || g1; + intPart = intDigits.substr(0, i); + + for (; i < len; i += g1) { + intPart += groupSeparator + intDigits.substr(i, g1); + } + + if (g2 > 0) intPart += groupSeparator + intDigits.slice(i); + if (isNeg) intPart = '-' + intPart; + } + + str = fractionPart + ? intPart + FORMAT.decimalSeparator + ((g2 = +FORMAT.fractionGroupSize) + ? fractionPart.replace(new RegExp('\\d{' + g2 + '}\\B', 'g'), + '$&' + FORMAT.fractionGroupSeparator) + : fractionPart) + : intPart; + } + + return str; + }; + + + /* + * Return a string array representing the value of this BigNumber as a simple fraction with + * an integer numerator and an integer denominator. The denominator will be a positive + * non-zero value less than or equal to the specified maximum denominator. If a maximum + * denominator is not specified, the denominator will be the lowest value necessary to + * represent the number exactly. + * + * [md] {number|string|BigNumber} Integer >= 1, or Infinity. The maximum denominator. + * + * '[BigNumber Error] Argument {not an integer|out of range} : {md}' + */ + P.toFraction = function (md) { + var arr, d, d0, d1, d2, e, exp, n, n0, n1, q, s, + x = this, + xc = x.c; + + if (md != null) { + n = new BigNumber(md); + + // Throw if md is less than one or is not an integer, unless it is Infinity. + if (!n.isInteger() && (n.c || n.s !== 1) || n.lt(ONE)) { + throw Error + (bignumberError + 'Argument ' + + (n.isInteger() ? 'out of range: ' : 'not an integer: ') + md); + } + } + + if (!xc) return x.toString(); + + d = new BigNumber(ONE); + n1 = d0 = new BigNumber(ONE); + d1 = n0 = new BigNumber(ONE); + s = coeffToString(xc); + + // Determine initial denominator. + // d is a power of 10 and the minimum max denominator that specifies the value exactly. + e = d.e = s.length - x.e - 1; + d.c[0] = POWS_TEN[(exp = e % LOG_BASE) < 0 ? LOG_BASE + exp : exp]; + md = !md || n.comparedTo(d) > 0 ? (e > 0 ? d : n1) : n; + + exp = MAX_EXP; + MAX_EXP = 1 / 0; + n = new BigNumber(s); + + // n0 = d1 = 0 + n0.c[0] = 0; + + for (; ;) { + q = div(n, d, 0, 1); + d2 = d0.plus(q.times(d1)); + if (d2.comparedTo(md) == 1) break; + d0 = d1; + d1 = d2; + n1 = n0.plus(q.times(d2 = n1)); + n0 = d2; + d = n.minus(q.times(d2 = d)); + n = d2; + } + + d2 = div(md.minus(d0), d1, 0, 1); + n0 = n0.plus(d2.times(n1)); + d0 = d0.plus(d2.times(d1)); + n0.s = n1.s = x.s; + e *= 2; + + // Determine which fraction is closer to x, n0/d0 or n1/d1 + arr = div(n1, d1, e, ROUNDING_MODE).minus(x).abs().comparedTo( + div(n0, d0, e, ROUNDING_MODE).minus(x).abs()) < 1 + ? [n1.toString(), d1.toString()] + : [n0.toString(), d0.toString()]; + + MAX_EXP = exp; + return arr; + }; + + + /* + * Return the value of this BigNumber converted to a number primitive. + */ + P.toNumber = function () { + return +this; + }; + + + /* + * Return a string representing the value of this BigNumber rounded to sd significant digits + * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits + * necessary to represent the integer part of the value in fixed-point notation, then use + * exponential notation. + * + * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. + * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. + * + * '[BigNumber Error] Argument {not a primitive number|not an integer|out of range}: {sd|rm}' + */ + P.toPrecision = function (sd, rm) { + if (sd != null) intCheck(sd, 1, MAX); + return format(this, sd, rm, 2); + }; + + + /* + * Return a string representing the value of this BigNumber in base b, or base 10 if b is + * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and + * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent + * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than + * TO_EXP_NEG, return exponential notation. + * + * [b] {number} Integer, 2 to ALPHABET.length inclusive. + * + * '[BigNumber Error] Base {not a primitive number|not an integer|out of range}: {b}' + */ + P.toString = function (b) { + var str, + n = this, + s = n.s, + e = n.e; + + // Infinity or NaN? + if (e === null) { + + if (s) { + str = 'Infinity'; + if (s < 0) str = '-' + str; + } else { + str = 'NaN'; + } + } else { + str = coeffToString(n.c); + + if (b == null) { + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(str, e) + : toFixedPoint(str, e, '0'); + } else { + intCheck(b, 2, ALPHABET.length, 'Base'); + str = convertBase(toFixedPoint(str, e, '0'), 10, b, s, true); + } + + if (s < 0 && n.c[0]) str = '-' + str; + } + + return str; + }; + + + /* + * Return as toString, but do not accept a base argument, and include the minus sign for + * negative zero. + */ + P.valueOf = P.toJSON = function () { + var str, + n = this, + e = n.e; + + if (e === null) return n.toString(); + + str = coeffToString(n.c); + + str = e <= TO_EXP_NEG || e >= TO_EXP_POS + ? toExponential(str, e) + : toFixedPoint(str, e, '0'); + + return n.s < 0 ? '-' + str : str; + }; + + + P._isBigNumber = true; + + if (configObject != null) BigNumber.set(configObject); + + return BigNumber; +} + + +// PRIVATE HELPER FUNCTIONS + + +function bitFloor(n) { + var i = n | 0; + return n > 0 || n === i ? i : i - 1; +} + + +// Return a coefficient array as a string of base 10 digits. +function coeffToString(a) { + var s, z, + i = 1, + j = a.length, + r = a[0] + ''; + + for (; i < j;) { + s = a[i++] + ''; + z = LOG_BASE - s.length; + for (; z--; s = '0' + s); + r += s; + } + + // Determine trailing zeros. + for (j = r.length; r.charCodeAt(--j) === 48;); + return r.slice(0, j + 1 || 1); +} + + +// Compare the value of BigNumbers x and y. +function compare(x, y) { + var a, b, + xc = x.c, + yc = y.c, + i = x.s, + j = y.s, + k = x.e, + l = y.e; + + // Either NaN? + if (!i || !j) return null; + + a = xc && !xc[0]; + b = yc && !yc[0]; + + // Either zero? + if (a || b) return a ? b ? 0 : -j : i; + + // Signs differ? + if (i != j) return i; + + a = i < 0; + b = k == l; + + // Either Infinity? + if (!xc || !yc) return b ? 0 : !xc ^ a ? 1 : -1; + + // Compare exponents. + if (!b) return k > l ^ a ? 1 : -1; + + j = (k = xc.length) < (l = yc.length) ? k : l; + + // Compare digit by digit. + for (i = 0; i < j; i++) if (xc[i] != yc[i]) return xc[i] > yc[i] ^ a ? 1 : -1; + + // Compare lengths. + return k == l ? 0 : k > l ^ a ? 1 : -1; +} + + +/* + * Check that n is a primitive number, an integer, and in range, otherwise throw. + */ +function intCheck(n, min, max, name) { + if (n < min || n > max || n !== (n < 0 ? mathceil(n) : mathfloor(n))) { + throw Error + (bignumberError + (name || 'Argument') + (typeof n == 'number' + ? n < min || n > max ? ' out of range: ' : ' not an integer: ' + : ' not a primitive number: ') + n); + } +} + + +function isArray(obj) { + return Object.prototype.toString.call(obj) == '[object Array]'; +} + + +// Assumes finite n. +function isOdd(n) { + var k = n.c.length - 1; + return bitFloor(n.e / LOG_BASE) == k && n.c[k] % 2 != 0; +} + + +function toExponential(str, e) { + return (str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str) + + (e < 0 ? 'e' : 'e+') + e; +} + + +function toFixedPoint(str, e, z) { + var len, zs; + + // Negative exponent? + if (e < 0) { + + // Prepend zeros. + for (zs = z + '.'; ++e; zs += z); + str = zs + str; + + // Positive exponent + } else { + len = str.length; + + // Append zeros. + if (++e > len) { + for (zs = z, e -= len; --e; zs += z); + str += zs; + } else if (e < len) { + str = str.slice(0, e) + '.' + str.slice(e); + } + } + + return str; +} + + +// EXPORTS + + +export var BigNumber = clone(); + +export default BigNumber; diff --git a/node_modules/bignumber.js/bower.json b/node_modules/bignumber.js/bower.json new file mode 100644 index 0000000..5fb671a --- /dev/null +++ b/node_modules/bignumber.js/bower.json @@ -0,0 +1,36 @@ +{ + "name": "bignumber.js", + "main": "bignumber.js", + "version": "7.2.1", + "homepage": "https://github.com/MikeMcl/bignumber.js", + "authors": [ + "Michael Mclaughlin " + ], + "description": "A library for arbitrary-precision decimal and non-decimal arithmetic", + "moduleType": [ + "amd", + "globals", + "node" + ], + "keywords": [ + "arbitrary", + "precision", + "arithmetic", + "big", + "number", + "decimal", + "float", + "biginteger", + "bigdecimal", + "bignumber", + "bigint", + "bignum" + ], + "license": "MIT", + "ignore": [ + ".*", + "*.json", + "test" + ] +} + diff --git a/node_modules/bignumber.js/doc/API.html b/node_modules/bignumber.js/doc/API.html new file mode 100644 index 0000000..ee1a4d1 --- /dev/null +++ b/node_modules/bignumber.js/doc/API.html @@ -0,0 +1,2118 @@ + + + + + + +bignumber.js API + + + + + + +
+ +

bignumber.js

+ +

A JavaScript library for arbitrary-precision arithmetic.

+

Hosted on GitHub.

+ +

API

+ +

+ See the README on GitHub for a + quick-start introduction. +

+

+ In all examples below, var and semicolons are not shown, and if a commented-out + value is in quotes it means toString has been called on the preceding expression. +

+ + +

CONSTRUCTOR

+ + +
+ BigNumberBigNumber(n [, base]) ⇒ BigNumber +
+

+ n: number|string|BigNumber
+ base: number: integer, 2 to 36 inclusive. (See + ALPHABET to extend this range). +

+

+ Returns a new instance of a BigNumber object with value n, where n + is a numeric value in the specified base, or base 10 if + base is omitted or is null or undefined. +

+
+x = new BigNumber(123.4567)                // '123.4567'
+// 'new' is optional
+y = BigNumber(x)                           // '123.4567'
+

+ If n is a base 10 value it can be in normal (fixed-point) or + exponential notation. Values in other bases must be in normal notation. Values in any base can + have fraction digits, i.e. digits after the decimal point. +

+
+new BigNumber(43210)                       // '43210'
+new BigNumber('4.321e+4')                  // '43210'
+new BigNumber('-735.0918e-430')            // '-7.350918e-428'
+new BigNumber('123412421.234324', 5)       // '607236.557696'
+

+ Signed 0, signed Infinity and NaN are supported. +

+
+new BigNumber('-Infinity')                 // '-Infinity'
+new BigNumber(NaN)                         // 'NaN'
+new BigNumber(-0)                          // '0'
+new BigNumber('.5')                        // '0.5'
+new BigNumber('+2')                        // '2'
+

+ String values in hexadecimal literal form, e.g. '0xff', are valid, as are + string values with the octal and binary prefixs '0o' and '0b'. + String values in octal literal form without the prefix will be interpreted as + decimals, e.g. '011' is interpreted as 11, not 9. +

+
+new BigNumber(-10110100.1, 2)              // '-180.5'
+new BigNumber('-0b10110100.1')             // '-180.5'
+new BigNumber('ff.8', 16)                  // '255.5'
+new BigNumber('0xff.8')                    // '255.5'
+

+ If a base is specified, n is rounded according to the current + DECIMAL_PLACES and + ROUNDING_MODE settings. This includes base + 10 so don't include a base parameter for decimal values unless + this behaviour is wanted. +

+
BigNumber.config({ DECIMAL_PLACES: 5 })
+new BigNumber(1.23456789)                  // '1.23456789'
+new BigNumber(1.23456789, 10)              // '1.23457'
+

An error is thrown if base is invalid. See Errors.

+

+ There is no limit to the number of digits of a value of type string (other than + that of JavaScript's maximum array size). See RANGE to set + the maximum and minimum possible exponent value of a BigNumber. +

+
+new BigNumber('5032485723458348569331745.33434346346912144534543')
+new BigNumber('4.321e10000000')
+

BigNumber NaN is returned if n is invalid + (unless BigNumber.DEBUG is true, see below).

+
+new BigNumber('.1*')                       // 'NaN'
+new BigNumber('blurgh')                    // 'NaN'
+new BigNumber(9, 2)                        // 'NaN'
+

+ To aid in debugging, if BigNumber.DEBUG is true then an error will + be thrown on an invalid n. An error will also be thrown if n is of + type number with more than 15 significant digits, as calling + toString or valueOf on + these numbers may not result in the intended value. +

+
+console.log(823456789123456.3)            //  823456789123456.2
+new BigNumber(823456789123456.3)          // '823456789123456.2'
+BigNumber.DEBUG = true
+// '[BigNumber Error] Number primitive has more than 15 significant digits'
+new BigNumber(823456789123456.3)
+// '[BigNumber Error] Not a base 2 number'
+new BigNumber(9, 2)
+ + + + +

Methods

+

The static methods of a BigNumber constructor.

+ + + + +
clone + .clone([object]) ⇒ BigNumber constructor +
+

object: object

+

+ Returns a new independent BigNumber constructor with configuration as described by + object (see config), or with the default + configuration if object is null or undefined. +

+

+ Throws if object is not an object. See Errors. +

+
BigNumber.config({ DECIMAL_PLACES: 5 })
+BN = BigNumber.clone({ DECIMAL_PLACES: 9 })
+
+x = new BigNumber(1)
+y = new BN(1)
+
+x.div(3)                        // 0.33333
+y.div(3)                        // 0.333333333
+
+// BN = BigNumber.clone({ DECIMAL_PLACES: 9 }) is equivalent to:
+BN = BigNumber.clone()
+BN.config({ DECIMAL_PLACES: 9 })
+ + + +
configset([object]) ⇒ object
+

+ object: object: an object that contains some or all of the following + properties. +

+

Configures the settings for this particular BigNumber constructor.

+ +
+
DECIMAL_PLACES
+
+ number: integer, 0 to 1e+9 inclusive
+ Default value: 20 +
+
+ The maximum number of decimal places of the results of operations involving + division, i.e. division, square root and base conversion operations, and power + operations with negative exponents.
+
+
+
BigNumber.config({ DECIMAL_PLACES: 5 })
+BigNumber.set({ DECIMAL_PLACES: 5 })    // equivalent
+
+ + + +
ROUNDING_MODE
+
+ number: integer, 0 to 8 inclusive
+ Default value: 4 (ROUND_HALF_UP) +
+
+ The rounding mode used in the above operations and the default rounding mode of + decimalPlaces, + precision, + toExponential, + toFixed, + toFormat and + toPrecision. +
+
The modes are available as enumerated properties of the BigNumber constructor.
+
+
BigNumber.config({ ROUNDING_MODE: 0 })
+BigNumber.set({ ROUNDING_MODE: BigNumber.ROUND_UP })    // equivalent
+
+ + + +
EXPONENTIAL_AT
+
+ number: integer, magnitude 0 to 1e+9 inclusive, or +
+ number[]: [ integer -1e+9 to 0 inclusive, integer + 0 to 1e+9 inclusive ]
+ Default value: [-7, 20] +
+
+ The exponent value(s) at which toString returns exponential notation. +
+
+ If a single number is assigned, the value is the exponent magnitude.
+ If an array of two numbers is assigned then the first number is the negative exponent + value at and beneath which exponential notation is used, and the second number is the + positive exponent value at and above which the same. +
+
+ For example, to emulate JavaScript numbers in terms of the exponent values at which they + begin to use exponential notation, use [-7, 20]. +
+
+
BigNumber.config({ EXPONENTIAL_AT: 2 })
+new BigNumber(12.3)         // '12.3'        e is only 1
+new BigNumber(123)          // '1.23e+2'
+new BigNumber(0.123)        // '0.123'       e is only -1
+new BigNumber(0.0123)       // '1.23e-2'
+
+BigNumber.config({ EXPONENTIAL_AT: [-7, 20] })
+new BigNumber(123456789)    // '123456789'   e is only 8
+new BigNumber(0.000000123)  // '1.23e-7'
+
+// Almost never return exponential notation:
+BigNumber.config({ EXPONENTIAL_AT: 1e+9 })
+
+// Always return exponential notation:
+BigNumber.config({ EXPONENTIAL_AT: 0 })
+
+
+ Regardless of the value of EXPONENTIAL_AT, the toFixed method + will always return a value in normal notation and the toExponential method + will always return a value in exponential form. +
+
+ Calling toString with a base argument, e.g. toString(10), will + also always return normal notation. +
+ + + +
RANGE
+
+ number: integer, magnitude 1 to 1e+9 inclusive, or +
+ number[]: [ integer -1e+9 to -1 inclusive, integer + 1 to 1e+9 inclusive ]
+ Default value: [-1e+9, 1e+9] +
+
+ The exponent value(s) beyond which overflow to Infinity and underflow to + zero occurs. +
+
+ If a single number is assigned, it is the maximum exponent magnitude: values wth a + positive exponent of greater magnitude become Infinity and those with a + negative exponent of greater magnitude become zero. +
+ If an array of two numbers is assigned then the first number is the negative exponent + limit and the second number is the positive exponent limit. +
+
+ For example, to emulate JavaScript numbers in terms of the exponent values at which they + become zero and Infinity, use [-324, 308]. +
+
+
BigNumber.config({ RANGE: 500 })
+BigNumber.config().RANGE     // [ -500, 500 ]
+new BigNumber('9.999e499')   // '9.999e+499'
+new BigNumber('1e500')       // 'Infinity'
+new BigNumber('1e-499')      // '1e-499'
+new BigNumber('1e-500')      // '0'
+
+BigNumber.config({ RANGE: [-3, 4] })
+new BigNumber(99999)         // '99999'      e is only 4
+new BigNumber(100000)        // 'Infinity'   e is 5
+new BigNumber(0.001)         // '0.01'       e is only -3
+new BigNumber(0.0001)        // '0'          e is -4
+
+
+ The largest possible magnitude of a finite BigNumber is + 9.999...e+1000000000.
+ The smallest possible magnitude of a non-zero BigNumber is 1e-1000000000. +
+ + + +
CRYPTO
+
+ boolean: true or false.
+ Default value: false +
+
+ The value that determines whether cryptographically-secure pseudo-random number + generation is used. +
+
+ If CRYPTO is set to true then the + random method will generate random digits using + crypto.getRandomValues in browsers that support it, or + crypto.randomBytes if using a version of Node.js that supports it. +
+
+ If neither function is supported by the host environment then attempting to set + CRYPTO to true will fail and an exception will be thrown. +
+
+ If CRYPTO is false then the source of randomness used will be + Math.random (which is assumed to generate at least 30 bits of + randomness). +
+
See random.
+
+
BigNumber.config({ CRYPTO: true })
+BigNumber.config().CRYPTO       // true
+BigNumber.random()              // 0.54340758610486147524
+
+ + + +
MODULO_MODE
+
+ number: integer, 0 to 9 inclusive
+ Default value: 1 (ROUND_DOWN) +
+
The modulo mode used when calculating the modulus: a mod n.
+
+ The quotient, q = a / n, is calculated according to the + ROUNDING_MODE that corresponds to the chosen + MODULO_MODE. +
+
The remainder, r, is calculated as: r = a - n * q.
+
+ The modes that are most commonly used for the modulus/remainder operation are shown in + the following table. Although the other rounding modes can be used, they may not give + useful results. +
+
+ + + + + + + + + + + + + + + + + + + + + + +
PropertyValueDescription
ROUND_UP0 + The remainder is positive if the dividend is negative, otherwise it is negative. +
ROUND_DOWN1 + The remainder has the same sign as the dividend.
+ This uses 'truncating division' and matches the behaviour of JavaScript's + remainder operator %. +
ROUND_FLOOR3 + The remainder has the same sign as the divisor.
+ This matches Python's % operator. +
ROUND_HALF_EVEN6The IEEE 754 remainder function.
EUCLID9 + The remainder is always positive. Euclidian division:
+ q = sign(n) * floor(a / abs(n)) +
+
+
+ The rounding/modulo modes are available as enumerated properties of the BigNumber + constructor. +
+
See modulo.
+
+
BigNumber.config({ MODULO_MODE: BigNumber.EUCLID })
+BigNumber.config({ MODULO_MODE: 9 })          // equivalent
+
+ + + +
POW_PRECISION
+
+ number: integer, 0 to 1e+9 inclusive.
+ Default value: 0 +
+
+ The maximum precision, i.e. number of significant digits, of the result of the power + operation (unless a modulus is specified). +
+
If set to 0, the number of significant digits will not be limited.
+
See exponentiatedBy.
+
BigNumber.config({ POW_PRECISION: 100 })
+ + + +
FORMAT
+
object
+
+ The FORMAT object configures the format of the string returned by the + toFormat method. +
+
+ The example below shows the properties of the FORMAT object that are + recognised, and their default values. +
+
+ Unlike the other configuration properties, the values of the properties of the + FORMAT object will not be checked for validity. The existing + FORMAT object will simply be replaced by the object that is passed in. + The object can include any number of the properties shown below. +
+
See toFormat for examples of usage.
+
+
+BigNumber.config({
+    FORMAT: {
+        // the decimal separator
+        decimalSeparator: '.',
+        // the grouping separator of the integer part
+        groupSeparator: ',',
+        // the primary grouping size of the integer part
+        groupSize: 3,
+        // the secondary grouping size of the integer part
+        secondaryGroupSize: 0,
+        // the grouping separator of the fraction part
+        fractionGroupSeparator: ' ',
+        // the grouping size of the fraction part
+        fractionGroupSize: 0
+    }
+});
+
+ + + +
ALPHABET
+
+ string
+ Default value: '0123456789abcdefghijklmnopqrstuvwxyz' +
+
+ The alphabet used for base conversion. The length of the alphabet corresponds to the + maximum value of the base argument that can be passed to the + BigNumber constructor or + toString. +
+
+ There is no maximum length for the alphabet, but it must be at least 2 characters long, and + it must not contain a repeated character, or '.', as that is used as the + decimal separator for all values whatever their base. +
+
+
// duodecimal (base 12)
+BigNumber.config({ ALPHABET: '0123456789TE' })
+x = new BigNumber('T', 12)
+x.toString()                // '10'
+x.toString(12)              // 'T'
+
+ + + +
+

+

Returns an object with the above properties and their current values.

+

+ Throws if object is not an object, or if an invalid value is assigned to + one or more of the above properties. See Errors. +

+
+BigNumber.config({
+    DECIMAL_PLACES: 40,
+    ROUNDING_MODE: BigNumber.ROUND_HALF_CEIL,
+    EXPONENTIAL_AT: [-10, 20],
+    RANGE: [-500, 500],
+    CRYPTO: true,
+    MODULO_MODE: BigNumber.ROUND_FLOOR,
+    POW_PRECISION: 80,
+    FORMAT: {
+        groupSize: 3,
+        groupSeparator: ' ',
+        decimalSeparator: ','
+    },
+    ALPHABET: '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_'
+});
+
+obj = BigNumber.config();
+obj.DECIMAL_PLACES        // 40
+obj.RANGE                 // [-500, 500]
+ + + +
+ isBigNumber.isBigNumber(value) ⇒ boolean +
+

value: any

+

+ Returns true if value is a BigNumber instance, otherwise returns + false. +

+
x = 42
+y = new BigNumber(x)
+
+BigNumber.isBigNumber(x)             // false
+y instanceof BigNumber               // true
+BigNumber.isBigNumber(y)             // true
+
+BN = BigNumber.clone();
+z = new BN(x)
+z instanceof BigNumber               // false
+BigNumber.isBigNumber(z)             // true
+ + + +
+ maximum.max([arg1 [, arg2, ...]]) ⇒ BigNumber +
+

+ arg1, arg2, ...: number|string|BigNumber
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the maximum of arg1, + arg2,... . +

+

The argument to this method can also be an array of values.

+

The return value is always exact and unrounded.

+
x = new BigNumber('3257869345.0378653')
+BigNumber.maximum(4e9, x, '123456789.9')      // '4000000000'
+
+arr = [12, '13', new BigNumber(14)]
+BigNumber.max(arr)                            // '14'
+ + + +
+ minimum.min([arg1 [, arg2, ...]]) ⇒ BigNumber +
+

+ arg1, arg2, ...: number|string|BigNumber
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the minimum of arg1, + arg2,... . +

+

The argument to this method can also be an array of values.

+

The return value is always exact and unrounded.

+
x = new BigNumber('3257869345.0378653')
+BigNumber.minimum(4e9, x, '123456789.9')      // '123456789.9'
+
+arr = [2, new BigNumber(-14), '-15.9999', -12]
+BigNumber.min(arr)                            // '-15.9999'
+ + + +
+ random.random([dp]) ⇒ BigNumber +
+

dp: number: integer, 0 to 1e+9 inclusive

+

+ Returns a new BigNumber with a pseudo-random value equal to or greater than 0 and + less than 1. +

+

+ The return value will have dp decimal places (or less if trailing zeros are + produced).
+ If dp is omitted then the number of decimal places will default to the current + DECIMAL_PLACES setting. +

+

+ Depending on the value of this BigNumber constructor's + CRYPTO setting and the support for the + crypto object in the host environment, the random digits of the return value are + generated by either Math.random (fastest), crypto.getRandomValues + (Web Cryptography API in recent browsers) or crypto.randomBytes (Node.js). +

+

+ If CRYPTO is true, i.e. one of the + crypto methods is to be used, the value of a returned BigNumber should be + cryptographically-secure and statistically indistinguishable from a random value. +

+

+ Throws if dp is invalid. See Errors. +

+
BigNumber.config({ DECIMAL_PLACES: 10 })
+BigNumber.random()              // '0.4117936847'
+BigNumber.random(20)            // '0.78193327636914089009'
+ + + +

Properties

+

+ The library's enumerated rounding modes are stored as properties of the constructor.
+ (They are not referenced internally by the library itself.) +

+

+ Rounding modes 0 to 6 (inclusive) are the same as those of Java's + BigDecimal class. +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyValueDescription
ROUND_UP0Rounds away from zero
ROUND_DOWN1Rounds towards zero
ROUND_CEIL2Rounds towards Infinity
ROUND_FLOOR3Rounds towards -Infinity
ROUND_HALF_UP4 + Rounds towards nearest neighbour.
+ If equidistant, rounds away from zero +
ROUND_HALF_DOWN5 + Rounds towards nearest neighbour.
+ If equidistant, rounds towards zero +
ROUND_HALF_EVEN6 + Rounds towards nearest neighbour.
+ If equidistant, rounds towards even neighbour +
ROUND_HALF_CEIL7 + Rounds towards nearest neighbour.
+ If equidistant, rounds towards Infinity +
ROUND_HALF_FLOOR8 + Rounds towards nearest neighbour.
+ If equidistant, rounds towards -Infinity +
+
+BigNumber.config({ ROUNDING_MODE: BigNumber.ROUND_CEIL })
+BigNumber.config({ ROUNDING_MODE: 2 })     // equivalent
+ + +

INSTANCE

+ +

Methods

+

The methods inherited by a BigNumber instance from its constructor's prototype object.

+

A BigNumber is immutable in the sense that it is not changed by its methods.

+

+ The treatment of ±0, ±Infinity and NaN is + consistent with how JavaScript treats these values. +

+

Many method names have a shorter alias.

+ + + +
absoluteValue.abs() ⇒ BigNumber
+

+ Returns a BigNumber whose value is the absolute value, i.e. the magnitude, of the value of + this BigNumber. +

+

The return value is always exact and unrounded.

+
+x = new BigNumber(-0.8)
+y = x.absoluteValue()           // '0.8'
+z = y.abs()                     // '0.8'
+ + + +
+ comparedTo.comparedTo(n [, base]) ⇒ number +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+ + + + + + + + + + + + + + + + + + +
Returns 
1If the value of this BigNumber is greater than the value of n
-1If the value of this BigNumber is less than the value of n
0If this BigNumber and n have the same value
nullIf the value of either this BigNumber or n is NaN
+
+x = new BigNumber(Infinity)
+y = new BigNumber(5)
+x.comparedTo(y)                 // 1
+x.comparedTo(x.minus(1))        // 0
+y.comparedTo(NaN)               // null
+y.comparedTo('110', 2)          // -1
+ + + +
+ decimalPlaces.dp([dp [, rm]]) ⇒ BigNumber|number +
+

+ dp: number: integer, 0 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive +

+

+ If dp is a number, returns a BigNumber whose value is the value of this BigNumber + rounded by rounding mode rm to a maximum of dp decimal places. +

+

+ If dp is omitted, or is null or undefined, the return + value is the number of decimal places of the value of this BigNumber, or null if + the value of this BigNumber is ±Infinity or NaN. +

+

+ If rm is omitted, or is null or undefined, + ROUNDING_MODE is used. +

+

+ Throws if dp or rm is invalid. See Errors. +

+
+x = new BigNumber(1234.56)
+x.decimalPlaces(1)                     // '1234.6'
+x.dp()                                 // 2
+x.decimalPlaces(2)                     // '1234.56'
+x.dp(10)                               // '1234.56'
+x.decimalPlaces(0, 1)                  // '1234'
+x.dp(0, 6)                             // '1235'
+x.decimalPlaces(1, 1)                  // '1234.5'
+x.dp(1, BigNumber.ROUND_HALF_EVEN)     // '1234.6'
+x                                      // '1234.56'
+y = new BigNumber('9.9e-101')
+y.dp()                                 // 102
+ + + +
dividedBy.div(n [, base]) ⇒ BigNumber +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the value of this BigNumber divided by + n, rounded according to the current + DECIMAL_PLACES and + ROUNDING_MODE settings. +

+
+x = new BigNumber(355)
+y = new BigNumber(113)
+x.dividedBy(y)                  // '3.14159292035398230088'
+x.div(5)                        // '71'
+x.div(47, 16)                   // '5'
+ + + +
+ dividedToIntegerBy.idiv(n [, base]) ⇒ + BigNumber +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the integer part of dividing the value of this BigNumber by + n. +

+
+x = new BigNumber(5)
+y = new BigNumber(3)
+x.dividedToIntegerBy(y)         // '1'
+x.idiv(0.7)                     // '7'
+x.idiv('0.f', 16)               // '5'
+ + + +
+ exponentiatedBy.pow(n [, m]) ⇒ BigNumber +
+

+ n: number|string|BigNumber: integer
+ m: number|string|BigNumber +

+

+ Returns a BigNumber whose value is the value of this BigNumber exponentiated by + n, i.e. raised to the power n, and optionally modulo a modulus + m. +

+

+ Throws if n is not an integer. See Errors. +

+

+ If n is negative the result is rounded according to the current + DECIMAL_PLACES and + ROUNDING_MODE settings. +

+

+ As the number of digits of the result of the power operation can grow so large so quickly, + e.g. 123.45610000 has over 50000 digits, the number of significant + digits calculated is limited to the value of the + POW_PRECISION setting (unless a modulus + m is specified). +

+

+ By default POW_PRECISION is set to 0. + This means that an unlimited number of significant digits will be calculated, and that the + method's performance will decrease dramatically for larger exponents. +

+

+ If m is specified and the value of m, n and this + BigNumber are integers, and n is positive, then a fast modular exponentiation + algorithm is used, otherwise the operation will be performed as + x.exponentiatedBy(n).modulo(m) with a + POW_PRECISION of 0. +

+
+Math.pow(0.7, 2)                // 0.48999999999999994
+x = new BigNumber(0.7)
+x.exponentiatedBy(2)            // '0.49'
+BigNumber(3).pow(-2)            // '0.11111111111111111111'
+ + + +
+ integerValue.integerValue([rm]) ⇒ BigNumber +
+

+ rm: number: integer, 0 to 8 inclusive +

+

+ Returns a BigNumber whose value is the value of this BigNumber rounded to an integer using + rounding mode rm. +

+

+ If rm is omitted, or is null or undefined, + ROUNDING_MODE is used. +

+

+ Throws if rm is invalid. See Errors. +

+
+x = new BigNumber(123.456)
+x.integerValue()                        // '123'
+x.integerValue(BigNumber.ROUND_CEIL)    // '124'
+y = new BigNumber(-12.7)
+y.integerValue()                        // '-13'
+y.integerValue(BigNumber.ROUND_DOWN)    // '-12'
+

+ The following is an example of how to add a prototype method that emulates JavaScript's + Math.round function. Math.ceil, Math.floor and + Math.trunc can be emulated in the same way with + BigNumber.ROUND_CEIL, BigNumber.ROUND_FLOOR and + BigNumber.ROUND_DOWN respectively. +

+
+BigNumber.prototype.round = function (n) {
+  return n.integerValue(BigNumber.ROUND_HALF_CEIL);
+};
+x.round()                               // '123'
+ + + +
isEqualTo.eq(n [, base]) ⇒ boolean
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns true if the value of this BigNumber is equal to the value of + n, otherwise returns false.
+ As with JavaScript, NaN does not equal NaN. +

+

Note: This method uses the comparedTo method internally.

+
+0 === 1e-324                    // true
+x = new BigNumber(0)
+x.isEqualTo('1e-324')           // false
+BigNumber(-0).eq(x)             // true  ( -0 === 0 )
+BigNumber(255).eq('ff', 16)     // true
+
+y = new BigNumber(NaN)
+y.isEqualTo(NaN)                // false
+ + + +
isFinite.isFinite() ⇒ boolean
+

+ Returns true if the value of this BigNumber is a finite number, otherwise + returns false. +

+

+ The only possible non-finite values of a BigNumber are NaN, Infinity + and -Infinity. +

+
+x = new BigNumber(1)
+x.isFinite()                    // true
+y = new BigNumber(Infinity)
+y.isFinite()                    // false
+

+ Note: The native method isFinite() can be used if + n <= Number.MAX_VALUE. +

+ + + +
isGreaterThan.gt(n [, base]) ⇒ boolean
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns true if the value of this BigNumber is greater than the value of + n, otherwise returns false. +

+

Note: This method uses the comparedTo method internally.

+
+0.1 > (0.3 - 0.2)                             // true
+x = new BigNumber(0.1)
+x.isGreaterThan(BigNumber(0.3).minus(0.2))    // false
+BigNumber(0).gt(x)                            // false
+BigNumber(11, 3).gt(11.1, 2)                  // true
+ + + +
+ isGreaterThanOrEqualTo.gte(n [, base]) ⇒ boolean +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns true if the value of this BigNumber is greater than or equal to the value + of n, otherwise returns false. +

+

Note: This method uses the comparedTo method internally.

+
+(0.3 - 0.2) >= 0.1                     // false
+x = new BigNumber(0.3).minus(0.2)
+x.isGreaterThanOrEqualTo(0.1)          // true
+BigNumber(1).gte(x)                    // true
+BigNumber(10, 18).gte('i', 36)         // true
+ + + +
isInteger.isInteger() ⇒ boolean
+

+ Returns true if the value of this BigNumber is an integer, otherwise returns + false. +

+
+x = new BigNumber(1)
+x.isInteger()                   // true
+y = new BigNumber(123.456)
+y.isInteger()                   // false
+ + + +
isLessThan.lt(n [, base]) ⇒ boolean
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns true if the value of this BigNumber is less than the value of + n, otherwise returns false. +

+

Note: This method uses the comparedTo method internally.

+
+(0.3 - 0.2) < 0.1                       // true
+x = new BigNumber(0.3).minus(0.2)
+x.isLessThan(0.1)                       // false
+BigNumber(0).lt(x)                      // true
+BigNumber(11.1, 2).lt(11, 3)            // true
+ + + +
+ isLessThanOrEqualTo.lte(n [, base]) ⇒ boolean +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns true if the value of this BigNumber is less than or equal to the value of + n, otherwise returns false. +

+

Note: This method uses the comparedTo method internally.

+
+0.1 <= (0.3 - 0.2)                                // false
+x = new BigNumber(0.1)
+x.isLessThanOrEqualTo(BigNumber(0.3).minus(0.2))  // true
+BigNumber(-1).lte(x)                              // true
+BigNumber(10, 18).lte('i', 36)                    // true
+ + + +
isNaN.isNaN() ⇒ boolean
+

+ Returns true if the value of this BigNumber is NaN, otherwise + returns false. +

+
+x = new BigNumber(NaN)
+x.isNaN()                       // true
+y = new BigNumber('Infinity')
+y.isNaN()                       // false
+

Note: The native method isNaN() can also be used.

+ + + +
isNegative.isNegative() ⇒ boolean
+

+ Returns true if the value of this BigNumber is negative, otherwise returns + false. +

+
+x = new BigNumber(-0)
+x.isNegative()                  // true
+y = new BigNumber(2)
+y.isNegative()                  // false
+

Note: n < 0 can be used if n <= -Number.MIN_VALUE.

+ + + +
isPositive.isPositive() ⇒ boolean
+

+ Returns true if the value of this BigNumber is positive, otherwise returns + false. +

+
+x = new BigNumber(-0)
+x.isPositive()                  // false
+y = new BigNumber(2)
+y.isPositive()                  // true
+ + + +
isZero.isZero() ⇒ boolean
+

+ Returns true if the value of this BigNumber is zero or minus zero, otherwise + returns false. +

+
+x = new BigNumber(-0)
+x.isZero() && x.isneg()         // true
+y = new BigNumber(Infinity)
+y.isZero()                      // false
+

Note: n == 0 can be used if n >= Number.MIN_VALUE.

+ + + +
+ minus.minus(n [, base]) ⇒ BigNumber +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

Returns a BigNumber whose value is the value of this BigNumber minus n.

+

The return value is always exact and unrounded.

+
+0.3 - 0.1                       // 0.19999999999999998
+x = new BigNumber(0.3)
+x.minus(0.1)                    // '0.2'
+x.minus(0.6, 20)                // '0'
+ + + +
modulo.mod(n [, base]) ⇒ BigNumber
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the value of this BigNumber modulo n, i.e. + the integer remainder of dividing this BigNumber by n. +

+

+ The value returned, and in particular its sign, is dependent on the value of the + MODULO_MODE setting of this BigNumber constructor. + If it is 1 (default value), the result will have the same sign as this BigNumber, + and it will match that of Javascript's % operator (within the limits of double + precision) and BigDecimal's remainder method. +

+

The return value is always exact and unrounded.

+

+ See MODULO_MODE for a description of the other + modulo modes. +

+
+1 % 0.9                         // 0.09999999999999998
+x = new BigNumber(1)
+x.modulo(0.9)                   // '0.1'
+y = new BigNumber(33)
+y.mod('a', 33)                  // '3'
+ + + +
+ multipliedBy.times(n [, base]) ⇒ BigNumber +
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

+ Returns a BigNumber whose value is the value of this BigNumber multiplied by n. +

+

The return value is always exact and unrounded.

+
+0.6 * 3                         // 1.7999999999999998
+x = new BigNumber(0.6)
+y = x.multipliedBy(3)           // '1.8'
+BigNumber('7e+500').times(y)    // '1.26e+501'
+x.multipliedBy('-a', 16)        // '-6'
+ + + +
negated.negated() ⇒ BigNumber
+

+ Returns a BigNumber whose value is the value of this BigNumber negated, i.e. multiplied by + -1. +

+
+x = new BigNumber(1.8)
+x.negated()                     // '-1.8'
+y = new BigNumber(-1.3)
+y.negated()                     // '1.3'
+ + + +
plus.plus(n [, base]) ⇒ BigNumber
+

+ n: number|string|BigNumber
+ base: number
+ See BigNumber for further parameter details. +

+

Returns a BigNumber whose value is the value of this BigNumber plus n.

+

The return value is always exact and unrounded.

+
+0.1 + 0.2                       // 0.30000000000000004
+x = new BigNumber(0.1)
+y = x.plus(0.2)                 // '0.3'
+BigNumber(0.7).plus(x).plus(y)  // '1'
+x.plus('0.1', 8)                // '0.225'
+ + + +
+ precision.sd([d [, rm]]) ⇒ BigNumber|number +
+

+ d: number|boolean: integer, 1 to 1e+9 + inclusive, or true or false
+ rm: number: integer, 0 to 8 inclusive. +

+

+ If d is a number, returns a BigNumber whose value is the value of this BigNumber + rounded to a precision of d significant digits using rounding mode + rm. +

+

+ If d is omitted or is null or undefined, the return + value is the number of significant digits of the value of this BigNumber, or null + if the value of this BigNumber is ±Infinity or NaN.

+

+

+ If d is true then any trailing zeros of the integer + part of a number are counted as significant digits, otherwise they are not. +

+

+ If rm is omitted or is null or undefined, + ROUNDING_MODE will be used. +

+

+ Throws if d or rm is invalid. See Errors. +

+
+x = new BigNumber(9876.54321)
+x.precision(6)                         // '9876.54'
+x.sd()                                 // 9
+x.precision(6, BigNumber.ROUND_UP)     // '9876.55'
+x.sd(2)                                // '9900'
+x.precision(2, 1)                      // '9800'
+x                                      // '9876.54321'
+y = new BigNumber(987000)
+y.precision()                          // 3
+y.sd(true)                             // 6
+ + + +
shiftedBy.shiftedBy(n) ⇒ BigNumber
+

+ n: number: integer, + -9007199254740991 to 9007199254740991 inclusive +

+

+ Returns a BigNumber whose value is the value of this BigNumber shifted by n + places. +

+ The shift is of the decimal point, i.e. of powers of ten, and is to the left if n + is negative or to the right if n is positive. +

+

The return value is always exact and unrounded.

+

+ Throws if n is invalid. See Errors. +

+
+x = new BigNumber(1.23)
+x.shiftedBy(3)                      // '1230'
+x.shiftedBy(-3)                     // '0.00123'
+ + + +
squareRoot.sqrt() ⇒ BigNumber
+

+ Returns a BigNumber whose value is the square root of the value of this BigNumber, + rounded according to the current + DECIMAL_PLACES and + ROUNDING_MODE settings. +

+

+ The return value will be correctly rounded, i.e. rounded as if the result was first calculated + to an infinite number of correct digits before rounding. +

+
+x = new BigNumber(16)
+x.squareRoot()                  // '4'
+y = new BigNumber(3)
+y.sqrt()                        // '1.73205080756887729353'
+ + + +
+ toExponential.toExponential([dp [, rm]]) ⇒ string +
+

+ dp: number: integer, 0 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive +

+

+ Returns a string representing the value of this BigNumber in exponential notation rounded + using rounding mode rm to dp decimal places, i.e with one digit + before the decimal point and dp digits after it. +

+

+ If the value of this BigNumber in exponential notation has fewer than dp fraction + digits, the return value will be appended with zeros accordingly. +

+

+ If dp is omitted, or is null or undefined, the number + of digits after the decimal point defaults to the minimum number of digits necessary to + represent the value exactly.
+ If rm is omitted or is null or undefined, + ROUNDING_MODE is used. +

+

+ Throws if dp or rm is invalid. See Errors. +

+
+x = 45.6
+y = new BigNumber(x)
+x.toExponential()               // '4.56e+1'
+y.toExponential()               // '4.56e+1'
+x.toExponential(0)              // '5e+1'
+y.toExponential(0)              // '5e+1'
+x.toExponential(1)              // '4.6e+1'
+y.toExponential(1)              // '4.6e+1'
+y.toExponential(1, 1)           // '4.5e+1'  (ROUND_DOWN)
+x.toExponential(3)              // '4.560e+1'
+y.toExponential(3)              // '4.560e+1'
+ + + +
+ toFixed.toFixed([dp [, rm]]) ⇒ string +
+

+ dp: number: integer, 0 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive +

+

+ Returns a string representing the value of this BigNumber in normal (fixed-point) notation + rounded to dp decimal places using rounding mode rm. +

+

+ If the value of this BigNumber in normal notation has fewer than dp fraction + digits, the return value will be appended with zeros accordingly. +

+

+ Unlike Number.prototype.toFixed, which returns exponential notation if a number + is greater or equal to 1021, this method will always return normal + notation. +

+

+ If dp is omitted or is null or undefined, the return + value will be unrounded and in normal notation. This is also unlike + Number.prototype.toFixed, which returns the value to zero decimal places.
+ It is useful when fixed-point notation is required and the current + EXPONENTIAL_AT setting causes + toString to return exponential notation.
+ If rm is omitted or is null or undefined, + ROUNDING_MODE is used. +

+

+ Throws if dp or rm is invalid. See Errors. +

+
+x = 3.456
+y = new BigNumber(x)
+x.toFixed()                     // '3'
+y.toFixed()                     // '3.456'
+y.toFixed(0)                    // '3'
+x.toFixed(2)                    // '3.46'
+y.toFixed(2)                    // '3.46'
+y.toFixed(2, 1)                 // '3.45'  (ROUND_DOWN)
+x.toFixed(5)                    // '3.45600'
+y.toFixed(5)                    // '3.45600'
+ + + +
+ toFormat.toFormat([dp [, rm]]) ⇒ string +
+

+ dp: number: integer, 0 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive +

+

+

+ Returns a string representing the value of this BigNumber in normal (fixed-point) notation + rounded to dp decimal places using rounding mode rm, and formatted + according to the properties of the FORMAT object. +

+

+ See the examples below for the properties of the + FORMAT object, their types and their usage. +

+

+ If dp is omitted or is null or undefined, then the + return value is not rounded to a fixed number of decimal places.
+ If rm is omitted or is null or undefined, + ROUNDING_MODE is used. +

+

+ Throws if dp or rm is invalid. See Errors. +

+
+format = {
+    decimalSeparator: '.',
+    groupSeparator: ',',
+    groupSize: 3,
+    secondaryGroupSize: 0,
+    fractionGroupSeparator: ' ',
+    fractionGroupSize: 0
+}
+BigNumber.config({ FORMAT: format })
+
+x = new BigNumber('123456789.123456789')
+x.toFormat()                    // '123,456,789.123456789'
+x.toFormat(1)                   // '123,456,789.1'
+
+// If a reference to the object assigned to FORMAT has been retained,
+// the format properties can be changed directly
+format.groupSeparator = ' '
+format.fractionGroupSize = 5
+x.toFormat()                    // '123 456 789.12345 6789'
+
+BigNumber.config({
+    FORMAT: {
+        decimalSeparator: ',',
+        groupSeparator: '.',
+        groupSize: 3,
+        secondaryGroupSize: 2
+    }
+})
+
+x.toFormat(6)                   // '12.34.56.789,123'
+ + + +
+ toFraction.toFraction([max]) ⇒ [string, string] +
+

+ max: number|string|BigNumber: integer >= 1 and <= + Infinity +

+

+ Returns a string array representing the value of this BigNumber as a simple fraction with an + integer numerator and an integer denominator. The denominator will be a positive non-zero + value less than or equal to max. +

+

+ If a maximum denominator, max, is not specified, or is null or + undefined, the denominator will be the lowest value necessary to represent the + number exactly. +

+

+ Throws if max is invalid. See Errors. +

+
+x = new BigNumber(1.75)
+x.toFraction()                  // '7, 4'
+
+pi = new BigNumber('3.14159265358')
+pi.toFraction()                 // '157079632679,50000000000'
+pi.toFraction(100000)           // '312689, 99532'
+pi.toFraction(10000)            // '355, 113'
+pi.toFraction(100)              // '311, 99'
+pi.toFraction(10)               // '22, 7'
+pi.toFraction(1)                // '3, 1'
+ + + +
toJSON.toJSON() ⇒ string
+

As valueOf.

+
+x = new BigNumber('177.7e+457')
+y = new BigNumber(235.4325)
+z = new BigNumber('0.0098074')
+
+// Serialize an array of three BigNumbers
+str = JSON.stringify( [x, y, z] )
+// "["1.777e+459","235.4325","0.0098074"]"
+
+// Return an array of three BigNumbers
+JSON.parse(str, function (key, val) {
+    return key === '' ? val : new BigNumber(val)
+})
+ + + +
toNumber.toNumber() ⇒ number
+

Returns the value of this BigNumber as a JavaScript number primitive.

+

+ This method is identical to using type coercion with the unary plus operator. +

+
+x = new BigNumber(456.789)
+x.toNumber()                    // 456.789
++x                              // 456.789
+
+y = new BigNumber('45987349857634085409857349856430985')
+y.toNumber()                    // 4.598734985763409e+34
+
+z = new BigNumber(-0)
+1 / z.toNumber()                // -Infinity
+1 / +z                          // -Infinity
+ + + +
+ toPrecision.toPrecision([sd [, rm]]) ⇒ string +
+

+ sd: number: integer, 1 to 1e+9 inclusive
+ rm: number: integer, 0 to 8 inclusive +

+

+ Returns a string representing the value of this BigNumber rounded to sd + significant digits using rounding mode rm. +

+

+ If sd is less than the number of digits necessary to represent the integer part + of the value in normal (fixed-point) notation, then exponential notation is used. +

+

+ If sd is omitted, or is null or undefined, then the + return value is the same as n.toString().
+ If rm is omitted or is null or undefined, + ROUNDING_MODE is used. +

+

+ Throws if sd or rm is invalid. See Errors. +

+
+x = 45.6
+y = new BigNumber(x)
+x.toPrecision()                 // '45.6'
+y.toPrecision()                 // '45.6'
+x.toPrecision(1)                // '5e+1'
+y.toPrecision(1)                // '5e+1'
+y.toPrecision(2, 0)             // '4.6e+1'  (ROUND_UP)
+y.toPrecision(2, 1)             // '4.5e+1'  (ROUND_DOWN)
+x.toPrecision(5)                // '45.600'
+y.toPrecision(5)                // '45.600'
+ + + +
toString.toString([base]) ⇒ string
+

+ base: number: integer, 2 to ALPHABET.length + inclusive (see ALPHABET). +

+

+ Returns a string representing the value of this BigNumber in the specified base, or base + 10 if base is omitted or is null or + undefined. +

+

+ For bases above 10, and using the default base conversion alphabet + (see ALPHABET), values from 10 to + 35 are represented by a-z + (as with Number.prototype.toString). +

+

+ If a base is specified the value is rounded according to the current + DECIMAL_PLACES + and ROUNDING_MODE settings. +

+

+ If a base is not specified, and this BigNumber has a positive + exponent that is equal to or greater than the positive component of the + current EXPONENTIAL_AT setting, + or a negative exponent equal to or less than the negative component of the + setting, then exponential notation is returned. +

+

If base is null or undefined it is ignored.

+

+ Throws if base is invalid. See Errors. +

+
+x = new BigNumber(750000)
+x.toString()                    // '750000'
+BigNumber.config({ EXPONENTIAL_AT: 5 })
+x.toString()                    // '7.5e+5'
+
+y = new BigNumber(362.875)
+y.toString(2)                   // '101101010.111'
+y.toString(9)                   // '442.77777777777777777778'
+y.toString(32)                  // 'ba.s'
+
+BigNumber.config({ DECIMAL_PLACES: 4 });
+z = new BigNumber('1.23456789')
+z.toString()                    // '1.23456789'
+z.toString(10)                  // '1.2346'
+ + + +
valueOf.valueOf() ⇒ string
+

+ As toString, but does not accept a base argument and includes the minus sign + for negative zero. +

+
+x = new BigNumber('-0')
+x.toString()                    // '0'
+x.valueOf()                     // '-0'
+y = new BigNumber('1.777e+457')
+y.valueOf()                     // '1.777e+457'
+ + + +

Properties

+

The properties of a BigNumber instance:

+ + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyDescriptionTypeValue
ccoefficient*number[] Array of base 1e14 numbers
eexponentnumberInteger, -1000000000 to 1000000000 inclusive
ssignnumber-1 or 1
+

*significand

+

+ The value of any of the c, e and s properties may also + be null. +

+

+ The above properties are best considered to be read-only. In early versions of this library it + was okay to change the exponent of a BigNumber by writing to its exponent property directly, + but this is no longer reliable as the value of the first element of the coefficient array is + now dependent on the exponent. +

+

+ Note that, as with JavaScript numbers, the original exponent and fractional trailing zeros are + not necessarily preserved. +

+
x = new BigNumber(0.123)              // '0.123'
+x.toExponential()                     // '1.23e-1'
+x.c                                   // '1,2,3'
+x.e                                   // -1
+x.s                                   // 1
+
+y = new Number(-123.4567000e+2)       // '-12345.67'
+y.toExponential()                     // '-1.234567e+4'
+z = new BigNumber('-123.4567000e+2')  // '-12345.67'
+z.toExponential()                     // '-1.234567e+4'
+z.c                                   // '1,2,3,4,5,6,7'
+z.e                                   // 4
+z.s                                   // -1
+ + + +

Zero, NaN and Infinity

+

+ The table below shows how ±0, NaN and + ±Infinity are stored. +

+ + + + + + + + + + + + + + + + + + + + + + + + + +
ces
±0[0]0±1
NaNnullnullnull
±Infinitynullnull±1
+
+x = new Number(-0)              // 0
+1 / x == -Infinity              // true
+
+y = new BigNumber(-0)           // '0'
+y.c                             // '0' ( [0].toString() )
+y.e                             // 0
+y.s                             // -1
+ + + +

Errors

+

The table below shows the errors that are thrown.

+

+ The errors are generic Error objects whose message begins + '[BigNumber Error]'. +

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
MethodThrows
+ BigNumber
+ comparedTo
+ dividedBy
+ dividedToIntegerBy
+ isEqualTo
+ isGreaterThan
+ isGreaterThanOrEqualTo
+ isLessThan
+ isLessThanOrEqualTo
+ minus
+ modulo
+ plus
+ multipliedBy +
Base not a primitive number
Base not an integer
Base out of range
Number primitive has more than 15 significant digits*
Not a base... number*
Not a number*
cloneObject expected
configObject expected
DECIMAL_PLACES not a primitive number
DECIMAL_PLACES not an integer
DECIMAL_PLACES out of range
ROUNDING_MODE not a primitive number
ROUNDING_MODE not an integer
ROUNDING_MODE out of range
EXPONENTIAL_AT not a primitive number
EXPONENTIAL_AT not an integer
EXPONENTIAL_AT out of range
RANGE not a primitive number
RANGE not an integer
RANGE cannot be zero
RANGE cannot be zero
CRYPTO not true or false
crypto unavailable
MODULO_MODE not a primitive number
MODULO_MODE not an integer
MODULO_MODE out of range
POW_PRECISION not a primitive number
POW_PRECISION not an integer
POW_PRECISION out of range
FORMAT not an object
ALPHABET invalid
+ decimalPlaces
+ precision
+ random
+ shiftedBy
+ toExponential
+ toFixed
+ toFormat
+ toPrecision +
Argument not a primitive number
Argument not an integer
Argument out of range
+ decimalPlaces
+ precision +
Argument not true or false
exponentiatedByArgument not an integer
+ minimum
+ maximum +
Not a number*
+ random + crypto unavailable
toFractionArgument not an integer
Argument out of range
toStringBase not a primitive number
Base not an integer
Base out of range
+

*Only thrown if BigNumber.DEBUG is true.

+

To determine if an exception is a BigNumber Error:

+
+try {
+    // ...
+} catch (e) {
+    if (e instanceof Error && e.message.indexOf('[BigNumber Error]') === 0) {
+        // ...
+    }
+}
+ + + +

FAQ

+ +
Why are trailing fractional zeros removed from BigNumbers?
+

+ Some arbitrary-precision libraries retain trailing fractional zeros as they can indicate the + precision of a value. This can be useful but the results of arithmetic operations can be + misleading. +

+
+x = new BigDecimal("1.0")
+y = new BigDecimal("1.1000")
+z = x.add(y)                      // 2.1000
+
+x = new BigDecimal("1.20")
+y = new BigDecimal("3.45000")
+z = x.multiply(y)                 // 4.1400000
+

+ To specify the precision of a value is to specify that the value lies + within a certain range. +

+

+ In the first example, x has a value of 1.0. The trailing zero shows + the precision of the value, implying that it is in the range 0.95 to + 1.05. Similarly, the precision indicated by the trailing zeros of y + indicates that the value is in the range 1.09995 to 1.10005. +

+

+ If we add the two lowest values in the ranges we have, 0.95 + 1.09995 = 2.04995, + and if we add the two highest values we have, 1.05 + 1.10005 = 2.15005, so the + range of the result of the addition implied by the precision of its operands is + 2.04995 to 2.15005. +

+

+ The result given by BigDecimal of 2.1000 however, indicates that the value is in + the range 2.09995 to 2.10005 and therefore the precision implied by + its trailing zeros may be misleading. +

+

+ In the second example, the true range is 4.122744 to 4.157256 yet + the BigDecimal answer of 4.1400000 indicates a range of 4.13999995 + to 4.14000005. Again, the precision implied by the trailing zeros may be + misleading. +

+

+ This library, like binary floating point and most calculators, does not retain trailing + fractional zeros. Instead, the toExponential, toFixed and + toPrecision methods enable trailing zeros to be added if and when required.
+

+
+ + + diff --git a/node_modules/bignumber.js/package.json b/node_modules/bignumber.js/package.json new file mode 100644 index 0000000..760db59 --- /dev/null +++ b/node_modules/bignumber.js/package.json @@ -0,0 +1,68 @@ +{ + "_from": "bignumber.js@^7.0.0", + "_id": "bignumber.js@7.2.1", + "_inBundle": false, + "_integrity": "sha512-S4XzBk5sMB+Rcb/LNcpzXr57VRTxgAvaAEDAl1AwRx27j00hT84O6OkteE7u8UB3NuaaygCRrEpqox4uDOrbdQ==", + "_location": "/bignumber.js", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "bignumber.js@^7.0.0", + "name": "bignumber.js", + "escapedName": "bignumber.js", + "rawSpec": "^7.0.0", + "saveSpec": null, + "fetchSpec": "^7.0.0" + }, + "_requiredBy": [ + "/json-bigint" + ], + "_resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-7.2.1.tgz", + "_shasum": "80c048759d826800807c4bfd521e50edbba57a5f", + "_spec": "bignumber.js@^7.0.0", + "_where": "/Users/cday/Code/zendesk/fetch-build-from-gcb/node_modules/json-bigint", + "author": { + "name": "Michael Mclaughlin", + "email": "M8ch88l@gmail.com" + }, + "browser": "bignumber.js", + "bugs": { + "url": "https://github.com/MikeMcl/bignumber.js/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "A library for arbitrary-precision decimal and non-decimal arithmetic", + "engines": { + "node": "*" + }, + "homepage": "https://github.com/MikeMcl/bignumber.js#readme", + "keywords": [ + "arbitrary", + "precision", + "arithmetic", + "big", + "number", + "decimal", + "float", + "biginteger", + "bigdecimal", + "bignumber", + "bigint", + "bignum" + ], + "license": "MIT", + "main": "bignumber", + "module": "bignumber.mjs", + "name": "bignumber.js", + "repository": { + "type": "git", + "url": "git+https://github.com/MikeMcl/bignumber.js.git" + }, + "scripts": { + "build": "uglifyjs bignumber.js --source-map bignumber.js.map -c -m -o bignumber.min.js --preamble \"/* bignumber.js v7.2.1 https://github.com/MikeMcl/bignumber.js/LICENCE */\"", + "test": "node test/test" + }, + "types": "bignumber.d.ts", + "version": "7.2.1" +} diff --git a/node_modules/buffer-equal-constant-time/.npmignore b/node_modules/buffer-equal-constant-time/.npmignore new file mode 100644 index 0000000..34e4f5c --- /dev/null +++ b/node_modules/buffer-equal-constant-time/.npmignore @@ -0,0 +1,2 @@ +.*.sw[mnop] +node_modules/ diff --git a/node_modules/buffer-equal-constant-time/.travis.yml b/node_modules/buffer-equal-constant-time/.travis.yml new file mode 100644 index 0000000..78e1c01 --- /dev/null +++ b/node_modules/buffer-equal-constant-time/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: +- "0.11" +- "0.10" diff --git a/node_modules/buffer-equal-constant-time/LICENSE.txt b/node_modules/buffer-equal-constant-time/LICENSE.txt new file mode 100644 index 0000000..9a064f3 --- /dev/null +++ b/node_modules/buffer-equal-constant-time/LICENSE.txt @@ -0,0 +1,12 @@ +Copyright (c) 2013, GoInstant Inc., a salesforce.com company +All rights reserved. + +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +* Neither the name of salesforce.com, nor GoInstant, nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/buffer-equal-constant-time/README.md b/node_modules/buffer-equal-constant-time/README.md new file mode 100644 index 0000000..4f227f5 --- /dev/null +++ b/node_modules/buffer-equal-constant-time/README.md @@ -0,0 +1,50 @@ +# buffer-equal-constant-time + +Constant-time `Buffer` comparison for node.js. Should work with browserify too. + +[![Build Status](https://travis-ci.org/goinstant/buffer-equal-constant-time.png?branch=master)](https://travis-ci.org/goinstant/buffer-equal-constant-time) + +```sh + npm install buffer-equal-constant-time +``` + +# Usage + +```js + var bufferEq = require('buffer-equal-constant-time'); + + var a = new Buffer('asdf'); + var b = new Buffer('asdf'); + if (bufferEq(a,b)) { + // the same! + } else { + // different in at least one byte! + } +``` + +If you'd like to install an `.equal()` method onto the node.js `Buffer` and +`SlowBuffer` prototypes: + +```js + require('buffer-equal-constant-time').install(); + + var a = new Buffer('asdf'); + var b = new Buffer('asdf'); + if (a.equal(b)) { + // the same! + } else { + // different in at least one byte! + } +``` + +To get rid of the installed `.equal()` method, call `.restore()`: + +```js + require('buffer-equal-constant-time').restore(); +``` + +# Legal + +© 2013 GoInstant Inc., a salesforce.com company + +Licensed under the BSD 3-clause license. diff --git a/node_modules/buffer-equal-constant-time/index.js b/node_modules/buffer-equal-constant-time/index.js new file mode 100644 index 0000000..5462c1f --- /dev/null +++ b/node_modules/buffer-equal-constant-time/index.js @@ -0,0 +1,41 @@ +/*jshint node:true */ +'use strict'; +var Buffer = require('buffer').Buffer; // browserify +var SlowBuffer = require('buffer').SlowBuffer; + +module.exports = bufferEq; + +function bufferEq(a, b) { + + // shortcutting on type is necessary for correctness + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + return false; + } + + // buffer sizes should be well-known information, so despite this + // shortcutting, it doesn't leak any information about the *contents* of the + // buffers. + if (a.length !== b.length) { + return false; + } + + var c = 0; + for (var i = 0; i < a.length; i++) { + /*jshint bitwise:false */ + c |= a[i] ^ b[i]; // XOR + } + return c === 0; +} + +bufferEq.install = function() { + Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) { + return bufferEq(this, that); + }; +}; + +var origBufEqual = Buffer.prototype.equal; +var origSlowBufEqual = SlowBuffer.prototype.equal; +bufferEq.restore = function() { + Buffer.prototype.equal = origBufEqual; + SlowBuffer.prototype.equal = origSlowBufEqual; +}; diff --git a/node_modules/buffer-equal-constant-time/package.json b/node_modules/buffer-equal-constant-time/package.json new file mode 100644 index 0000000..8d0fcd7 --- /dev/null +++ b/node_modules/buffer-equal-constant-time/package.json @@ -0,0 +1,55 @@ +{ + "_from": "buffer-equal-constant-time@1.0.1", + "_id": "buffer-equal-constant-time@1.0.1", + "_inBundle": false, + "_integrity": "sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk=", + "_location": "/buffer-equal-constant-time", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "buffer-equal-constant-time@1.0.1", + "name": "buffer-equal-constant-time", + "escapedName": "buffer-equal-constant-time", + "rawSpec": "1.0.1", + "saveSpec": null, + "fetchSpec": "1.0.1" + }, + "_requiredBy": [ + "/jwa" + ], + "_resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "_shasum": "f8e71132f7ffe6e01a5c9697a4c6f3e48d5cc819", + "_spec": "buffer-equal-constant-time@1.0.1", + "_where": "/Users/cday/Code/zendesk/fetch-build-from-gcb/node_modules/jwa", + "author": { + "name": "GoInstant Inc., a salesforce.com company" + }, + "bugs": { + "url": "https://github.com/goinstant/buffer-equal-constant-time/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Constant-time comparison of Buffers", + "devDependencies": { + "mocha": "~1.15.1" + }, + "homepage": "https://github.com/goinstant/buffer-equal-constant-time#readme", + "keywords": [ + "buffer", + "equal", + "constant-time", + "crypto" + ], + "license": "BSD-3-Clause", + "main": "index.js", + "name": "buffer-equal-constant-time", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/goinstant/buffer-equal-constant-time.git" + }, + "scripts": { + "test": "mocha test.js" + }, + "version": "1.0.1" +} diff --git a/node_modules/buffer-equal-constant-time/test.js b/node_modules/buffer-equal-constant-time/test.js new file mode 100644 index 0000000..0bc972d --- /dev/null +++ b/node_modules/buffer-equal-constant-time/test.js @@ -0,0 +1,42 @@ +/*jshint node:true */ +'use strict'; + +var bufferEq = require('./index'); +var assert = require('assert'); + +describe('buffer-equal-constant-time', function() { + var a = new Buffer('asdfasdf123456'); + var b = new Buffer('asdfasdf123456'); + var c = new Buffer('asdfasdf'); + + describe('bufferEq', function() { + it('says a == b', function() { + assert.strictEqual(bufferEq(a, b), true); + }); + + it('says a != c', function() { + assert.strictEqual(bufferEq(a, c), false); + }); + }); + + describe('install/restore', function() { + before(function() { + bufferEq.install(); + }); + after(function() { + bufferEq.restore(); + }); + + it('installed an .equal method', function() { + var SlowBuffer = require('buffer').SlowBuffer; + assert.ok(Buffer.prototype.equal); + assert.ok(SlowBuffer.prototype.equal); + }); + + it('infected existing Buffers', function() { + assert.strictEqual(a.equal(b), true); + assert.strictEqual(a.equal(c), false); + }); + }); + +}); diff --git a/node_modules/debug/CHANGELOG.md b/node_modules/debug/CHANGELOG.md new file mode 100644 index 0000000..820d21e --- /dev/null +++ b/node_modules/debug/CHANGELOG.md @@ -0,0 +1,395 @@ + +3.1.0 / 2017-09-26 +================== + + * Add `DEBUG_HIDE_DATE` env var (#486) + * Remove ReDoS regexp in %o formatter (#504) + * Remove "component" from package.json + * Remove `component.json` + * Ignore package-lock.json + * Examples: fix colors printout + * Fix: browser detection + * Fix: spelling mistake (#496, @EdwardBetts) + +3.0.1 / 2017-08-24 +================== + + * Fix: Disable colors in Edge and Internet Explorer (#489) + +3.0.0 / 2017-08-08 +================== + + * Breaking: Remove DEBUG_FD (#406) + * Breaking: Use `Date#toISOString()` instead to `Date#toUTCString()` when output is not a TTY (#418) + * Breaking: Make millisecond timer namespace specific and allow 'always enabled' output (#408) + * Addition: document `enabled` flag (#465) + * Addition: add 256 colors mode (#481) + * Addition: `enabled()` updates existing debug instances, add `destroy()` function (#440) + * Update: component: update "ms" to v2.0.0 + * Update: separate the Node and Browser tests in Travis-CI + * Update: refactor Readme, fixed documentation, added "Namespace Colors" section, redid screenshots + * Update: separate Node.js and web browser examples for organization + * Update: update "browserify" to v14.4.0 + * Fix: fix Readme typo (#473) + +2.6.9 / 2017-09-22 +================== + + * remove ReDoS regexp in %o formatter (#504) + +2.6.8 / 2017-05-18 +================== + + * Fix: Check for undefined on browser globals (#462, @marbemac) + +2.6.7 / 2017-05-16 +================== + + * Fix: Update ms to 2.0.0 to fix regular expression denial of service vulnerability (#458, @hubdotcom) + * Fix: Inline extend function in node implementation (#452, @dougwilson) + * Docs: Fix typo (#455, @msasad) + +2.6.5 / 2017-04-27 +================== + + * Fix: null reference check on window.documentElement.style.WebkitAppearance (#447, @thebigredgeek) + * Misc: clean up browser reference checks (#447, @thebigredgeek) + * Misc: add npm-debug.log to .gitignore (@thebigredgeek) + + +2.6.4 / 2017-04-20 +================== + + * Fix: bug that would occur if process.env.DEBUG is a non-string value. (#444, @LucianBuzzo) + * Chore: ignore bower.json in npm installations. (#437, @joaovieira) + * Misc: update "ms" to v0.7.3 (@tootallnate) + +2.6.3 / 2017-03-13 +================== + + * Fix: Electron reference to `process.env.DEBUG` (#431, @paulcbetts) + * Docs: Changelog fix (@thebigredgeek) + +2.6.2 / 2017-03-10 +================== + + * Fix: DEBUG_MAX_ARRAY_LENGTH (#420, @slavaGanzin) + * Docs: Add backers and sponsors from Open Collective (#422, @piamancini) + * Docs: Add Slackin invite badge (@tootallnate) + +2.6.1 / 2017-02-10 +================== + + * Fix: Module's `export default` syntax fix for IE8 `Expected identifier` error + * Fix: Whitelist DEBUG_FD for values 1 and 2 only (#415, @pi0) + * Fix: IE8 "Expected identifier" error (#414, @vgoma) + * Fix: Namespaces would not disable once enabled (#409, @musikov) + +2.6.0 / 2016-12-28 +================== + + * Fix: added better null pointer checks for browser useColors (@thebigredgeek) + * Improvement: removed explicit `window.debug` export (#404, @tootallnate) + * Improvement: deprecated `DEBUG_FD` environment variable (#405, @tootallnate) + +2.5.2 / 2016-12-25 +================== + + * Fix: reference error on window within webworkers (#393, @KlausTrainer) + * Docs: fixed README typo (#391, @lurch) + * Docs: added notice about v3 api discussion (@thebigredgeek) + +2.5.1 / 2016-12-20 +================== + + * Fix: babel-core compatibility + +2.5.0 / 2016-12-20 +================== + + * Fix: wrong reference in bower file (@thebigredgeek) + * Fix: webworker compatibility (@thebigredgeek) + * Fix: output formatting issue (#388, @kribblo) + * Fix: babel-loader compatibility (#383, @escwald) + * Misc: removed built asset from repo and publications (@thebigredgeek) + * Misc: moved source files to /src (#378, @yamikuronue) + * Test: added karma integration and replaced babel with browserify for browser tests (#378, @yamikuronue) + * Test: coveralls integration (#378, @yamikuronue) + * Docs: simplified language in the opening paragraph (#373, @yamikuronue) + +2.4.5 / 2016-12-17 +================== + + * Fix: `navigator` undefined in Rhino (#376, @jochenberger) + * Fix: custom log function (#379, @hsiliev) + * Improvement: bit of cleanup + linting fixes (@thebigredgeek) + * Improvement: rm non-maintainted `dist/` dir (#375, @freewil) + * Docs: simplified language in the opening paragraph. (#373, @yamikuronue) + +2.4.4 / 2016-12-14 +================== + + * Fix: work around debug being loaded in preload scripts for electron (#368, @paulcbetts) + +2.4.3 / 2016-12-14 +================== + + * Fix: navigation.userAgent error for react native (#364, @escwald) + +2.4.2 / 2016-12-14 +================== + + * Fix: browser colors (#367, @tootallnate) + * Misc: travis ci integration (@thebigredgeek) + * Misc: added linting and testing boilerplate with sanity check (@thebigredgeek) + +2.4.1 / 2016-12-13 +================== + + * Fix: typo that broke the package (#356) + +2.4.0 / 2016-12-13 +================== + + * Fix: bower.json references unbuilt src entry point (#342, @justmatt) + * Fix: revert "handle regex special characters" (@tootallnate) + * Feature: configurable util.inspect()`options for NodeJS (#327, @tootallnate) + * Feature: %O`(big O) pretty-prints objects (#322, @tootallnate) + * Improvement: allow colors in workers (#335, @botverse) + * Improvement: use same color for same namespace. (#338, @lchenay) + +2.3.3 / 2016-11-09 +================== + + * Fix: Catch `JSON.stringify()` errors (#195, Jovan Alleyne) + * Fix: Returning `localStorage` saved values (#331, Levi Thomason) + * Improvement: Don't create an empty object when no `process` (Nathan Rajlich) + +2.3.2 / 2016-11-09 +================== + + * Fix: be super-safe in index.js as well (@TooTallNate) + * Fix: should check whether process exists (Tom Newby) + +2.3.1 / 2016-11-09 +================== + + * Fix: Added electron compatibility (#324, @paulcbetts) + * Improvement: Added performance optimizations (@tootallnate) + * Readme: Corrected PowerShell environment variable example (#252, @gimre) + * Misc: Removed yarn lock file from source control (#321, @fengmk2) + +2.3.0 / 2016-11-07 +================== + + * Fix: Consistent placement of ms diff at end of output (#215, @gorangajic) + * Fix: Escaping of regex special characters in namespace strings (#250, @zacronos) + * Fix: Fixed bug causing crash on react-native (#282, @vkarpov15) + * Feature: Enabled ES6+ compatible import via default export (#212 @bucaran) + * Feature: Added %O formatter to reflect Chrome's console.log capability (#279, @oncletom) + * Package: Update "ms" to 0.7.2 (#315, @DevSide) + * Package: removed superfluous version property from bower.json (#207 @kkirsche) + * Readme: fix USE_COLORS to DEBUG_COLORS + * Readme: Doc fixes for format string sugar (#269, @mlucool) + * Readme: Updated docs for DEBUG_FD and DEBUG_COLORS environment variables (#232, @mattlyons0) + * Readme: doc fixes for PowerShell (#271 #243, @exoticknight @unreadable) + * Readme: better docs for browser support (#224, @matthewmueller) + * Tooling: Added yarn integration for development (#317, @thebigredgeek) + * Misc: Renamed History.md to CHANGELOG.md (@thebigredgeek) + * Misc: Added license file (#226 #274, @CantemoInternal @sdaitzman) + * Misc: Updated contributors (@thebigredgeek) + +2.2.0 / 2015-05-09 +================== + + * package: update "ms" to v0.7.1 (#202, @dougwilson) + * README: add logging to file example (#193, @DanielOchoa) + * README: fixed a typo (#191, @amir-s) + * browser: expose `storage` (#190, @stephenmathieson) + * Makefile: add a `distclean` target (#189, @stephenmathieson) + +2.1.3 / 2015-03-13 +================== + + * Updated stdout/stderr example (#186) + * Updated example/stdout.js to match debug current behaviour + * Renamed example/stderr.js to stdout.js + * Update Readme.md (#184) + * replace high intensity foreground color for bold (#182, #183) + +2.1.2 / 2015-03-01 +================== + + * dist: recompile + * update "ms" to v0.7.0 + * package: update "browserify" to v9.0.3 + * component: fix "ms.js" repo location + * changed bower package name + * updated documentation about using debug in a browser + * fix: security error on safari (#167, #168, @yields) + +2.1.1 / 2014-12-29 +================== + + * browser: use `typeof` to check for `console` existence + * browser: check for `console.log` truthiness (fix IE 8/9) + * browser: add support for Chrome apps + * Readme: added Windows usage remarks + * Add `bower.json` to properly support bower install + +2.1.0 / 2014-10-15 +================== + + * node: implement `DEBUG_FD` env variable support + * package: update "browserify" to v6.1.0 + * package: add "license" field to package.json (#135, @panuhorsmalahti) + +2.0.0 / 2014-09-01 +================== + + * package: update "browserify" to v5.11.0 + * node: use stderr rather than stdout for logging (#29, @stephenmathieson) + +1.0.4 / 2014-07-15 +================== + + * dist: recompile + * example: remove `console.info()` log usage + * example: add "Content-Type" UTF-8 header to browser example + * browser: place %c marker after the space character + * browser: reset the "content" color via `color: inherit` + * browser: add colors support for Firefox >= v31 + * debug: prefer an instance `log()` function over the global one (#119) + * Readme: update documentation about styled console logs for FF v31 (#116, @wryk) + +1.0.3 / 2014-07-09 +================== + + * Add support for multiple wildcards in namespaces (#122, @seegno) + * browser: fix lint + +1.0.2 / 2014-06-10 +================== + + * browser: update color palette (#113, @gscottolson) + * common: make console logging function configurable (#108, @timoxley) + * node: fix %o colors on old node <= 0.8.x + * Makefile: find node path using shell/which (#109, @timoxley) + +1.0.1 / 2014-06-06 +================== + + * browser: use `removeItem()` to clear localStorage + * browser, node: don't set DEBUG if namespaces is undefined (#107, @leedm777) + * package: add "contributors" section + * node: fix comment typo + * README: list authors + +1.0.0 / 2014-06-04 +================== + + * make ms diff be global, not be scope + * debug: ignore empty strings in enable() + * node: make DEBUG_COLORS able to disable coloring + * *: export the `colors` array + * npmignore: don't publish the `dist` dir + * Makefile: refactor to use browserify + * package: add "browserify" as a dev dependency + * Readme: add Web Inspector Colors section + * node: reset terminal color for the debug content + * node: map "%o" to `util.inspect()` + * browser: map "%j" to `JSON.stringify()` + * debug: add custom "formatters" + * debug: use "ms" module for humanizing the diff + * Readme: add "bash" syntax highlighting + * browser: add Firebug color support + * browser: add colors for WebKit browsers + * node: apply log to `console` + * rewrite: abstract common logic for Node & browsers + * add .jshintrc file + +0.8.1 / 2014-04-14 +================== + + * package: re-add the "component" section + +0.8.0 / 2014-03-30 +================== + + * add `enable()` method for nodejs. Closes #27 + * change from stderr to stdout + * remove unnecessary index.js file + +0.7.4 / 2013-11-13 +================== + + * remove "browserify" key from package.json (fixes something in browserify) + +0.7.3 / 2013-10-30 +================== + + * fix: catch localStorage security error when cookies are blocked (Chrome) + * add debug(err) support. Closes #46 + * add .browser prop to package.json. Closes #42 + +0.7.2 / 2013-02-06 +================== + + * fix package.json + * fix: Mobile Safari (private mode) is broken with debug + * fix: Use unicode to send escape character to shell instead of octal to work with strict mode javascript + +0.7.1 / 2013-02-05 +================== + + * add repository URL to package.json + * add DEBUG_COLORED to force colored output + * add browserify support + * fix component. Closes #24 + +0.7.0 / 2012-05-04 +================== + + * Added .component to package.json + * Added debug.component.js build + +0.6.0 / 2012-03-16 +================== + + * Added support for "-" prefix in DEBUG [Vinay Pulim] + * Added `.enabled` flag to the node version [TooTallNate] + +0.5.0 / 2012-02-02 +================== + + * Added: humanize diffs. Closes #8 + * Added `debug.disable()` to the CS variant + * Removed padding. Closes #10 + * Fixed: persist client-side variant again. Closes #9 + +0.4.0 / 2012-02-01 +================== + + * Added browser variant support for older browsers [TooTallNate] + * Added `debug.enable('project:*')` to browser variant [TooTallNate] + * Added padding to diff (moved it to the right) + +0.3.0 / 2012-01-26 +================== + + * Added millisecond diff when isatty, otherwise UTC string + +0.2.0 / 2012-01-22 +================== + + * Added wildcard support + +0.1.0 / 2011-12-02 +================== + + * Added: remove colors unless stderr isatty [TooTallNate] + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/node_modules/debug/LICENSE b/node_modules/debug/LICENSE new file mode 100644 index 0000000..658c933 --- /dev/null +++ b/node_modules/debug/LICENSE @@ -0,0 +1,19 @@ +(The MIT License) + +Copyright (c) 2014 TJ Holowaychuk + +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. + diff --git a/node_modules/debug/README.md b/node_modules/debug/README.md new file mode 100644 index 0000000..88dae35 --- /dev/null +++ b/node_modules/debug/README.md @@ -0,0 +1,455 @@ +# debug +[![Build Status](https://travis-ci.org/visionmedia/debug.svg?branch=master)](https://travis-ci.org/visionmedia/debug) [![Coverage Status](https://coveralls.io/repos/github/visionmedia/debug/badge.svg?branch=master)](https://coveralls.io/github/visionmedia/debug?branch=master) [![Slack](https://visionmedia-community-slackin.now.sh/badge.svg)](https://visionmedia-community-slackin.now.sh/) [![OpenCollective](https://opencollective.com/debug/backers/badge.svg)](#backers) +[![OpenCollective](https://opencollective.com/debug/sponsors/badge.svg)](#sponsors) + + + +A tiny JavaScript debugging utility modelled after Node.js core's debugging +technique. Works in Node.js and web browsers. + +## Installation + +```bash +$ npm install debug +``` + +## Usage + +`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. + +Example [_app.js_](./examples/node/app.js): + +```js +var debug = require('debug')('http') + , http = require('http') + , name = 'My App'; + +// fake app + +debug('booting %o', name); + +http.createServer(function(req, res){ + debug(req.method + ' ' + req.url); + res.end('hello\n'); +}).listen(3000, function(){ + debug('listening'); +}); + +// fake worker of some kind + +require('./worker'); +``` + +Example [_worker.js_](./examples/node/worker.js): + +```js +var a = require('debug')('worker:a') + , b = require('debug')('worker:b'); + +function work() { + a('doing lots of uninteresting work'); + setTimeout(work, Math.random() * 1000); +} + +work(); + +function workb() { + b('doing some work'); + setTimeout(workb, Math.random() * 2000); +} + +workb(); +``` + +The `DEBUG` environment variable is then used to enable these based on space or +comma-delimited names. + +Here are some examples: + +screen shot 2017-08-08 at 12 53 04 pm +screen shot 2017-08-08 at 12 53 38 pm +screen shot 2017-08-08 at 12 53 25 pm + +#### Windows command prompt notes + +##### CMD + +On Windows the environment variable is set using the `set` command. + +```cmd +set DEBUG=*,-not_this +``` + +Example: + +```cmd +set DEBUG=* & node app.js +``` + +##### PowerShell (VS Code default) + +PowerShell uses different syntax to set environment variables. + +```cmd +$env:DEBUG = "*,-not_this" +``` + +Example: + +```cmd +$env:DEBUG='app';node app.js +``` + +Then, run the program to be debugged as usual. + +npm script example: +```js + "windowsDebug": "@powershell -Command $env:DEBUG='*';node app.js", +``` + +## Namespace Colors + +Every debug instance has a color generated for it based on its namespace name. +This helps when visually parsing the debug output to identify which debug instance +a debug line belongs to. + +#### Node.js + +In Node.js, colors are enabled when stderr is a TTY. You also _should_ install +the [`supports-color`](https://npmjs.org/supports-color) module alongside debug, +otherwise debug will only use a small handful of basic colors. + + + +#### Web Browser + +Colors are also enabled on "Web Inspectors" that understand the `%c` formatting +option. These are WebKit web inspectors, Firefox ([since version +31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) +and the Firebug plugin for Firefox (any version). + + + + +## Millisecond diff + +When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. + + + +When stdout is not a TTY, `Date#toISOString()` is used, making it more useful for logging the debug information as shown below: + + + + +## Conventions + +If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". If you append a "*" to the end of your name, it will always be enabled regardless of the setting of the DEBUG environment variable. You can then use it for normal output as well as debug output. + +## Wildcards + +The `*` character may be used as a wildcard. Suppose for example your library has +debuggers named "connect:bodyParser", "connect:compress", "connect:session", +instead of listing all three with +`DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do +`DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. + +You can also exclude specific debuggers by prefixing them with a "-" character. +For example, `DEBUG=*,-connect:*` would include all debuggers except those +starting with "connect:". + +## Environment Variables + +When running through Node.js, you can set a few environment variables that will +change the behavior of the debug logging: + +| Name | Purpose | +|-----------|-------------------------------------------------| +| `DEBUG` | Enables/disables specific debugging namespaces. | +| `DEBUG_HIDE_DATE` | Hide date from debug output (non-TTY). | +| `DEBUG_COLORS`| Whether or not to use colors in the debug output. | +| `DEBUG_DEPTH` | Object inspection depth. | +| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | + + +__Note:__ The environment variables beginning with `DEBUG_` end up being +converted into an Options object that gets used with `%o`/`%O` formatters. +See the Node.js documentation for +[`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) +for the complete list. + +## Formatters + +Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. +Below are the officially supported formatters: + +| Formatter | Representation | +|-----------|----------------| +| `%O` | Pretty-print an Object on multiple lines. | +| `%o` | Pretty-print an Object all on a single line. | +| `%s` | String. | +| `%d` | Number (both integer and float). | +| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | +| `%%` | Single percent sign ('%'). This does not consume an argument. | + + +### Custom formatters + +You can add custom formatters by extending the `debug.formatters` object. +For example, if you wanted to add support for rendering a Buffer as hex with +`%h`, you could do something like: + +```js +const createDebug = require('debug') +createDebug.formatters.h = (v) => { + return v.toString('hex') +} + +// …elsewhere +const debug = createDebug('foo') +debug('this is hex: %h', new Buffer('hello world')) +// foo this is hex: 68656c6c6f20776f726c6421 +0ms +``` + + +## Browser Support + +You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), +or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), +if you don't want to build it yourself. + +Debug's enable state is currently persisted by `localStorage`. +Consider the situation shown below where you have `worker:a` and `worker:b`, +and wish to debug both. You can enable this using `localStorage.debug`: + +```js +localStorage.debug = 'worker:*' +``` + +And then refresh the page. + +```js +a = debug('worker:a'); +b = debug('worker:b'); + +setInterval(function(){ + a('doing some work'); +}, 1000); + +setInterval(function(){ + b('doing some work'); +}, 1200); +``` + + +## Output streams + + By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: + +Example [_stdout.js_](./examples/node/stdout.js): + +```js +var debug = require('debug'); +var error = debug('app:error'); + +// by default stderr is used +error('goes to stderr!'); + +var log = debug('app:log'); +// set this namespace to log via console.log +log.log = console.log.bind(console); // don't forget to bind to console! +log('goes to stdout'); +error('still goes to stderr!'); + +// set all output to go via console.info +// overrides all per-namespace log settings +debug.log = console.info.bind(console); +error('now goes to stdout via console.info'); +log('still goes to stdout, but via console.info now'); +``` + +## Extend +You can simply extend debugger +```js +const log = require('debug')('auth'); + +//creates new debug instance with extended namespace +const logSign = log.extend('sign'); +const logLogin = log.extend('login'); + +log('hello'); // auth hello +logSign('hello'); //auth:sign hello +logLogin('hello'); //auth:login hello +``` + +## Set dynamically + +You can also enable debug dynamically by calling the `enable()` method : + +```js +let debug = require('debug'); + +console.log(1, debug.enabled('test')); + +debug.enable('test'); +console.log(2, debug.enabled('test')); + +debug.disable(); +console.log(3, debug.enabled('test')); + +``` + +print : +``` +1 false +2 true +3 false +``` + +Usage : +`enable(namespaces)` +`namespaces` can include modes separated by a colon and wildcards. + +Note that calling `enable()` completely overrides previously set DEBUG variable : + +``` +$ DEBUG=foo node -e 'var dbg = require("debug"); dbg.enable("bar"); console.log(dbg.enabled("foo"))' +=> false +``` + +`disable()` + +Will disable all namespaces. The functions returns the namespaces currently +enabled (and skipped). This can be useful if you want to disable debugging +temporarily without knowing what was enabled to begin with. + +For example: + +```js +let debug = require('debug'); +debug.enable('foo:*,-foo:bar'); +let namespaces = debug.disable(); +debug.enable(namespaces); +``` + +Note: There is no guarantee that the string will be identical to the initial +enable string, but semantically they will be identical. + +## Checking whether a debug target is enabled + +After you've created a debug instance, you can determine whether or not it is +enabled by checking the `enabled` property: + +```javascript +const debug = require('debug')('http'); + +if (debug.enabled) { + // do stuff... +} +``` + +You can also manually toggle this property to force the debug instance to be +enabled or disabled. + + +## Authors + + - TJ Holowaychuk + - Nathan Rajlich + - Andrew Rhyne + +## Backers + +Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## Sponsors + +Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +## License + +(The MIT License) + +Copyright (c) 2014-2017 TJ Holowaychuk <tj@vision-media.ca> + +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. diff --git a/node_modules/debug/dist/debug.js b/node_modules/debug/dist/debug.js new file mode 100644 index 0000000..89ad0c2 --- /dev/null +++ b/node_modules/debug/dist/debug.js @@ -0,0 +1,912 @@ +"use strict"; + +function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread(); } + +function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance"); } + +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } + +function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } } + +function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } + +(function (f) { + if ((typeof exports === "undefined" ? "undefined" : _typeof(exports)) === "object" && typeof module !== "undefined") { + module.exports = f(); + } else if (typeof define === "function" && define.amd) { + define([], f); + } else { + var g; + + if (typeof window !== "undefined") { + g = window; + } else if (typeof global !== "undefined") { + g = global; + } else if (typeof self !== "undefined") { + g = self; + } else { + g = this; + } + + g.debug = f(); + } +})(function () { + var define, module, exports; + return function () { + function r(e, n, t) { + function o(i, f) { + if (!n[i]) { + if (!e[i]) { + var c = "function" == typeof require && require; + if (!f && c) return c(i, !0); + if (u) return u(i, !0); + var a = new Error("Cannot find module '" + i + "'"); + throw a.code = "MODULE_NOT_FOUND", a; + } + + var p = n[i] = { + exports: {} + }; + e[i][0].call(p.exports, function (r) { + var n = e[i][1][r]; + return o(n || r); + }, p, p.exports, r, e, n, t); + } + + return n[i].exports; + } + + for (var u = "function" == typeof require && require, i = 0; i < t.length; i++) { + o(t[i]); + } + + return o; + } + + return r; + }()({ + 1: [function (require, module, exports) { + /** + * Helpers. + */ + var s = 1000; + var m = s * 60; + var h = m * 60; + var d = h * 24; + var w = d * 7; + var y = d * 365.25; + /** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + + module.exports = function (val, options) { + options = options || {}; + + var type = _typeof(val); + + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isNaN(val) === false) { + return options.long ? fmtLong(val) : fmtShort(val); + } + + throw new Error('val is not a non-empty string or a valid number. val=' + JSON.stringify(val)); + }; + /** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + + + function parse(str) { + str = String(str); + + if (str.length > 100) { + return; + } + + var match = /^((?:\d+)?\-?\d?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(str); + + if (!match) { + return; + } + + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + + case 'weeks': + case 'week': + case 'w': + return n * w; + + case 'days': + case 'day': + case 'd': + return n * d; + + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + + default: + return undefined; + } + } + /** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + + + function fmtShort(ms) { + var msAbs = Math.abs(ms); + + if (msAbs >= d) { + return Math.round(ms / d) + 'd'; + } + + if (msAbs >= h) { + return Math.round(ms / h) + 'h'; + } + + if (msAbs >= m) { + return Math.round(ms / m) + 'm'; + } + + if (msAbs >= s) { + return Math.round(ms / s) + 's'; + } + + return ms + 'ms'; + } + /** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + + + function fmtLong(ms) { + var msAbs = Math.abs(ms); + + if (msAbs >= d) { + return plural(ms, msAbs, d, 'day'); + } + + if (msAbs >= h) { + return plural(ms, msAbs, h, 'hour'); + } + + if (msAbs >= m) { + return plural(ms, msAbs, m, 'minute'); + } + + if (msAbs >= s) { + return plural(ms, msAbs, s, 'second'); + } + + return ms + ' ms'; + } + /** + * Pluralization helper. + */ + + + function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); + } + }, {}], + 2: [function (require, module, exports) { + // shim for using process in browser + var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it + // don't break things. But we need to wrap it in a try catch in case it is + // wrapped in strict mode code which doesn't define any globals. It's inside a + // function because try/catches deoptimize in certain engines. + + var cachedSetTimeout; + var cachedClearTimeout; + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + + function defaultClearTimeout() { + throw new Error('clearTimeout has not been defined'); + } + + (function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } + })(); + + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } // if setTimeout wasn't available but was latter defined + + + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch (e) { + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch (e) { + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + } + + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } // if clearTimeout wasn't available but was latter defined + + + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e) { + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e) { + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + } + + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + + draining = false; + + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + + var timeout = runTimeout(cleanUpNextTick); + draining = true; + var len = queue.length; + + while (len) { + currentQueue = queue; + queue = []; + + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + + queueIndex = -1; + len = queue.length; + } + + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + + process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + + queue.push(new Item(fun, args)); + + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + }; // v8 likes predictible objects + + + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + + process.title = 'browser'; + process.browser = true; + process.env = {}; + process.argv = []; + process.version = ''; // empty string to avoid regexp issues + + process.versions = {}; + + function noop() {} + + process.on = noop; + process.addListener = noop; + process.once = noop; + process.off = noop; + process.removeListener = noop; + process.removeAllListeners = noop; + process.emit = noop; + process.prependListener = noop; + process.prependOnceListener = noop; + + process.listeners = function (name) { + return []; + }; + + 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'); + }; + + process.umask = function () { + return 0; + }; + }, {}], + 3: [function (require, module, exports) { + /** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ + function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = require('ms'); + Object.keys(env).forEach(function (key) { + createDebug[key] = env[key]; + }); + /** + * Active `debug` instances. + */ + + createDebug.instances = []; + /** + * The currently active debug mode names, and names to skip. + */ + + createDebug.names = []; + createDebug.skips = []; + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + + createDebug.formatters = {}; + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + + function selectColor(namespace) { + var hash = 0; + + for (var i = 0; i < namespace.length; i++) { + hash = (hash << 5) - hash + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + + createDebug.selectColor = selectColor; + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + + function createDebug(namespace) { + var prevTime; + + function debug() { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + + // Disabled? + if (!debug.enabled) { + return; + } + + var self = debug; // Set `diff` timestamp + + var curr = Number(new Date()); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + args[0] = createDebug.coerce(args[0]); + + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } // Apply any `formatters` transformations + + + var index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, function (match, format) { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return match; + } + + index++; + var formatter = createDebug.formatters[format]; + + if (typeof formatter === 'function') { + var val = args[index]; + match = formatter.call(self, val); // Now we need to remove `args[index]` since it's inlined in the `format` + + args.splice(index, 1); + index--; + } + + return match; + }); // Apply env-specific formatting (colors, etc.) + + createDebug.formatArgs.call(self, args); + var logFn = self.log || createDebug.log; + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.enabled = createDebug.enabled(namespace); + debug.useColors = createDebug.useColors(); + debug.color = selectColor(namespace); + debug.destroy = destroy; + debug.extend = extend; // Debug.formatArgs = formatArgs; + // debug.rawLog = rawLog; + // env-specific initialization logic for debug instances + + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } + + createDebug.instances.push(debug); + return debug; + } + + function destroy() { + var index = createDebug.instances.indexOf(this); + + if (index !== -1) { + createDebug.instances.splice(index, 1); + return true; + } + + return false; + } + + function extend(namespace, delimiter) { + var newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + + + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.names = []; + createDebug.skips = []; + var i; + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; + + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } + + namespaces = split[i].replace(/\*/g, '.*?'); + + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + + for (i = 0; i < createDebug.instances.length; i++) { + var instance = createDebug.instances[i]; + instance.enabled = createDebug.enabled(instance.namespace); + } + } + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + + + function disable() { + var namespaces = [].concat(_toConsumableArray(createDebug.names.map(toNamespace)), _toConsumableArray(createDebug.skips.map(toNamespace).map(function (namespace) { + return '-' + namespace; + }))).join(','); + createDebug.enable(''); + return namespaces; + } + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + + + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } + + var i; + var len; + + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } + + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } + + return false; + } + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + + + function toNamespace(regexp) { + return regexp.toString().substring(2, regexp.toString().length - 2).replace(/\.\*\?$/, '*'); + } + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + + + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + + return val; + } + + createDebug.enable(createDebug.load()); + return createDebug; + } + + module.exports = setup; + }, { + "ms": 1 + }], + 4: [function (require, module, exports) { + (function (process) { + /* eslint-env browser */ + + /** + * This is the web browser implementation of `debug()`. + */ + exports.log = log; + exports.formatArgs = formatArgs; + exports.save = save; + exports.load = load; + exports.useColors = useColors; + exports.storage = localstorage(); + /** + * Colors. + */ + + exports.colors = ['#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC', '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF', '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC', '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF', '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC', '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033', '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366', '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933', '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC', '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF', '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33']; + /** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + // eslint-disable-next-line complexity + + function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } // Internet Explorer and Edge do not support colors. + + + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + + + return typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773 + typeof window !== 'undefined' && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker + typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); + } + /** + * Colorize log arguments if enabled. + * + * @api public + */ + + + function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + this.namespace + (this.useColors ? ' %c' : ' ') + args[0] + (this.useColors ? '%c ' : ' ') + '+' + module.exports.humanize(this.diff); + + if (!this.useColors) { + return; + } + + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + + var index = 0; + var lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, function (match) { + if (match === '%%') { + return; + } + + index++; + + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + args.splice(lastC, 0, c); + } + /** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ + + + function log() { + var _console; + + // This hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return (typeof console === "undefined" ? "undefined" : _typeof(console)) === 'object' && console.log && (_console = console).log.apply(_console, arguments); + } + /** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + + + function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) {// Swallow + // XXX (@Qix-) should we be logging these? + } + } + /** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + + + function load() { + var r; + + try { + r = exports.storage.getItem('debug'); + } catch (error) {} // Swallow + // XXX (@Qix-) should we be logging these? + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + + + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; + } + /** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + + + function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) {// Swallow + // XXX (@Qix-) should we be logging these? + } + } + + module.exports = require('./common')(exports); + var formatters = module.exports.formatters; + /** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + + formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } + }; + }).call(this, require('_process')); + }, { + "./common": 3, + "_process": 2 + }] + }, {}, [4])(4); +}); diff --git a/node_modules/debug/package.json b/node_modules/debug/package.json new file mode 100644 index 0000000..78c0492 --- /dev/null +++ b/node_modules/debug/package.json @@ -0,0 +1,103 @@ +{ + "_from": "debug@4", + "_id": "debug@4.1.1", + "_inBundle": false, + "_integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "_location": "/debug", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "debug@4", + "name": "debug", + "escapedName": "debug", + "rawSpec": "4", + "saveSpec": null, + "fetchSpec": "4" + }, + "_requiredBy": [ + "/agent-base", + "/https-proxy-agent" + ], + "_resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "_shasum": "3b72260255109c6b589cee050f1d516139664791", + "_spec": "debug@4", + "_where": "/Users/cday/Code/zendesk/fetch-build-from-gcb/node_modules/https-proxy-agent", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "browser": "./src/browser.js", + "bugs": { + "url": "https://github.com/visionmedia/debug/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net", + "url": "http://n8.io" + }, + { + "name": "Andrew Rhyne", + "email": "rhyneandrew@gmail.com" + } + ], + "dependencies": { + "ms": "^2.1.1" + }, + "deprecated": false, + "description": "small debugging utility", + "devDependencies": { + "@babel/cli": "^7.0.0", + "@babel/core": "^7.0.0", + "@babel/preset-env": "^7.0.0", + "browserify": "14.4.0", + "chai": "^3.5.0", + "concurrently": "^3.1.0", + "coveralls": "^3.0.2", + "istanbul": "^0.4.5", + "karma": "^3.0.0", + "karma-chai": "^0.1.0", + "karma-mocha": "^1.3.0", + "karma-phantomjs-launcher": "^1.0.2", + "mocha": "^5.2.0", + "mocha-lcov-reporter": "^1.2.0", + "rimraf": "^2.5.4", + "xo": "^0.23.0" + }, + "files": [ + "src", + "dist/debug.js", + "LICENSE", + "README.md" + ], + "homepage": "https://github.com/visionmedia/debug#readme", + "keywords": [ + "debug", + "log", + "debugger" + ], + "license": "MIT", + "main": "./src/index.js", + "name": "debug", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" + }, + "scripts": { + "build": "npm run build:debug && npm run build:test", + "build:debug": "babel -o dist/debug.js dist/debug.es6.js > dist/debug.js", + "build:test": "babel -d dist test.js", + "clean": "rimraf dist coverage", + "lint": "xo", + "prebuild:debug": "mkdir -p dist && browserify --standalone debug -o dist/debug.es6.js .", + "pretest:browser": "npm run build", + "test": "npm run test:node && npm run test:browser", + "test:browser": "karma start --single-run", + "test:coverage": "cat ./coverage/lcov.info | coveralls", + "test:node": "istanbul cover _mocha -- test.js" + }, + "unpkg": "./dist/debug.js", + "version": "4.1.1" +} diff --git a/node_modules/debug/src/browser.js b/node_modules/debug/src/browser.js new file mode 100644 index 0000000..5f34c0d --- /dev/null +++ b/node_modules/debug/src/browser.js @@ -0,0 +1,264 @@ +/* eslint-env browser */ + +/** + * This is the web browser implementation of `debug()`. + */ + +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); + +/** + * Colors. + */ + +exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +// eslint-disable-next-line complexity +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } + + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); + + if (!this.useColors) { + return; + } + + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); + + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ +function log(...args) { + // This hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return typeof console === 'object' && + console.log && + console.log(...args); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ +function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; +} + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } +} + +module.exports = require('./common')(exports); + +const {formatters} = module.exports; + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; diff --git a/node_modules/debug/src/common.js b/node_modules/debug/src/common.js new file mode 100644 index 0000000..2f82b8d --- /dev/null +++ b/node_modules/debug/src/common.js @@ -0,0 +1,266 @@ + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ + +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = require('ms'); + + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); + + /** + * Active `debug` instances. + */ + createDebug.instances = []; + + /** + * The currently active debug mode names, and names to skip. + */ + + createDebug.names = []; + createDebug.skips = []; + + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; + + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; + + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } + + const self = debug; + + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + args[0] = createDebug.coerce(args[0]); + + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } + + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return match; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); + + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); + + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.enabled = createDebug.enabled(namespace); + debug.useColors = createDebug.useColors(); + debug.color = selectColor(namespace); + debug.destroy = destroy; + debug.extend = extend; + // Debug.formatArgs = formatArgs; + // debug.rawLog = rawLog; + + // env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } + + createDebug.instances.push(debug); + + return debug; + } + + function destroy() { + const index = createDebug.instances.indexOf(this); + if (index !== -1) { + createDebug.instances.splice(index, 1); + return true; + } + return false; + } + + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + + createDebug.names = []; + createDebug.skips = []; + + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; + + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } + + namespaces = split[i].replace(/\*/g, '.*?'); + + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + + for (i = 0; i < createDebug.instances.length; i++) { + const instance = createDebug.instances[i]; + instance.enabled = createDebug.enabled(instance.namespace); + } + } + + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } + + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } + + let i; + let len; + + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } + + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } + + return false; + } + + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } + + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + + createDebug.enable(createDebug.load()); + + return createDebug; +} + +module.exports = setup; diff --git a/node_modules/debug/src/index.js b/node_modules/debug/src/index.js new file mode 100644 index 0000000..bf4c57f --- /dev/null +++ b/node_modules/debug/src/index.js @@ -0,0 +1,10 @@ +/** + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. + */ + +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = require('./browser.js'); +} else { + module.exports = require('./node.js'); +} diff --git a/node_modules/debug/src/node.js b/node_modules/debug/src/node.js new file mode 100644 index 0000000..5e1f154 --- /dev/null +++ b/node_modules/debug/src/node.js @@ -0,0 +1,257 @@ +/** + * Module dependencies. + */ + +const tty = require('tty'); +const util = require('util'); + +/** + * This is the Node.js implementation of `debug()`. + */ + +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; + +/** + * Colors. + */ + +exports.colors = [6, 2, 3, 4, 5, 1]; + +try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = require('supports-color'); + + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } +} catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. +} + +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + +exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); +}).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); + + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } + + obj[prop] = val; + return obj; +}, {}); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); +} + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + +function formatArgs(args) { + const {namespace: name, useColors} = this; + + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } +} + +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; +} + +/** + * Invokes `util.format()` with the specified arguments and writes to stderr. + */ + +function log(...args) { + return process.stderr.write(util.format(...args) + '\n'); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; +} + +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + +function init(debug) { + debug.inspectOpts = {}; + + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} + +module.exports = require('./common')(exports); + +const {formatters} = module.exports; + +/** + * Map %o to `util.inspect()`, all on a single line. + */ + +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .replace(/\s*\n\s*/g, ' '); +}; + +/** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ + +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; diff --git a/node_modules/ecdsa-sig-formatter/CODEOWNERS b/node_modules/ecdsa-sig-formatter/CODEOWNERS new file mode 100644 index 0000000..4451d3d --- /dev/null +++ b/node_modules/ecdsa-sig-formatter/CODEOWNERS @@ -0,0 +1 @@ +* @omsmith diff --git a/node_modules/ecdsa-sig-formatter/LICENSE b/node_modules/ecdsa-sig-formatter/LICENSE new file mode 100644 index 0000000..8754ed6 --- /dev/null +++ b/node_modules/ecdsa-sig-formatter/LICENSE @@ -0,0 +1,201 @@ +Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. 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 and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2015 D2L Corporation + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/ecdsa-sig-formatter/README.md b/node_modules/ecdsa-sig-formatter/README.md new file mode 100644 index 0000000..daa95d6 --- /dev/null +++ b/node_modules/ecdsa-sig-formatter/README.md @@ -0,0 +1,65 @@ +# ecdsa-sig-formatter + +[![Build Status](https://travis-ci.org/Brightspace/node-ecdsa-sig-formatter.svg?branch=master)](https://travis-ci.org/Brightspace/node-ecdsa-sig-formatter) [![Coverage Status](https://coveralls.io/repos/Brightspace/node-ecdsa-sig-formatter/badge.svg)](https://coveralls.io/r/Brightspace/node-ecdsa-sig-formatter) + +Translate between JOSE and ASN.1/DER encodings for ECDSA signatures + +## Install +```sh +npm install ecdsa-sig-formatter --save +``` + +## Usage +```js +var format = require('ecdsa-sig-formatter'); + +var derSignature = '..'; // asn.1/DER encoded ecdsa signature + +var joseSignature = format.derToJose(derSignature); + +``` + +### API + +--- + +#### `.derToJose(Buffer|String signature, String alg)` -> `String` + +Convert the ASN.1/DER encoded signature to a JOSE-style concatenated signature. +Returns a _base64 url_ encoded `String`. + +* If _signature_ is a `String`, it should be _base64_ encoded +* _alg_ must be one of _ES256_, _ES384_ or _ES512_ + +--- + +#### `.joseToDer(Buffer|String signature, String alg)` -> `Buffer` + +Convert the JOSE-style concatenated signature to an ASN.1/DER encoded +signature. Returns a `Buffer` + +* If _signature_ is a `String`, it should be _base64 url_ encoded +* _alg_ must be one of _ES256_, _ES384_ or _ES512_ + +## Contributing + +1. **Fork** the repository. Committing directly against this repository is + highly discouraged. + +2. Make your modifications in a branch, updating and writing new unit tests + as necessary in the `spec` directory. + +3. Ensure that all tests pass with `npm test` + +4. `rebase` your changes against master. *Do not merge*. + +5. Submit a pull request to this repository. Wait for tests to run and someone + to chime in. + +### Code Style + +This repository is configured with [EditorConfig][EditorConfig] and +[ESLint][ESLint] rules. + +[EditorConfig]: http://editorconfig.org/ +[ESLint]: http://eslint.org diff --git a/node_modules/ecdsa-sig-formatter/package.json b/node_modules/ecdsa-sig-formatter/package.json new file mode 100644 index 0000000..b90f439 --- /dev/null +++ b/node_modules/ecdsa-sig-formatter/package.json @@ -0,0 +1,74 @@ +{ + "_from": "ecdsa-sig-formatter@^1.0.11", + "_id": "ecdsa-sig-formatter@1.0.11", + "_inBundle": false, + "_integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "_location": "/ecdsa-sig-formatter", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "ecdsa-sig-formatter@^1.0.11", + "name": "ecdsa-sig-formatter", + "escapedName": "ecdsa-sig-formatter", + "rawSpec": "^1.0.11", + "saveSpec": null, + "fetchSpec": "^1.0.11" + }, + "_requiredBy": [ + "/google-auth-library", + "/jwa" + ], + "_resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "_shasum": "ae0f0fa2d85045ef14a817daa3ce9acd0489e5bf", + "_spec": "ecdsa-sig-formatter@^1.0.11", + "_where": "/Users/cday/Code/zendesk/fetch-build-from-gcb/node_modules/google-auth-library", + "author": { + "name": "D2L Corporation" + }, + "bugs": { + "url": "https://github.com/Brightspace/node-ecdsa-sig-formatter/issues" + }, + "bundleDependencies": false, + "dependencies": { + "safe-buffer": "^5.0.1" + }, + "deprecated": false, + "description": "Translate ECDSA signatures between ASN.1/DER and JOSE-style concatenation", + "devDependencies": { + "bench": "^0.3.6", + "chai": "^3.5.0", + "coveralls": "^2.11.9", + "eslint": "^2.12.0", + "eslint-config-brightspace": "^0.2.1", + "istanbul": "^0.4.3", + "jwk-to-pem": "^1.2.5", + "mocha": "^2.5.3", + "native-crypto": "^1.7.0" + }, + "homepage": "https://github.com/Brightspace/node-ecdsa-sig-formatter#readme", + "keywords": [ + "ecdsa", + "der", + "asn.1", + "jwt", + "jwa", + "jsonwebtoken", + "jose" + ], + "license": "Apache-2.0", + "main": "src/ecdsa-sig-formatter.js", + "name": "ecdsa-sig-formatter", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/Brightspace/node-ecdsa-sig-formatter.git" + }, + "scripts": { + "check-style": "eslint .", + "pretest": "npm run check-style", + "report-cov": "cat ./coverage/lcov.info | coveralls", + "test": "istanbul cover --root src _mocha -- spec" + }, + "typings": "./src/ecdsa-sig-formatter.d.ts", + "version": "1.0.11" +} diff --git a/node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.d.ts b/node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.d.ts new file mode 100644 index 0000000..9693aa0 --- /dev/null +++ b/node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.d.ts @@ -0,0 +1,17 @@ +/// + +declare module "ecdsa-sig-formatter" { + /** + * Convert the ASN.1/DER encoded signature to a JOSE-style concatenated signature. Returns a base64 url encoded String. + * If signature is a String, it should be base64 encoded + * alg must be one of ES256, ES384 or ES512 + */ + export function derToJose(signature: Buffer | string, alg: string): string; + + /** + * Convert the JOSE-style concatenated signature to an ASN.1/DER encoded signature. Returns a Buffer + * If signature is a String, it should be base64 url encoded + * alg must be one of ES256, ES384 or ES512 + */ + export function joseToDer(signature: Buffer | string, alg: string): Buffer +} diff --git a/node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js b/node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js new file mode 100644 index 0000000..38eeb9b --- /dev/null +++ b/node_modules/ecdsa-sig-formatter/src/ecdsa-sig-formatter.js @@ -0,0 +1,187 @@ +'use strict'; + +var Buffer = require('safe-buffer').Buffer; + +var getParamBytesForAlg = require('./param-bytes-for-alg'); + +var MAX_OCTET = 0x80, + CLASS_UNIVERSAL = 0, + PRIMITIVE_BIT = 0x20, + TAG_SEQ = 0x10, + TAG_INT = 0x02, + ENCODED_TAG_SEQ = (TAG_SEQ | PRIMITIVE_BIT) | (CLASS_UNIVERSAL << 6), + ENCODED_TAG_INT = TAG_INT | (CLASS_UNIVERSAL << 6); + +function base64Url(base64) { + return base64 + .replace(/=/g, '') + .replace(/\+/g, '-') + .replace(/\//g, '_'); +} + +function signatureAsBuffer(signature) { + if (Buffer.isBuffer(signature)) { + return signature; + } else if ('string' === typeof signature) { + return Buffer.from(signature, 'base64'); + } + + throw new TypeError('ECDSA signature must be a Base64 string or a Buffer'); +} + +function derToJose(signature, alg) { + signature = signatureAsBuffer(signature); + var paramBytes = getParamBytesForAlg(alg); + + // the DER encoded param should at most be the param size, plus a padding + // zero, since due to being a signed integer + var maxEncodedParamLength = paramBytes + 1; + + var inputLength = signature.length; + + var offset = 0; + if (signature[offset++] !== ENCODED_TAG_SEQ) { + throw new Error('Could not find expected "seq"'); + } + + var seqLength = signature[offset++]; + if (seqLength === (MAX_OCTET | 1)) { + seqLength = signature[offset++]; + } + + if (inputLength - offset < seqLength) { + throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining'); + } + + if (signature[offset++] !== ENCODED_TAG_INT) { + throw new Error('Could not find expected "int" for "r"'); + } + + var rLength = signature[offset++]; + + if (inputLength - offset - 2 < rLength) { + throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available'); + } + + if (maxEncodedParamLength < rLength) { + throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); + } + + var rOffset = offset; + offset += rLength; + + if (signature[offset++] !== ENCODED_TAG_INT) { + throw new Error('Could not find expected "int" for "s"'); + } + + var sLength = signature[offset++]; + + if (inputLength - offset !== sLength) { + throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"'); + } + + if (maxEncodedParamLength < sLength) { + throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); + } + + var sOffset = offset; + offset += sLength; + + if (offset !== inputLength) { + throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain'); + } + + var rPadding = paramBytes - rLength, + sPadding = paramBytes - sLength; + + var dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength); + + for (offset = 0; offset < rPadding; ++offset) { + dst[offset] = 0; + } + signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength); + + offset = paramBytes; + + for (var o = offset; offset < o + sPadding; ++offset) { + dst[offset] = 0; + } + signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength); + + dst = dst.toString('base64'); + dst = base64Url(dst); + + return dst; +} + +function countPadding(buf, start, stop) { + var padding = 0; + while (start + padding < stop && buf[start + padding] === 0) { + ++padding; + } + + var needsSign = buf[start + padding] >= MAX_OCTET; + if (needsSign) { + --padding; + } + + return padding; +} + +function joseToDer(signature, alg) { + signature = signatureAsBuffer(signature); + var paramBytes = getParamBytesForAlg(alg); + + var signatureBytes = signature.length; + if (signatureBytes !== paramBytes * 2) { + throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"'); + } + + var rPadding = countPadding(signature, 0, paramBytes); + var sPadding = countPadding(signature, paramBytes, signature.length); + var rLength = paramBytes - rPadding; + var sLength = paramBytes - sPadding; + + var rsBytes = 1 + 1 + rLength + 1 + 1 + sLength; + + var shortLength = rsBytes < MAX_OCTET; + + var dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes); + + var offset = 0; + dst[offset++] = ENCODED_TAG_SEQ; + if (shortLength) { + // Bit 8 has value "0" + // bits 7-1 give the length. + dst[offset++] = rsBytes; + } else { + // Bit 8 of first octet has value "1" + // bits 7-1 give the number of additional length octets. + dst[offset++] = MAX_OCTET | 1; + // length, base 256 + dst[offset++] = rsBytes & 0xff; + } + dst[offset++] = ENCODED_TAG_INT; + dst[offset++] = rLength; + if (rPadding < 0) { + dst[offset++] = 0; + offset += signature.copy(dst, offset, 0, paramBytes); + } else { + offset += signature.copy(dst, offset, rPadding, paramBytes); + } + dst[offset++] = ENCODED_TAG_INT; + dst[offset++] = sLength; + if (sPadding < 0) { + dst[offset++] = 0; + signature.copy(dst, offset, paramBytes); + } else { + signature.copy(dst, offset, paramBytes + sPadding); + } + + return dst; +} + +module.exports = { + derToJose: derToJose, + joseToDer: joseToDer +}; diff --git a/node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js b/node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js new file mode 100644 index 0000000..9fe67ac --- /dev/null +++ b/node_modules/ecdsa-sig-formatter/src/param-bytes-for-alg.js @@ -0,0 +1,23 @@ +'use strict'; + +function getParamSize(keySize) { + var result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1); + return result; +} + +var paramBytesForAlg = { + ES256: getParamSize(256), + ES384: getParamSize(384), + ES512: getParamSize(521) +}; + +function getParamBytesForAlg(alg) { + var paramBytes = paramBytesForAlg[alg]; + if (paramBytes) { + return paramBytes; + } + + throw new Error('Unknown algorithm "' + alg + '"'); +} + +module.exports = getParamBytesForAlg; diff --git a/node_modules/event-target-shim/LICENSE b/node_modules/event-target-shim/LICENSE new file mode 100644 index 0000000..c39e694 --- /dev/null +++ b/node_modules/event-target-shim/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2015 Toru Nagashima + +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. + diff --git a/node_modules/event-target-shim/README.md b/node_modules/event-target-shim/README.md new file mode 100644 index 0000000..a4f9c1b --- /dev/null +++ b/node_modules/event-target-shim/README.md @@ -0,0 +1,293 @@ +# event-target-shim + +[![npm version](https://img.shields.io/npm/v/event-target-shim.svg)](https://www.npmjs.com/package/event-target-shim) +[![Downloads/month](https://img.shields.io/npm/dm/event-target-shim.svg)](http://www.npmtrends.com/event-target-shim) +[![Build Status](https://travis-ci.org/mysticatea/event-target-shim.svg?branch=master)](https://travis-ci.org/mysticatea/event-target-shim) +[![Coverage Status](https://codecov.io/gh/mysticatea/event-target-shim/branch/master/graph/badge.svg)](https://codecov.io/gh/mysticatea/event-target-shim) +[![Dependency Status](https://david-dm.org/mysticatea/event-target-shim.svg)](https://david-dm.org/mysticatea/event-target-shim) + +An implementation of [WHATWG EventTarget interface](https://dom.spec.whatwg.org/#interface-eventtarget), plus few extensions. + +- This provides `EventTarget` constructor that can inherit for your custom object. +- This provides an utility that defines properties of attribute listeners (e.g. `obj.onclick`). + +```js +import {EventTarget, defineEventAttribute} from "event-target-shim" + +class Foo extends EventTarget { + // ... +} + +// Define `foo.onhello` property. +defineEventAttribute(Foo.prototype, "hello") + +// Use +const foo = new Foo() +foo.addEventListener("hello", e => console.log("hello", e)) +foo.onhello = e => console.log("onhello:", e) +foo.dispatchEvent(new CustomEvent("hello")) +``` + +## 💿 Installation + +Use [npm](https://www.npmjs.com/) to install then use a bundler. + +``` +npm install event-target-shim +``` + +Or download from [`dist` directory](./dist). + +- [dist/event-target-shim.mjs](dist/event-target-shim.mjs) ... ES modules version. +- [dist/event-target-shim.js](dist/event-target-shim.js) ... Common JS version. +- [dist/event-target-shim.umd.js](dist/event-target-shim.umd.js) ... UMD (Universal Module Definition) version. This is transpiled by [Babel](https://babeljs.io/) for IE 11. + +## 📖 Usage + +```js +import {EventTarget, defineEventAttribute} from "event-target-shim" +// or +const {EventTarget, defineEventAttribute} = require("event-target-shim") + +// or UMD version defines a global variable: +const {EventTarget, defineEventAttribute} = window.EventTargetShim +``` + +### EventTarget + +> https://dom.spec.whatwg.org/#interface-eventtarget + +#### eventTarget.addEventListener(type, callback, options) + +Register an event listener. + +- `type` is a string. This is the event name to register. +- `callback` is a function. This is the event listener to register. +- `options` is a boolean or an object `{ capture?: boolean, passive?: boolean, once?: boolean }`. If this is a boolean, it's same meaning as `{ capture: options }`. + - `capture` is the flag to register the event listener for capture phase. + - `passive` is the flag to ignore `event.preventDefault()` method in the event listener. + - `once` is the flag to remove the event listener automatically after the first call. + +#### eventTarget.removeEventListener(type, callback, options) + +Unregister an event listener. + +- `type` is a string. This is the event name to unregister. +- `callback` is a function. This is the event listener to unregister. +- `options` is a boolean or an object `{ capture?: boolean }`. If this is a boolean, it's same meaning as `{ capture: options }`. + - `capture` is the flag to register the event listener for capture phase. + +#### eventTarget.dispatchEvent(event) + +Dispatch an event. + +- `event` is a [Event](https://dom.spec.whatwg.org/#event) object or an object `{ type: string, [key: string]: any }`. The latter is non-standard but useful. In both cases, listeners receive the event as implementing [Event](https://dom.spec.whatwg.org/#event) interface. + +### defineEventAttribute(proto, type) + +Define an event attribute (e.g. `onclick`) to `proto`. This is non-standard. + +- `proto` is an object (assuming it's a prototype object). This function defines a getter/setter pair for the event attribute. +- `type` is a string. This is the event name to define. + +For example: + +```js +class AbortSignal extends EventTarget { + constructor() { + this.aborted = false + } +} +// Define `onabort` property. +defineEventAttribute(AbortSignal.prototype, "abort") +``` + +### EventTarget(types) + +Define a custom `EventTarget` class with event attributes. This is non-standard. + +- `types` is a string or an array of strings. This is the event name to define. + +For example: + +```js +// This has `onabort` property. +class AbortSignal extends EventTarget("abort") { + constructor() { + this.aborted = false + } +} +``` + +## 📚 Examples + +### ES2015 and later + +> https://jsfiddle.net/636vea92/ + +```js +const {EventTarget, defineEventAttribute} = EventTargetShim + +// Define a derived class. +class Foo extends EventTarget { + // ... +} + +// Define `foo.onhello` property. +defineEventAttribute(Foo.prototype, "hello") + +// Register event listeners. +const foo = new Foo() +foo.addEventListener("hello", (e) => { + console.log("hello", e) +}) +foo.onhello = (e) => { + console.log("onhello", e) +} + +// Dispatching events +foo.dispatchEvent(new CustomEvent("hello", { detail: "detail" })) +``` + +### Typescript + +```ts +import { EventTarget, defineEventAttribute } from "event-target-shim"; + +// Define events +type FooEvents = { + hello: CustomEvent +} +type FooEventAttributes = { + onhello: CustomEvent +} + +// Define a derived class. +class Foo extends EventTarget { + // ... +} +// Define `foo.onhello` property's implementation. +defineEventAttribute(Foo.prototype, "hello") + +// Register event listeners. +const foo = new Foo() +foo.addEventListener("hello", (e) => { + console.log("hello", e.detail) +}) +foo.onhello = (e) => { + console.log("onhello", e.detail) +} + +// Dispatching events +foo.dispatchEvent(new CustomEvent("hello", { detail: "detail" })) +``` + +Unfortunately, both `FooEvents` and `FooEventAttributes` are needed because TypeScript doesn't allow the mutation of string literal types. If TypeScript allowed us to compute `"onhello"` from `"hello"` in types, `FooEventAttributes` will be optional. + +This `EventTarget` type is compatible with `EventTarget` interface of `lib.dom.d.ts`. + +#### To disallow unknown events + +By default, methods such as `addEventListener` accept unknown events. You can disallow unknown events by the third type parameter `"strict"`. + +```ts +type FooEvents = { + hello: CustomEvent +} +class Foo extends EventTarget { + // ... +} + +// OK because `hello` is defined in FooEvents. +foo.addEventListener("hello", (e) => { +}) +// Error because `unknown` is not defined in FooEvents. +foo.addEventListener("unknown", (e) => { +}) +``` + +However, if you use `"strict"` parameter, it loses compatibility with `EventTarget` interface of `lib.dom.d.ts`. + +#### To infer the type of `dispatchEvent()` method + +TypeScript cannot infer the event type of `dispatchEvent()` method properly from the argument in most cases. You can improve this behavior with the following steps: + +1. Use the third type parameter `"strict"`. This prevents inferring to `dispatchEvent()`. +2. Make the `type` property of event definitions stricter. + +```ts +type FooEvents = { + hello: CustomEvent & { type: "hello" } + hey: Event & { type: "hey" } +} +class Foo extends EventTarget { + // ... +} + +// Error because `detail` property is lacking. +foo.dispatchEvent({ type: "hello" }) +``` + +### ES5 + +> https://jsfiddle.net/522zc9de/ + +```js +// Define a derived class. +function Foo() { + EventTarget.call(this) +} +Foo.prototype = Object.create(EventTarget.prototype, { + constructor: { value: Foo, configurable: true, writable: true } + // ... +}) + +// Define `foo.onhello` property. +defineEventAttribute(Foo.prototype, "hello") + +// Register event listeners. +var foo = new Foo() +foo.addEventListener("hello", function(e) { + console.log("hello", e) +}) +foo.onhello = function(e) { + console.log("onhello", e) +} + +// Dispatching events +function isSupportEventConstrucor() { // IE does not support. + try { + new CusomEvent("hello") + return true + } catch (_err) { + return false + } +} +if (isSupportEventConstrucor()) { + foo.dispatchEvent(new CustomEvent("hello", { detail: "detail" })) +} else { + var e = document.createEvent("CustomEvent") + e.initCustomEvent("hello", false, false, "detail") + foo.dispatchEvent(e) +} +``` + +## 📰 Changelog + +- See [GitHub releases](https://github.com/mysticatea/event-target-shim/releases). + +## 🍻 Contributing + +Contributing is welcome ❤️ + +Please use GitHub issues/PRs. + +### Development tools + +- `npm install` installs dependencies for development. +- `npm test` runs tests and measures code coverage. +- `npm run clean` removes temporary files of tests. +- `npm run coverage` opens code coverage of the previous test with your default browser. +- `npm run lint` runs ESLint. +- `npm run build` generates `dist` codes. +- `npm run watch` runs tests on each file change. diff --git a/node_modules/event-target-shim/dist/event-target-shim.js b/node_modules/event-target-shim/dist/event-target-shim.js new file mode 100644 index 0000000..53ce220 --- /dev/null +++ b/node_modules/event-target-shim/dist/event-target-shim.js @@ -0,0 +1,871 @@ +/** + * @author Toru Nagashima + * @copyright 2015 Toru Nagashima. All rights reserved. + * See LICENSE file in root directory for full license. + */ +'use strict'; + +Object.defineProperty(exports, '__esModule', { value: true }); + +/** + * @typedef {object} PrivateData + * @property {EventTarget} eventTarget The event target. + * @property {{type:string}} event The original event object. + * @property {number} eventPhase The current event phase. + * @property {EventTarget|null} currentTarget The current event target. + * @property {boolean} canceled The flag to prevent default. + * @property {boolean} stopped The flag to stop propagation. + * @property {boolean} immediateStopped The flag to stop propagation immediately. + * @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null. + * @property {number} timeStamp The unix time. + * @private + */ + +/** + * Private data for event wrappers. + * @type {WeakMap} + * @private + */ +const privateData = new WeakMap(); + +/** + * Cache for wrapper classes. + * @type {WeakMap} + * @private + */ +const wrappers = new WeakMap(); + +/** + * Get private data. + * @param {Event} event The event object to get private data. + * @returns {PrivateData} The private data of the event. + * @private + */ +function pd(event) { + const retv = privateData.get(event); + console.assert( + retv != null, + "'this' is expected an Event object, but got", + event + ); + return retv +} + +/** + * https://dom.spec.whatwg.org/#set-the-canceled-flag + * @param data {PrivateData} private data. + */ +function setCancelFlag(data) { + if (data.passiveListener != null) { + if ( + typeof console !== "undefined" && + typeof console.error === "function" + ) { + console.error( + "Unable to preventDefault inside passive event listener invocation.", + data.passiveListener + ); + } + return + } + if (!data.event.cancelable) { + return + } + + data.canceled = true; + if (typeof data.event.preventDefault === "function") { + data.event.preventDefault(); + } +} + +/** + * @see https://dom.spec.whatwg.org/#interface-event + * @private + */ +/** + * The event wrapper. + * @constructor + * @param {EventTarget} eventTarget The event target of this dispatching. + * @param {Event|{type:string}} event The original event to wrap. + */ +function Event(eventTarget, event) { + privateData.set(this, { + eventTarget, + event, + eventPhase: 2, + currentTarget: eventTarget, + canceled: false, + stopped: false, + immediateStopped: false, + passiveListener: null, + timeStamp: event.timeStamp || Date.now(), + }); + + // https://heycam.github.io/webidl/#Unforgeable + Object.defineProperty(this, "isTrusted", { value: false, enumerable: true }); + + // Define accessors + const keys = Object.keys(event); + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (!(key in this)) { + Object.defineProperty(this, key, defineRedirectDescriptor(key)); + } + } +} + +// Should be enumerable, but class methods are not enumerable. +Event.prototype = { + /** + * The type of this event. + * @type {string} + */ + get type() { + return pd(this).event.type + }, + + /** + * The target of this event. + * @type {EventTarget} + */ + get target() { + return pd(this).eventTarget + }, + + /** + * The target of this event. + * @type {EventTarget} + */ + get currentTarget() { + return pd(this).currentTarget + }, + + /** + * @returns {EventTarget[]} The composed path of this event. + */ + composedPath() { + const currentTarget = pd(this).currentTarget; + if (currentTarget == null) { + return [] + } + return [currentTarget] + }, + + /** + * Constant of NONE. + * @type {number} + */ + get NONE() { + return 0 + }, + + /** + * Constant of CAPTURING_PHASE. + * @type {number} + */ + get CAPTURING_PHASE() { + return 1 + }, + + /** + * Constant of AT_TARGET. + * @type {number} + */ + get AT_TARGET() { + return 2 + }, + + /** + * Constant of BUBBLING_PHASE. + * @type {number} + */ + get BUBBLING_PHASE() { + return 3 + }, + + /** + * The target of this event. + * @type {number} + */ + get eventPhase() { + return pd(this).eventPhase + }, + + /** + * Stop event bubbling. + * @returns {void} + */ + stopPropagation() { + const data = pd(this); + + data.stopped = true; + if (typeof data.event.stopPropagation === "function") { + data.event.stopPropagation(); + } + }, + + /** + * Stop event bubbling. + * @returns {void} + */ + stopImmediatePropagation() { + const data = pd(this); + + data.stopped = true; + data.immediateStopped = true; + if (typeof data.event.stopImmediatePropagation === "function") { + data.event.stopImmediatePropagation(); + } + }, + + /** + * The flag to be bubbling. + * @type {boolean} + */ + get bubbles() { + return Boolean(pd(this).event.bubbles) + }, + + /** + * The flag to be cancelable. + * @type {boolean} + */ + get cancelable() { + return Boolean(pd(this).event.cancelable) + }, + + /** + * Cancel this event. + * @returns {void} + */ + preventDefault() { + setCancelFlag(pd(this)); + }, + + /** + * The flag to indicate cancellation state. + * @type {boolean} + */ + get defaultPrevented() { + return pd(this).canceled + }, + + /** + * The flag to be composed. + * @type {boolean} + */ + get composed() { + return Boolean(pd(this).event.composed) + }, + + /** + * The unix time of this event. + * @type {number} + */ + get timeStamp() { + return pd(this).timeStamp + }, + + /** + * The target of this event. + * @type {EventTarget} + * @deprecated + */ + get srcElement() { + return pd(this).eventTarget + }, + + /** + * The flag to stop event bubbling. + * @type {boolean} + * @deprecated + */ + get cancelBubble() { + return pd(this).stopped + }, + set cancelBubble(value) { + if (!value) { + return + } + const data = pd(this); + + data.stopped = true; + if (typeof data.event.cancelBubble === "boolean") { + data.event.cancelBubble = true; + } + }, + + /** + * The flag to indicate cancellation state. + * @type {boolean} + * @deprecated + */ + get returnValue() { + return !pd(this).canceled + }, + set returnValue(value) { + if (!value) { + setCancelFlag(pd(this)); + } + }, + + /** + * Initialize this event object. But do nothing under event dispatching. + * @param {string} type The event type. + * @param {boolean} [bubbles=false] The flag to be possible to bubble up. + * @param {boolean} [cancelable=false] The flag to be possible to cancel. + * @deprecated + */ + initEvent() { + // Do nothing. + }, +}; + +// `constructor` is not enumerable. +Object.defineProperty(Event.prototype, "constructor", { + value: Event, + configurable: true, + writable: true, +}); + +// Ensure `event instanceof window.Event` is `true`. +if (typeof window !== "undefined" && typeof window.Event !== "undefined") { + Object.setPrototypeOf(Event.prototype, window.Event.prototype); + + // Make association for wrappers. + wrappers.set(window.Event.prototype, Event); +} + +/** + * Get the property descriptor to redirect a given property. + * @param {string} key Property name to define property descriptor. + * @returns {PropertyDescriptor} The property descriptor to redirect the property. + * @private + */ +function defineRedirectDescriptor(key) { + return { + get() { + return pd(this).event[key] + }, + set(value) { + pd(this).event[key] = value; + }, + configurable: true, + enumerable: true, + } +} + +/** + * Get the property descriptor to call a given method property. + * @param {string} key Property name to define property descriptor. + * @returns {PropertyDescriptor} The property descriptor to call the method property. + * @private + */ +function defineCallDescriptor(key) { + return { + value() { + const event = pd(this).event; + return event[key].apply(event, arguments) + }, + configurable: true, + enumerable: true, + } +} + +/** + * Define new wrapper class. + * @param {Function} BaseEvent The base wrapper class. + * @param {Object} proto The prototype of the original event. + * @returns {Function} The defined wrapper class. + * @private + */ +function defineWrapper(BaseEvent, proto) { + const keys = Object.keys(proto); + if (keys.length === 0) { + return BaseEvent + } + + /** CustomEvent */ + function CustomEvent(eventTarget, event) { + BaseEvent.call(this, eventTarget, event); + } + + CustomEvent.prototype = Object.create(BaseEvent.prototype, { + constructor: { value: CustomEvent, configurable: true, writable: true }, + }); + + // Define accessors. + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (!(key in BaseEvent.prototype)) { + const descriptor = Object.getOwnPropertyDescriptor(proto, key); + const isFunc = typeof descriptor.value === "function"; + Object.defineProperty( + CustomEvent.prototype, + key, + isFunc + ? defineCallDescriptor(key) + : defineRedirectDescriptor(key) + ); + } + } + + return CustomEvent +} + +/** + * Get the wrapper class of a given prototype. + * @param {Object} proto The prototype of the original event to get its wrapper. + * @returns {Function} The wrapper class. + * @private + */ +function getWrapper(proto) { + if (proto == null || proto === Object.prototype) { + return Event + } + + let wrapper = wrappers.get(proto); + if (wrapper == null) { + wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto); + wrappers.set(proto, wrapper); + } + return wrapper +} + +/** + * Wrap a given event to management a dispatching. + * @param {EventTarget} eventTarget The event target of this dispatching. + * @param {Object} event The event to wrap. + * @returns {Event} The wrapper instance. + * @private + */ +function wrapEvent(eventTarget, event) { + const Wrapper = getWrapper(Object.getPrototypeOf(event)); + return new Wrapper(eventTarget, event) +} + +/** + * Get the immediateStopped flag of a given event. + * @param {Event} event The event to get. + * @returns {boolean} The flag to stop propagation immediately. + * @private + */ +function isStopped(event) { + return pd(event).immediateStopped +} + +/** + * Set the current event phase of a given event. + * @param {Event} event The event to set current target. + * @param {number} eventPhase New event phase. + * @returns {void} + * @private + */ +function setEventPhase(event, eventPhase) { + pd(event).eventPhase = eventPhase; +} + +/** + * Set the current target of a given event. + * @param {Event} event The event to set current target. + * @param {EventTarget|null} currentTarget New current target. + * @returns {void} + * @private + */ +function setCurrentTarget(event, currentTarget) { + pd(event).currentTarget = currentTarget; +} + +/** + * Set a passive listener of a given event. + * @param {Event} event The event to set current target. + * @param {Function|null} passiveListener New passive listener. + * @returns {void} + * @private + */ +function setPassiveListener(event, passiveListener) { + pd(event).passiveListener = passiveListener; +} + +/** + * @typedef {object} ListenerNode + * @property {Function} listener + * @property {1|2|3} listenerType + * @property {boolean} passive + * @property {boolean} once + * @property {ListenerNode|null} next + * @private + */ + +/** + * @type {WeakMap>} + * @private + */ +const listenersMap = new WeakMap(); + +// Listener types +const CAPTURE = 1; +const BUBBLE = 2; +const ATTRIBUTE = 3; + +/** + * Check whether a given value is an object or not. + * @param {any} x The value to check. + * @returns {boolean} `true` if the value is an object. + */ +function isObject(x) { + return x !== null && typeof x === "object" //eslint-disable-line no-restricted-syntax +} + +/** + * Get listeners. + * @param {EventTarget} eventTarget The event target to get. + * @returns {Map} The listeners. + * @private + */ +function getListeners(eventTarget) { + const listeners = listenersMap.get(eventTarget); + if (listeners == null) { + throw new TypeError( + "'this' is expected an EventTarget object, but got another value." + ) + } + return listeners +} + +/** + * Get the property descriptor for the event attribute of a given event. + * @param {string} eventName The event name to get property descriptor. + * @returns {PropertyDescriptor} The property descriptor. + * @private + */ +function defineEventAttributeDescriptor(eventName) { + return { + get() { + const listeners = getListeners(this); + let node = listeners.get(eventName); + while (node != null) { + if (node.listenerType === ATTRIBUTE) { + return node.listener + } + node = node.next; + } + return null + }, + + set(listener) { + if (typeof listener !== "function" && !isObject(listener)) { + listener = null; // eslint-disable-line no-param-reassign + } + const listeners = getListeners(this); + + // Traverse to the tail while removing old value. + let prev = null; + let node = listeners.get(eventName); + while (node != null) { + if (node.listenerType === ATTRIBUTE) { + // Remove old value. + if (prev !== null) { + prev.next = node.next; + } else if (node.next !== null) { + listeners.set(eventName, node.next); + } else { + listeners.delete(eventName); + } + } else { + prev = node; + } + + node = node.next; + } + + // Add new value. + if (listener !== null) { + const newNode = { + listener, + listenerType: ATTRIBUTE, + passive: false, + once: false, + next: null, + }; + if (prev === null) { + listeners.set(eventName, newNode); + } else { + prev.next = newNode; + } + } + }, + configurable: true, + enumerable: true, + } +} + +/** + * Define an event attribute (e.g. `eventTarget.onclick`). + * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite. + * @param {string} eventName The event name to define. + * @returns {void} + */ +function defineEventAttribute(eventTargetPrototype, eventName) { + Object.defineProperty( + eventTargetPrototype, + `on${eventName}`, + defineEventAttributeDescriptor(eventName) + ); +} + +/** + * Define a custom EventTarget with event attributes. + * @param {string[]} eventNames Event names for event attributes. + * @returns {EventTarget} The custom EventTarget. + * @private + */ +function defineCustomEventTarget(eventNames) { + /** CustomEventTarget */ + function CustomEventTarget() { + EventTarget.call(this); + } + + CustomEventTarget.prototype = Object.create(EventTarget.prototype, { + constructor: { + value: CustomEventTarget, + configurable: true, + writable: true, + }, + }); + + for (let i = 0; i < eventNames.length; ++i) { + defineEventAttribute(CustomEventTarget.prototype, eventNames[i]); + } + + return CustomEventTarget +} + +/** + * EventTarget. + * + * - This is constructor if no arguments. + * - This is a function which returns a CustomEventTarget constructor if there are arguments. + * + * For example: + * + * class A extends EventTarget {} + * class B extends EventTarget("message") {} + * class C extends EventTarget("message", "error") {} + * class D extends EventTarget(["message", "error"]) {} + */ +function EventTarget() { + /*eslint-disable consistent-return */ + if (this instanceof EventTarget) { + listenersMap.set(this, new Map()); + return + } + if (arguments.length === 1 && Array.isArray(arguments[0])) { + return defineCustomEventTarget(arguments[0]) + } + if (arguments.length > 0) { + const types = new Array(arguments.length); + for (let i = 0; i < arguments.length; ++i) { + types[i] = arguments[i]; + } + return defineCustomEventTarget(types) + } + throw new TypeError("Cannot call a class as a function") + /*eslint-enable consistent-return */ +} + +// Should be enumerable, but class methods are not enumerable. +EventTarget.prototype = { + /** + * Add a given listener to this event target. + * @param {string} eventName The event name to add. + * @param {Function} listener The listener to add. + * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. + * @returns {void} + */ + addEventListener(eventName, listener, options) { + if (listener == null) { + return + } + if (typeof listener !== "function" && !isObject(listener)) { + throw new TypeError("'listener' should be a function or an object.") + } + + const listeners = getListeners(this); + const optionsIsObj = isObject(options); + const capture = optionsIsObj + ? Boolean(options.capture) + : Boolean(options); + const listenerType = capture ? CAPTURE : BUBBLE; + const newNode = { + listener, + listenerType, + passive: optionsIsObj && Boolean(options.passive), + once: optionsIsObj && Boolean(options.once), + next: null, + }; + + // Set it as the first node if the first node is null. + let node = listeners.get(eventName); + if (node === undefined) { + listeners.set(eventName, newNode); + return + } + + // Traverse to the tail while checking duplication.. + let prev = null; + while (node != null) { + if ( + node.listener === listener && + node.listenerType === listenerType + ) { + // Should ignore duplication. + return + } + prev = node; + node = node.next; + } + + // Add it. + prev.next = newNode; + }, + + /** + * Remove a given listener from this event target. + * @param {string} eventName The event name to remove. + * @param {Function} listener The listener to remove. + * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. + * @returns {void} + */ + removeEventListener(eventName, listener, options) { + if (listener == null) { + return + } + + const listeners = getListeners(this); + const capture = isObject(options) + ? Boolean(options.capture) + : Boolean(options); + const listenerType = capture ? CAPTURE : BUBBLE; + + let prev = null; + let node = listeners.get(eventName); + while (node != null) { + if ( + node.listener === listener && + node.listenerType === listenerType + ) { + if (prev !== null) { + prev.next = node.next; + } else if (node.next !== null) { + listeners.set(eventName, node.next); + } else { + listeners.delete(eventName); + } + return + } + + prev = node; + node = node.next; + } + }, + + /** + * Dispatch a given event. + * @param {Event|{type:string}} event The event to dispatch. + * @returns {boolean} `false` if canceled. + */ + dispatchEvent(event) { + if (event == null || typeof event.type !== "string") { + throw new TypeError('"event.type" should be a string.') + } + + // If listeners aren't registered, terminate. + const listeners = getListeners(this); + const eventName = event.type; + let node = listeners.get(eventName); + if (node == null) { + return true + } + + // Since we cannot rewrite several properties, so wrap object. + const wrappedEvent = wrapEvent(this, event); + + // This doesn't process capturing phase and bubbling phase. + // This isn't participating in a tree. + let prev = null; + while (node != null) { + // Remove this listener if it's once + if (node.once) { + if (prev !== null) { + prev.next = node.next; + } else if (node.next !== null) { + listeners.set(eventName, node.next); + } else { + listeners.delete(eventName); + } + } else { + prev = node; + } + + // Call this listener + setPassiveListener( + wrappedEvent, + node.passive ? node.listener : null + ); + if (typeof node.listener === "function") { + try { + node.listener.call(this, wrappedEvent); + } catch (err) { + if ( + typeof console !== "undefined" && + typeof console.error === "function" + ) { + console.error(err); + } + } + } else if ( + node.listenerType !== ATTRIBUTE && + typeof node.listener.handleEvent === "function" + ) { + node.listener.handleEvent(wrappedEvent); + } + + // Break if `event.stopImmediatePropagation` was called. + if (isStopped(wrappedEvent)) { + break + } + + node = node.next; + } + setPassiveListener(wrappedEvent, null); + setEventPhase(wrappedEvent, 0); + setCurrentTarget(wrappedEvent, null); + + return !wrappedEvent.defaultPrevented + }, +}; + +// `constructor` is not enumerable. +Object.defineProperty(EventTarget.prototype, "constructor", { + value: EventTarget, + configurable: true, + writable: true, +}); + +// Ensure `eventTarget instanceof window.EventTarget` is `true`. +if ( + typeof window !== "undefined" && + typeof window.EventTarget !== "undefined" +) { + Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype); +} + +exports.defineEventAttribute = defineEventAttribute; +exports.EventTarget = EventTarget; +exports.default = EventTarget; + +module.exports = EventTarget +module.exports.EventTarget = module.exports["default"] = EventTarget +module.exports.defineEventAttribute = defineEventAttribute +//# sourceMappingURL=event-target-shim.js.map diff --git a/node_modules/event-target-shim/dist/event-target-shim.js.map b/node_modules/event-target-shim/dist/event-target-shim.js.map new file mode 100644 index 0000000..83c5f62 --- /dev/null +++ b/node_modules/event-target-shim/dist/event-target-shim.js.map @@ -0,0 +1 @@ +{"version":3,"file":"event-target-shim.js","sources":["../src/event.mjs","../src/event-target.mjs"],"sourcesContent":["/**\n * @typedef {object} PrivateData\n * @property {EventTarget} eventTarget The event target.\n * @property {{type:string}} event The original event object.\n * @property {number} eventPhase The current event phase.\n * @property {EventTarget|null} currentTarget The current event target.\n * @property {boolean} canceled The flag to prevent default.\n * @property {boolean} stopped The flag to stop propagation.\n * @property {boolean} immediateStopped The flag to stop propagation immediately.\n * @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null.\n * @property {number} timeStamp The unix time.\n * @private\n */\n\n/**\n * Private data for event wrappers.\n * @type {WeakMap}\n * @private\n */\nconst privateData = new WeakMap()\n\n/**\n * Cache for wrapper classes.\n * @type {WeakMap}\n * @private\n */\nconst wrappers = new WeakMap()\n\n/**\n * Get private data.\n * @param {Event} event The event object to get private data.\n * @returns {PrivateData} The private data of the event.\n * @private\n */\nfunction pd(event) {\n const retv = privateData.get(event)\n console.assert(\n retv != null,\n \"'this' is expected an Event object, but got\",\n event\n )\n return retv\n}\n\n/**\n * https://dom.spec.whatwg.org/#set-the-canceled-flag\n * @param data {PrivateData} private data.\n */\nfunction setCancelFlag(data) {\n if (data.passiveListener != null) {\n if (\n typeof console !== \"undefined\" &&\n typeof console.error === \"function\"\n ) {\n console.error(\n \"Unable to preventDefault inside passive event listener invocation.\",\n data.passiveListener\n )\n }\n return\n }\n if (!data.event.cancelable) {\n return\n }\n\n data.canceled = true\n if (typeof data.event.preventDefault === \"function\") {\n data.event.preventDefault()\n }\n}\n\n/**\n * @see https://dom.spec.whatwg.org/#interface-event\n * @private\n */\n/**\n * The event wrapper.\n * @constructor\n * @param {EventTarget} eventTarget The event target of this dispatching.\n * @param {Event|{type:string}} event The original event to wrap.\n */\nfunction Event(eventTarget, event) {\n privateData.set(this, {\n eventTarget,\n event,\n eventPhase: 2,\n currentTarget: eventTarget,\n canceled: false,\n stopped: false,\n immediateStopped: false,\n passiveListener: null,\n timeStamp: event.timeStamp || Date.now(),\n })\n\n // https://heycam.github.io/webidl/#Unforgeable\n Object.defineProperty(this, \"isTrusted\", { value: false, enumerable: true })\n\n // Define accessors\n const keys = Object.keys(event)\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i]\n if (!(key in this)) {\n Object.defineProperty(this, key, defineRedirectDescriptor(key))\n }\n }\n}\n\n// Should be enumerable, but class methods are not enumerable.\nEvent.prototype = {\n /**\n * The type of this event.\n * @type {string}\n */\n get type() {\n return pd(this).event.type\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n */\n get target() {\n return pd(this).eventTarget\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n */\n get currentTarget() {\n return pd(this).currentTarget\n },\n\n /**\n * @returns {EventTarget[]} The composed path of this event.\n */\n composedPath() {\n const currentTarget = pd(this).currentTarget\n if (currentTarget == null) {\n return []\n }\n return [currentTarget]\n },\n\n /**\n * Constant of NONE.\n * @type {number}\n */\n get NONE() {\n return 0\n },\n\n /**\n * Constant of CAPTURING_PHASE.\n * @type {number}\n */\n get CAPTURING_PHASE() {\n return 1\n },\n\n /**\n * Constant of AT_TARGET.\n * @type {number}\n */\n get AT_TARGET() {\n return 2\n },\n\n /**\n * Constant of BUBBLING_PHASE.\n * @type {number}\n */\n get BUBBLING_PHASE() {\n return 3\n },\n\n /**\n * The target of this event.\n * @type {number}\n */\n get eventPhase() {\n return pd(this).eventPhase\n },\n\n /**\n * Stop event bubbling.\n * @returns {void}\n */\n stopPropagation() {\n const data = pd(this)\n\n data.stopped = true\n if (typeof data.event.stopPropagation === \"function\") {\n data.event.stopPropagation()\n }\n },\n\n /**\n * Stop event bubbling.\n * @returns {void}\n */\n stopImmediatePropagation() {\n const data = pd(this)\n\n data.stopped = true\n data.immediateStopped = true\n if (typeof data.event.stopImmediatePropagation === \"function\") {\n data.event.stopImmediatePropagation()\n }\n },\n\n /**\n * The flag to be bubbling.\n * @type {boolean}\n */\n get bubbles() {\n return Boolean(pd(this).event.bubbles)\n },\n\n /**\n * The flag to be cancelable.\n * @type {boolean}\n */\n get cancelable() {\n return Boolean(pd(this).event.cancelable)\n },\n\n /**\n * Cancel this event.\n * @returns {void}\n */\n preventDefault() {\n setCancelFlag(pd(this))\n },\n\n /**\n * The flag to indicate cancellation state.\n * @type {boolean}\n */\n get defaultPrevented() {\n return pd(this).canceled\n },\n\n /**\n * The flag to be composed.\n * @type {boolean}\n */\n get composed() {\n return Boolean(pd(this).event.composed)\n },\n\n /**\n * The unix time of this event.\n * @type {number}\n */\n get timeStamp() {\n return pd(this).timeStamp\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n * @deprecated\n */\n get srcElement() {\n return pd(this).eventTarget\n },\n\n /**\n * The flag to stop event bubbling.\n * @type {boolean}\n * @deprecated\n */\n get cancelBubble() {\n return pd(this).stopped\n },\n set cancelBubble(value) {\n if (!value) {\n return\n }\n const data = pd(this)\n\n data.stopped = true\n if (typeof data.event.cancelBubble === \"boolean\") {\n data.event.cancelBubble = true\n }\n },\n\n /**\n * The flag to indicate cancellation state.\n * @type {boolean}\n * @deprecated\n */\n get returnValue() {\n return !pd(this).canceled\n },\n set returnValue(value) {\n if (!value) {\n setCancelFlag(pd(this))\n }\n },\n\n /**\n * Initialize this event object. But do nothing under event dispatching.\n * @param {string} type The event type.\n * @param {boolean} [bubbles=false] The flag to be possible to bubble up.\n * @param {boolean} [cancelable=false] The flag to be possible to cancel.\n * @deprecated\n */\n initEvent() {\n // Do nothing.\n },\n}\n\n// `constructor` is not enumerable.\nObject.defineProperty(Event.prototype, \"constructor\", {\n value: Event,\n configurable: true,\n writable: true,\n})\n\n// Ensure `event instanceof window.Event` is `true`.\nif (typeof window !== \"undefined\" && typeof window.Event !== \"undefined\") {\n Object.setPrototypeOf(Event.prototype, window.Event.prototype)\n\n // Make association for wrappers.\n wrappers.set(window.Event.prototype, Event)\n}\n\n/**\n * Get the property descriptor to redirect a given property.\n * @param {string} key Property name to define property descriptor.\n * @returns {PropertyDescriptor} The property descriptor to redirect the property.\n * @private\n */\nfunction defineRedirectDescriptor(key) {\n return {\n get() {\n return pd(this).event[key]\n },\n set(value) {\n pd(this).event[key] = value\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Get the property descriptor to call a given method property.\n * @param {string} key Property name to define property descriptor.\n * @returns {PropertyDescriptor} The property descriptor to call the method property.\n * @private\n */\nfunction defineCallDescriptor(key) {\n return {\n value() {\n const event = pd(this).event\n return event[key].apply(event, arguments)\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Define new wrapper class.\n * @param {Function} BaseEvent The base wrapper class.\n * @param {Object} proto The prototype of the original event.\n * @returns {Function} The defined wrapper class.\n * @private\n */\nfunction defineWrapper(BaseEvent, proto) {\n const keys = Object.keys(proto)\n if (keys.length === 0) {\n return BaseEvent\n }\n\n /** CustomEvent */\n function CustomEvent(eventTarget, event) {\n BaseEvent.call(this, eventTarget, event)\n }\n\n CustomEvent.prototype = Object.create(BaseEvent.prototype, {\n constructor: { value: CustomEvent, configurable: true, writable: true },\n })\n\n // Define accessors.\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i]\n if (!(key in BaseEvent.prototype)) {\n const descriptor = Object.getOwnPropertyDescriptor(proto, key)\n const isFunc = typeof descriptor.value === \"function\"\n Object.defineProperty(\n CustomEvent.prototype,\n key,\n isFunc\n ? defineCallDescriptor(key)\n : defineRedirectDescriptor(key)\n )\n }\n }\n\n return CustomEvent\n}\n\n/**\n * Get the wrapper class of a given prototype.\n * @param {Object} proto The prototype of the original event to get its wrapper.\n * @returns {Function} The wrapper class.\n * @private\n */\nfunction getWrapper(proto) {\n if (proto == null || proto === Object.prototype) {\n return Event\n }\n\n let wrapper = wrappers.get(proto)\n if (wrapper == null) {\n wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto)\n wrappers.set(proto, wrapper)\n }\n return wrapper\n}\n\n/**\n * Wrap a given event to management a dispatching.\n * @param {EventTarget} eventTarget The event target of this dispatching.\n * @param {Object} event The event to wrap.\n * @returns {Event} The wrapper instance.\n * @private\n */\nexport function wrapEvent(eventTarget, event) {\n const Wrapper = getWrapper(Object.getPrototypeOf(event))\n return new Wrapper(eventTarget, event)\n}\n\n/**\n * Get the immediateStopped flag of a given event.\n * @param {Event} event The event to get.\n * @returns {boolean} The flag to stop propagation immediately.\n * @private\n */\nexport function isStopped(event) {\n return pd(event).immediateStopped\n}\n\n/**\n * Set the current event phase of a given event.\n * @param {Event} event The event to set current target.\n * @param {number} eventPhase New event phase.\n * @returns {void}\n * @private\n */\nexport function setEventPhase(event, eventPhase) {\n pd(event).eventPhase = eventPhase\n}\n\n/**\n * Set the current target of a given event.\n * @param {Event} event The event to set current target.\n * @param {EventTarget|null} currentTarget New current target.\n * @returns {void}\n * @private\n */\nexport function setCurrentTarget(event, currentTarget) {\n pd(event).currentTarget = currentTarget\n}\n\n/**\n * Set a passive listener of a given event.\n * @param {Event} event The event to set current target.\n * @param {Function|null} passiveListener New passive listener.\n * @returns {void}\n * @private\n */\nexport function setPassiveListener(event, passiveListener) {\n pd(event).passiveListener = passiveListener\n}\n","import {\n isStopped,\n setCurrentTarget,\n setEventPhase,\n setPassiveListener,\n wrapEvent,\n} from \"./event.mjs\"\n\n/**\n * @typedef {object} ListenerNode\n * @property {Function} listener\n * @property {1|2|3} listenerType\n * @property {boolean} passive\n * @property {boolean} once\n * @property {ListenerNode|null} next\n * @private\n */\n\n/**\n * @type {WeakMap>}\n * @private\n */\nconst listenersMap = new WeakMap()\n\n// Listener types\nconst CAPTURE = 1\nconst BUBBLE = 2\nconst ATTRIBUTE = 3\n\n/**\n * Check whether a given value is an object or not.\n * @param {any} x The value to check.\n * @returns {boolean} `true` if the value is an object.\n */\nfunction isObject(x) {\n return x !== null && typeof x === \"object\" //eslint-disable-line no-restricted-syntax\n}\n\n/**\n * Get listeners.\n * @param {EventTarget} eventTarget The event target to get.\n * @returns {Map} The listeners.\n * @private\n */\nfunction getListeners(eventTarget) {\n const listeners = listenersMap.get(eventTarget)\n if (listeners == null) {\n throw new TypeError(\n \"'this' is expected an EventTarget object, but got another value.\"\n )\n }\n return listeners\n}\n\n/**\n * Get the property descriptor for the event attribute of a given event.\n * @param {string} eventName The event name to get property descriptor.\n * @returns {PropertyDescriptor} The property descriptor.\n * @private\n */\nfunction defineEventAttributeDescriptor(eventName) {\n return {\n get() {\n const listeners = getListeners(this)\n let node = listeners.get(eventName)\n while (node != null) {\n if (node.listenerType === ATTRIBUTE) {\n return node.listener\n }\n node = node.next\n }\n return null\n },\n\n set(listener) {\n if (typeof listener !== \"function\" && !isObject(listener)) {\n listener = null // eslint-disable-line no-param-reassign\n }\n const listeners = getListeners(this)\n\n // Traverse to the tail while removing old value.\n let prev = null\n let node = listeners.get(eventName)\n while (node != null) {\n if (node.listenerType === ATTRIBUTE) {\n // Remove old value.\n if (prev !== null) {\n prev.next = node.next\n } else if (node.next !== null) {\n listeners.set(eventName, node.next)\n } else {\n listeners.delete(eventName)\n }\n } else {\n prev = node\n }\n\n node = node.next\n }\n\n // Add new value.\n if (listener !== null) {\n const newNode = {\n listener,\n listenerType: ATTRIBUTE,\n passive: false,\n once: false,\n next: null,\n }\n if (prev === null) {\n listeners.set(eventName, newNode)\n } else {\n prev.next = newNode\n }\n }\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Define an event attribute (e.g. `eventTarget.onclick`).\n * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite.\n * @param {string} eventName The event name to define.\n * @returns {void}\n */\nfunction defineEventAttribute(eventTargetPrototype, eventName) {\n Object.defineProperty(\n eventTargetPrototype,\n `on${eventName}`,\n defineEventAttributeDescriptor(eventName)\n )\n}\n\n/**\n * Define a custom EventTarget with event attributes.\n * @param {string[]} eventNames Event names for event attributes.\n * @returns {EventTarget} The custom EventTarget.\n * @private\n */\nfunction defineCustomEventTarget(eventNames) {\n /** CustomEventTarget */\n function CustomEventTarget() {\n EventTarget.call(this)\n }\n\n CustomEventTarget.prototype = Object.create(EventTarget.prototype, {\n constructor: {\n value: CustomEventTarget,\n configurable: true,\n writable: true,\n },\n })\n\n for (let i = 0; i < eventNames.length; ++i) {\n defineEventAttribute(CustomEventTarget.prototype, eventNames[i])\n }\n\n return CustomEventTarget\n}\n\n/**\n * EventTarget.\n *\n * - This is constructor if no arguments.\n * - This is a function which returns a CustomEventTarget constructor if there are arguments.\n *\n * For example:\n *\n * class A extends EventTarget {}\n * class B extends EventTarget(\"message\") {}\n * class C extends EventTarget(\"message\", \"error\") {}\n * class D extends EventTarget([\"message\", \"error\"]) {}\n */\nfunction EventTarget() {\n /*eslint-disable consistent-return */\n if (this instanceof EventTarget) {\n listenersMap.set(this, new Map())\n return\n }\n if (arguments.length === 1 && Array.isArray(arguments[0])) {\n return defineCustomEventTarget(arguments[0])\n }\n if (arguments.length > 0) {\n const types = new Array(arguments.length)\n for (let i = 0; i < arguments.length; ++i) {\n types[i] = arguments[i]\n }\n return defineCustomEventTarget(types)\n }\n throw new TypeError(\"Cannot call a class as a function\")\n /*eslint-enable consistent-return */\n}\n\n// Should be enumerable, but class methods are not enumerable.\nEventTarget.prototype = {\n /**\n * Add a given listener to this event target.\n * @param {string} eventName The event name to add.\n * @param {Function} listener The listener to add.\n * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.\n * @returns {void}\n */\n addEventListener(eventName, listener, options) {\n if (listener == null) {\n return\n }\n if (typeof listener !== \"function\" && !isObject(listener)) {\n throw new TypeError(\"'listener' should be a function or an object.\")\n }\n\n const listeners = getListeners(this)\n const optionsIsObj = isObject(options)\n const capture = optionsIsObj\n ? Boolean(options.capture)\n : Boolean(options)\n const listenerType = capture ? CAPTURE : BUBBLE\n const newNode = {\n listener,\n listenerType,\n passive: optionsIsObj && Boolean(options.passive),\n once: optionsIsObj && Boolean(options.once),\n next: null,\n }\n\n // Set it as the first node if the first node is null.\n let node = listeners.get(eventName)\n if (node === undefined) {\n listeners.set(eventName, newNode)\n return\n }\n\n // Traverse to the tail while checking duplication..\n let prev = null\n while (node != null) {\n if (\n node.listener === listener &&\n node.listenerType === listenerType\n ) {\n // Should ignore duplication.\n return\n }\n prev = node\n node = node.next\n }\n\n // Add it.\n prev.next = newNode\n },\n\n /**\n * Remove a given listener from this event target.\n * @param {string} eventName The event name to remove.\n * @param {Function} listener The listener to remove.\n * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.\n * @returns {void}\n */\n removeEventListener(eventName, listener, options) {\n if (listener == null) {\n return\n }\n\n const listeners = getListeners(this)\n const capture = isObject(options)\n ? Boolean(options.capture)\n : Boolean(options)\n const listenerType = capture ? CAPTURE : BUBBLE\n\n let prev = null\n let node = listeners.get(eventName)\n while (node != null) {\n if (\n node.listener === listener &&\n node.listenerType === listenerType\n ) {\n if (prev !== null) {\n prev.next = node.next\n } else if (node.next !== null) {\n listeners.set(eventName, node.next)\n } else {\n listeners.delete(eventName)\n }\n return\n }\n\n prev = node\n node = node.next\n }\n },\n\n /**\n * Dispatch a given event.\n * @param {Event|{type:string}} event The event to dispatch.\n * @returns {boolean} `false` if canceled.\n */\n dispatchEvent(event) {\n if (event == null || typeof event.type !== \"string\") {\n throw new TypeError('\"event.type\" should be a string.')\n }\n\n // If listeners aren't registered, terminate.\n const listeners = getListeners(this)\n const eventName = event.type\n let node = listeners.get(eventName)\n if (node == null) {\n return true\n }\n\n // Since we cannot rewrite several properties, so wrap object.\n const wrappedEvent = wrapEvent(this, event)\n\n // This doesn't process capturing phase and bubbling phase.\n // This isn't participating in a tree.\n let prev = null\n while (node != null) {\n // Remove this listener if it's once\n if (node.once) {\n if (prev !== null) {\n prev.next = node.next\n } else if (node.next !== null) {\n listeners.set(eventName, node.next)\n } else {\n listeners.delete(eventName)\n }\n } else {\n prev = node\n }\n\n // Call this listener\n setPassiveListener(\n wrappedEvent,\n node.passive ? node.listener : null\n )\n if (typeof node.listener === \"function\") {\n try {\n node.listener.call(this, wrappedEvent)\n } catch (err) {\n if (\n typeof console !== \"undefined\" &&\n typeof console.error === \"function\"\n ) {\n console.error(err)\n }\n }\n } else if (\n node.listenerType !== ATTRIBUTE &&\n typeof node.listener.handleEvent === \"function\"\n ) {\n node.listener.handleEvent(wrappedEvent)\n }\n\n // Break if `event.stopImmediatePropagation` was called.\n if (isStopped(wrappedEvent)) {\n break\n }\n\n node = node.next\n }\n setPassiveListener(wrappedEvent, null)\n setEventPhase(wrappedEvent, 0)\n setCurrentTarget(wrappedEvent, null)\n\n return !wrappedEvent.defaultPrevented\n },\n}\n\n// `constructor` is not enumerable.\nObject.defineProperty(EventTarget.prototype, \"constructor\", {\n value: EventTarget,\n configurable: true,\n writable: true,\n})\n\n// Ensure `eventTarget instanceof window.EventTarget` is `true`.\nif (\n typeof window !== \"undefined\" &&\n typeof window.EventTarget !== \"undefined\"\n) {\n Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype)\n}\n\nexport { defineEventAttribute, EventTarget }\nexport default EventTarget\n"],"names":[],"mappings":"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"} \ No newline at end of file diff --git a/node_modules/event-target-shim/dist/event-target-shim.mjs b/node_modules/event-target-shim/dist/event-target-shim.mjs new file mode 100644 index 0000000..114f3a1 --- /dev/null +++ b/node_modules/event-target-shim/dist/event-target-shim.mjs @@ -0,0 +1,862 @@ +/** + * @author Toru Nagashima + * @copyright 2015 Toru Nagashima. All rights reserved. + * See LICENSE file in root directory for full license. + */ +/** + * @typedef {object} PrivateData + * @property {EventTarget} eventTarget The event target. + * @property {{type:string}} event The original event object. + * @property {number} eventPhase The current event phase. + * @property {EventTarget|null} currentTarget The current event target. + * @property {boolean} canceled The flag to prevent default. + * @property {boolean} stopped The flag to stop propagation. + * @property {boolean} immediateStopped The flag to stop propagation immediately. + * @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null. + * @property {number} timeStamp The unix time. + * @private + */ + +/** + * Private data for event wrappers. + * @type {WeakMap} + * @private + */ +const privateData = new WeakMap(); + +/** + * Cache for wrapper classes. + * @type {WeakMap} + * @private + */ +const wrappers = new WeakMap(); + +/** + * Get private data. + * @param {Event} event The event object to get private data. + * @returns {PrivateData} The private data of the event. + * @private + */ +function pd(event) { + const retv = privateData.get(event); + console.assert( + retv != null, + "'this' is expected an Event object, but got", + event + ); + return retv +} + +/** + * https://dom.spec.whatwg.org/#set-the-canceled-flag + * @param data {PrivateData} private data. + */ +function setCancelFlag(data) { + if (data.passiveListener != null) { + if ( + typeof console !== "undefined" && + typeof console.error === "function" + ) { + console.error( + "Unable to preventDefault inside passive event listener invocation.", + data.passiveListener + ); + } + return + } + if (!data.event.cancelable) { + return + } + + data.canceled = true; + if (typeof data.event.preventDefault === "function") { + data.event.preventDefault(); + } +} + +/** + * @see https://dom.spec.whatwg.org/#interface-event + * @private + */ +/** + * The event wrapper. + * @constructor + * @param {EventTarget} eventTarget The event target of this dispatching. + * @param {Event|{type:string}} event The original event to wrap. + */ +function Event(eventTarget, event) { + privateData.set(this, { + eventTarget, + event, + eventPhase: 2, + currentTarget: eventTarget, + canceled: false, + stopped: false, + immediateStopped: false, + passiveListener: null, + timeStamp: event.timeStamp || Date.now(), + }); + + // https://heycam.github.io/webidl/#Unforgeable + Object.defineProperty(this, "isTrusted", { value: false, enumerable: true }); + + // Define accessors + const keys = Object.keys(event); + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (!(key in this)) { + Object.defineProperty(this, key, defineRedirectDescriptor(key)); + } + } +} + +// Should be enumerable, but class methods are not enumerable. +Event.prototype = { + /** + * The type of this event. + * @type {string} + */ + get type() { + return pd(this).event.type + }, + + /** + * The target of this event. + * @type {EventTarget} + */ + get target() { + return pd(this).eventTarget + }, + + /** + * The target of this event. + * @type {EventTarget} + */ + get currentTarget() { + return pd(this).currentTarget + }, + + /** + * @returns {EventTarget[]} The composed path of this event. + */ + composedPath() { + const currentTarget = pd(this).currentTarget; + if (currentTarget == null) { + return [] + } + return [currentTarget] + }, + + /** + * Constant of NONE. + * @type {number} + */ + get NONE() { + return 0 + }, + + /** + * Constant of CAPTURING_PHASE. + * @type {number} + */ + get CAPTURING_PHASE() { + return 1 + }, + + /** + * Constant of AT_TARGET. + * @type {number} + */ + get AT_TARGET() { + return 2 + }, + + /** + * Constant of BUBBLING_PHASE. + * @type {number} + */ + get BUBBLING_PHASE() { + return 3 + }, + + /** + * The target of this event. + * @type {number} + */ + get eventPhase() { + return pd(this).eventPhase + }, + + /** + * Stop event bubbling. + * @returns {void} + */ + stopPropagation() { + const data = pd(this); + + data.stopped = true; + if (typeof data.event.stopPropagation === "function") { + data.event.stopPropagation(); + } + }, + + /** + * Stop event bubbling. + * @returns {void} + */ + stopImmediatePropagation() { + const data = pd(this); + + data.stopped = true; + data.immediateStopped = true; + if (typeof data.event.stopImmediatePropagation === "function") { + data.event.stopImmediatePropagation(); + } + }, + + /** + * The flag to be bubbling. + * @type {boolean} + */ + get bubbles() { + return Boolean(pd(this).event.bubbles) + }, + + /** + * The flag to be cancelable. + * @type {boolean} + */ + get cancelable() { + return Boolean(pd(this).event.cancelable) + }, + + /** + * Cancel this event. + * @returns {void} + */ + preventDefault() { + setCancelFlag(pd(this)); + }, + + /** + * The flag to indicate cancellation state. + * @type {boolean} + */ + get defaultPrevented() { + return pd(this).canceled + }, + + /** + * The flag to be composed. + * @type {boolean} + */ + get composed() { + return Boolean(pd(this).event.composed) + }, + + /** + * The unix time of this event. + * @type {number} + */ + get timeStamp() { + return pd(this).timeStamp + }, + + /** + * The target of this event. + * @type {EventTarget} + * @deprecated + */ + get srcElement() { + return pd(this).eventTarget + }, + + /** + * The flag to stop event bubbling. + * @type {boolean} + * @deprecated + */ + get cancelBubble() { + return pd(this).stopped + }, + set cancelBubble(value) { + if (!value) { + return + } + const data = pd(this); + + data.stopped = true; + if (typeof data.event.cancelBubble === "boolean") { + data.event.cancelBubble = true; + } + }, + + /** + * The flag to indicate cancellation state. + * @type {boolean} + * @deprecated + */ + get returnValue() { + return !pd(this).canceled + }, + set returnValue(value) { + if (!value) { + setCancelFlag(pd(this)); + } + }, + + /** + * Initialize this event object. But do nothing under event dispatching. + * @param {string} type The event type. + * @param {boolean} [bubbles=false] The flag to be possible to bubble up. + * @param {boolean} [cancelable=false] The flag to be possible to cancel. + * @deprecated + */ + initEvent() { + // Do nothing. + }, +}; + +// `constructor` is not enumerable. +Object.defineProperty(Event.prototype, "constructor", { + value: Event, + configurable: true, + writable: true, +}); + +// Ensure `event instanceof window.Event` is `true`. +if (typeof window !== "undefined" && typeof window.Event !== "undefined") { + Object.setPrototypeOf(Event.prototype, window.Event.prototype); + + // Make association for wrappers. + wrappers.set(window.Event.prototype, Event); +} + +/** + * Get the property descriptor to redirect a given property. + * @param {string} key Property name to define property descriptor. + * @returns {PropertyDescriptor} The property descriptor to redirect the property. + * @private + */ +function defineRedirectDescriptor(key) { + return { + get() { + return pd(this).event[key] + }, + set(value) { + pd(this).event[key] = value; + }, + configurable: true, + enumerable: true, + } +} + +/** + * Get the property descriptor to call a given method property. + * @param {string} key Property name to define property descriptor. + * @returns {PropertyDescriptor} The property descriptor to call the method property. + * @private + */ +function defineCallDescriptor(key) { + return { + value() { + const event = pd(this).event; + return event[key].apply(event, arguments) + }, + configurable: true, + enumerable: true, + } +} + +/** + * Define new wrapper class. + * @param {Function} BaseEvent The base wrapper class. + * @param {Object} proto The prototype of the original event. + * @returns {Function} The defined wrapper class. + * @private + */ +function defineWrapper(BaseEvent, proto) { + const keys = Object.keys(proto); + if (keys.length === 0) { + return BaseEvent + } + + /** CustomEvent */ + function CustomEvent(eventTarget, event) { + BaseEvent.call(this, eventTarget, event); + } + + CustomEvent.prototype = Object.create(BaseEvent.prototype, { + constructor: { value: CustomEvent, configurable: true, writable: true }, + }); + + // Define accessors. + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (!(key in BaseEvent.prototype)) { + const descriptor = Object.getOwnPropertyDescriptor(proto, key); + const isFunc = typeof descriptor.value === "function"; + Object.defineProperty( + CustomEvent.prototype, + key, + isFunc + ? defineCallDescriptor(key) + : defineRedirectDescriptor(key) + ); + } + } + + return CustomEvent +} + +/** + * Get the wrapper class of a given prototype. + * @param {Object} proto The prototype of the original event to get its wrapper. + * @returns {Function} The wrapper class. + * @private + */ +function getWrapper(proto) { + if (proto == null || proto === Object.prototype) { + return Event + } + + let wrapper = wrappers.get(proto); + if (wrapper == null) { + wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto); + wrappers.set(proto, wrapper); + } + return wrapper +} + +/** + * Wrap a given event to management a dispatching. + * @param {EventTarget} eventTarget The event target of this dispatching. + * @param {Object} event The event to wrap. + * @returns {Event} The wrapper instance. + * @private + */ +function wrapEvent(eventTarget, event) { + const Wrapper = getWrapper(Object.getPrototypeOf(event)); + return new Wrapper(eventTarget, event) +} + +/** + * Get the immediateStopped flag of a given event. + * @param {Event} event The event to get. + * @returns {boolean} The flag to stop propagation immediately. + * @private + */ +function isStopped(event) { + return pd(event).immediateStopped +} + +/** + * Set the current event phase of a given event. + * @param {Event} event The event to set current target. + * @param {number} eventPhase New event phase. + * @returns {void} + * @private + */ +function setEventPhase(event, eventPhase) { + pd(event).eventPhase = eventPhase; +} + +/** + * Set the current target of a given event. + * @param {Event} event The event to set current target. + * @param {EventTarget|null} currentTarget New current target. + * @returns {void} + * @private + */ +function setCurrentTarget(event, currentTarget) { + pd(event).currentTarget = currentTarget; +} + +/** + * Set a passive listener of a given event. + * @param {Event} event The event to set current target. + * @param {Function|null} passiveListener New passive listener. + * @returns {void} + * @private + */ +function setPassiveListener(event, passiveListener) { + pd(event).passiveListener = passiveListener; +} + +/** + * @typedef {object} ListenerNode + * @property {Function} listener + * @property {1|2|3} listenerType + * @property {boolean} passive + * @property {boolean} once + * @property {ListenerNode|null} next + * @private + */ + +/** + * @type {WeakMap>} + * @private + */ +const listenersMap = new WeakMap(); + +// Listener types +const CAPTURE = 1; +const BUBBLE = 2; +const ATTRIBUTE = 3; + +/** + * Check whether a given value is an object or not. + * @param {any} x The value to check. + * @returns {boolean} `true` if the value is an object. + */ +function isObject(x) { + return x !== null && typeof x === "object" //eslint-disable-line no-restricted-syntax +} + +/** + * Get listeners. + * @param {EventTarget} eventTarget The event target to get. + * @returns {Map} The listeners. + * @private + */ +function getListeners(eventTarget) { + const listeners = listenersMap.get(eventTarget); + if (listeners == null) { + throw new TypeError( + "'this' is expected an EventTarget object, but got another value." + ) + } + return listeners +} + +/** + * Get the property descriptor for the event attribute of a given event. + * @param {string} eventName The event name to get property descriptor. + * @returns {PropertyDescriptor} The property descriptor. + * @private + */ +function defineEventAttributeDescriptor(eventName) { + return { + get() { + const listeners = getListeners(this); + let node = listeners.get(eventName); + while (node != null) { + if (node.listenerType === ATTRIBUTE) { + return node.listener + } + node = node.next; + } + return null + }, + + set(listener) { + if (typeof listener !== "function" && !isObject(listener)) { + listener = null; // eslint-disable-line no-param-reassign + } + const listeners = getListeners(this); + + // Traverse to the tail while removing old value. + let prev = null; + let node = listeners.get(eventName); + while (node != null) { + if (node.listenerType === ATTRIBUTE) { + // Remove old value. + if (prev !== null) { + prev.next = node.next; + } else if (node.next !== null) { + listeners.set(eventName, node.next); + } else { + listeners.delete(eventName); + } + } else { + prev = node; + } + + node = node.next; + } + + // Add new value. + if (listener !== null) { + const newNode = { + listener, + listenerType: ATTRIBUTE, + passive: false, + once: false, + next: null, + }; + if (prev === null) { + listeners.set(eventName, newNode); + } else { + prev.next = newNode; + } + } + }, + configurable: true, + enumerable: true, + } +} + +/** + * Define an event attribute (e.g. `eventTarget.onclick`). + * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite. + * @param {string} eventName The event name to define. + * @returns {void} + */ +function defineEventAttribute(eventTargetPrototype, eventName) { + Object.defineProperty( + eventTargetPrototype, + `on${eventName}`, + defineEventAttributeDescriptor(eventName) + ); +} + +/** + * Define a custom EventTarget with event attributes. + * @param {string[]} eventNames Event names for event attributes. + * @returns {EventTarget} The custom EventTarget. + * @private + */ +function defineCustomEventTarget(eventNames) { + /** CustomEventTarget */ + function CustomEventTarget() { + EventTarget.call(this); + } + + CustomEventTarget.prototype = Object.create(EventTarget.prototype, { + constructor: { + value: CustomEventTarget, + configurable: true, + writable: true, + }, + }); + + for (let i = 0; i < eventNames.length; ++i) { + defineEventAttribute(CustomEventTarget.prototype, eventNames[i]); + } + + return CustomEventTarget +} + +/** + * EventTarget. + * + * - This is constructor if no arguments. + * - This is a function which returns a CustomEventTarget constructor if there are arguments. + * + * For example: + * + * class A extends EventTarget {} + * class B extends EventTarget("message") {} + * class C extends EventTarget("message", "error") {} + * class D extends EventTarget(["message", "error"]) {} + */ +function EventTarget() { + /*eslint-disable consistent-return */ + if (this instanceof EventTarget) { + listenersMap.set(this, new Map()); + return + } + if (arguments.length === 1 && Array.isArray(arguments[0])) { + return defineCustomEventTarget(arguments[0]) + } + if (arguments.length > 0) { + const types = new Array(arguments.length); + for (let i = 0; i < arguments.length; ++i) { + types[i] = arguments[i]; + } + return defineCustomEventTarget(types) + } + throw new TypeError("Cannot call a class as a function") + /*eslint-enable consistent-return */ +} + +// Should be enumerable, but class methods are not enumerable. +EventTarget.prototype = { + /** + * Add a given listener to this event target. + * @param {string} eventName The event name to add. + * @param {Function} listener The listener to add. + * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. + * @returns {void} + */ + addEventListener(eventName, listener, options) { + if (listener == null) { + return + } + if (typeof listener !== "function" && !isObject(listener)) { + throw new TypeError("'listener' should be a function or an object.") + } + + const listeners = getListeners(this); + const optionsIsObj = isObject(options); + const capture = optionsIsObj + ? Boolean(options.capture) + : Boolean(options); + const listenerType = capture ? CAPTURE : BUBBLE; + const newNode = { + listener, + listenerType, + passive: optionsIsObj && Boolean(options.passive), + once: optionsIsObj && Boolean(options.once), + next: null, + }; + + // Set it as the first node if the first node is null. + let node = listeners.get(eventName); + if (node === undefined) { + listeners.set(eventName, newNode); + return + } + + // Traverse to the tail while checking duplication.. + let prev = null; + while (node != null) { + if ( + node.listener === listener && + node.listenerType === listenerType + ) { + // Should ignore duplication. + return + } + prev = node; + node = node.next; + } + + // Add it. + prev.next = newNode; + }, + + /** + * Remove a given listener from this event target. + * @param {string} eventName The event name to remove. + * @param {Function} listener The listener to remove. + * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. + * @returns {void} + */ + removeEventListener(eventName, listener, options) { + if (listener == null) { + return + } + + const listeners = getListeners(this); + const capture = isObject(options) + ? Boolean(options.capture) + : Boolean(options); + const listenerType = capture ? CAPTURE : BUBBLE; + + let prev = null; + let node = listeners.get(eventName); + while (node != null) { + if ( + node.listener === listener && + node.listenerType === listenerType + ) { + if (prev !== null) { + prev.next = node.next; + } else if (node.next !== null) { + listeners.set(eventName, node.next); + } else { + listeners.delete(eventName); + } + return + } + + prev = node; + node = node.next; + } + }, + + /** + * Dispatch a given event. + * @param {Event|{type:string}} event The event to dispatch. + * @returns {boolean} `false` if canceled. + */ + dispatchEvent(event) { + if (event == null || typeof event.type !== "string") { + throw new TypeError('"event.type" should be a string.') + } + + // If listeners aren't registered, terminate. + const listeners = getListeners(this); + const eventName = event.type; + let node = listeners.get(eventName); + if (node == null) { + return true + } + + // Since we cannot rewrite several properties, so wrap object. + const wrappedEvent = wrapEvent(this, event); + + // This doesn't process capturing phase and bubbling phase. + // This isn't participating in a tree. + let prev = null; + while (node != null) { + // Remove this listener if it's once + if (node.once) { + if (prev !== null) { + prev.next = node.next; + } else if (node.next !== null) { + listeners.set(eventName, node.next); + } else { + listeners.delete(eventName); + } + } else { + prev = node; + } + + // Call this listener + setPassiveListener( + wrappedEvent, + node.passive ? node.listener : null + ); + if (typeof node.listener === "function") { + try { + node.listener.call(this, wrappedEvent); + } catch (err) { + if ( + typeof console !== "undefined" && + typeof console.error === "function" + ) { + console.error(err); + } + } + } else if ( + node.listenerType !== ATTRIBUTE && + typeof node.listener.handleEvent === "function" + ) { + node.listener.handleEvent(wrappedEvent); + } + + // Break if `event.stopImmediatePropagation` was called. + if (isStopped(wrappedEvent)) { + break + } + + node = node.next; + } + setPassiveListener(wrappedEvent, null); + setEventPhase(wrappedEvent, 0); + setCurrentTarget(wrappedEvent, null); + + return !wrappedEvent.defaultPrevented + }, +}; + +// `constructor` is not enumerable. +Object.defineProperty(EventTarget.prototype, "constructor", { + value: EventTarget, + configurable: true, + writable: true, +}); + +// Ensure `eventTarget instanceof window.EventTarget` is `true`. +if ( + typeof window !== "undefined" && + typeof window.EventTarget !== "undefined" +) { + Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype); +} + +export default EventTarget; +export { defineEventAttribute, EventTarget }; +//# sourceMappingURL=event-target-shim.mjs.map diff --git a/node_modules/event-target-shim/dist/event-target-shim.mjs.map b/node_modules/event-target-shim/dist/event-target-shim.mjs.map new file mode 100644 index 0000000..57b3e8f --- /dev/null +++ b/node_modules/event-target-shim/dist/event-target-shim.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"event-target-shim.mjs","sources":["../src/event.mjs","../src/event-target.mjs"],"sourcesContent":["/**\n * @typedef {object} PrivateData\n * @property {EventTarget} eventTarget The event target.\n * @property {{type:string}} event The original event object.\n * @property {number} eventPhase The current event phase.\n * @property {EventTarget|null} currentTarget The current event target.\n * @property {boolean} canceled The flag to prevent default.\n * @property {boolean} stopped The flag to stop propagation.\n * @property {boolean} immediateStopped The flag to stop propagation immediately.\n * @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null.\n * @property {number} timeStamp The unix time.\n * @private\n */\n\n/**\n * Private data for event wrappers.\n * @type {WeakMap}\n * @private\n */\nconst privateData = new WeakMap()\n\n/**\n * Cache for wrapper classes.\n * @type {WeakMap}\n * @private\n */\nconst wrappers = new WeakMap()\n\n/**\n * Get private data.\n * @param {Event} event The event object to get private data.\n * @returns {PrivateData} The private data of the event.\n * @private\n */\nfunction pd(event) {\n const retv = privateData.get(event)\n console.assert(\n retv != null,\n \"'this' is expected an Event object, but got\",\n event\n )\n return retv\n}\n\n/**\n * https://dom.spec.whatwg.org/#set-the-canceled-flag\n * @param data {PrivateData} private data.\n */\nfunction setCancelFlag(data) {\n if (data.passiveListener != null) {\n if (\n typeof console !== \"undefined\" &&\n typeof console.error === \"function\"\n ) {\n console.error(\n \"Unable to preventDefault inside passive event listener invocation.\",\n data.passiveListener\n )\n }\n return\n }\n if (!data.event.cancelable) {\n return\n }\n\n data.canceled = true\n if (typeof data.event.preventDefault === \"function\") {\n data.event.preventDefault()\n }\n}\n\n/**\n * @see https://dom.spec.whatwg.org/#interface-event\n * @private\n */\n/**\n * The event wrapper.\n * @constructor\n * @param {EventTarget} eventTarget The event target of this dispatching.\n * @param {Event|{type:string}} event The original event to wrap.\n */\nfunction Event(eventTarget, event) {\n privateData.set(this, {\n eventTarget,\n event,\n eventPhase: 2,\n currentTarget: eventTarget,\n canceled: false,\n stopped: false,\n immediateStopped: false,\n passiveListener: null,\n timeStamp: event.timeStamp || Date.now(),\n })\n\n // https://heycam.github.io/webidl/#Unforgeable\n Object.defineProperty(this, \"isTrusted\", { value: false, enumerable: true })\n\n // Define accessors\n const keys = Object.keys(event)\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i]\n if (!(key in this)) {\n Object.defineProperty(this, key, defineRedirectDescriptor(key))\n }\n }\n}\n\n// Should be enumerable, but class methods are not enumerable.\nEvent.prototype = {\n /**\n * The type of this event.\n * @type {string}\n */\n get type() {\n return pd(this).event.type\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n */\n get target() {\n return pd(this).eventTarget\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n */\n get currentTarget() {\n return pd(this).currentTarget\n },\n\n /**\n * @returns {EventTarget[]} The composed path of this event.\n */\n composedPath() {\n const currentTarget = pd(this).currentTarget\n if (currentTarget == null) {\n return []\n }\n return [currentTarget]\n },\n\n /**\n * Constant of NONE.\n * @type {number}\n */\n get NONE() {\n return 0\n },\n\n /**\n * Constant of CAPTURING_PHASE.\n * @type {number}\n */\n get CAPTURING_PHASE() {\n return 1\n },\n\n /**\n * Constant of AT_TARGET.\n * @type {number}\n */\n get AT_TARGET() {\n return 2\n },\n\n /**\n * Constant of BUBBLING_PHASE.\n * @type {number}\n */\n get BUBBLING_PHASE() {\n return 3\n },\n\n /**\n * The target of this event.\n * @type {number}\n */\n get eventPhase() {\n return pd(this).eventPhase\n },\n\n /**\n * Stop event bubbling.\n * @returns {void}\n */\n stopPropagation() {\n const data = pd(this)\n\n data.stopped = true\n if (typeof data.event.stopPropagation === \"function\") {\n data.event.stopPropagation()\n }\n },\n\n /**\n * Stop event bubbling.\n * @returns {void}\n */\n stopImmediatePropagation() {\n const data = pd(this)\n\n data.stopped = true\n data.immediateStopped = true\n if (typeof data.event.stopImmediatePropagation === \"function\") {\n data.event.stopImmediatePropagation()\n }\n },\n\n /**\n * The flag to be bubbling.\n * @type {boolean}\n */\n get bubbles() {\n return Boolean(pd(this).event.bubbles)\n },\n\n /**\n * The flag to be cancelable.\n * @type {boolean}\n */\n get cancelable() {\n return Boolean(pd(this).event.cancelable)\n },\n\n /**\n * Cancel this event.\n * @returns {void}\n */\n preventDefault() {\n setCancelFlag(pd(this))\n },\n\n /**\n * The flag to indicate cancellation state.\n * @type {boolean}\n */\n get defaultPrevented() {\n return pd(this).canceled\n },\n\n /**\n * The flag to be composed.\n * @type {boolean}\n */\n get composed() {\n return Boolean(pd(this).event.composed)\n },\n\n /**\n * The unix time of this event.\n * @type {number}\n */\n get timeStamp() {\n return pd(this).timeStamp\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n * @deprecated\n */\n get srcElement() {\n return pd(this).eventTarget\n },\n\n /**\n * The flag to stop event bubbling.\n * @type {boolean}\n * @deprecated\n */\n get cancelBubble() {\n return pd(this).stopped\n },\n set cancelBubble(value) {\n if (!value) {\n return\n }\n const data = pd(this)\n\n data.stopped = true\n if (typeof data.event.cancelBubble === \"boolean\") {\n data.event.cancelBubble = true\n }\n },\n\n /**\n * The flag to indicate cancellation state.\n * @type {boolean}\n * @deprecated\n */\n get returnValue() {\n return !pd(this).canceled\n },\n set returnValue(value) {\n if (!value) {\n setCancelFlag(pd(this))\n }\n },\n\n /**\n * Initialize this event object. But do nothing under event dispatching.\n * @param {string} type The event type.\n * @param {boolean} [bubbles=false] The flag to be possible to bubble up.\n * @param {boolean} [cancelable=false] The flag to be possible to cancel.\n * @deprecated\n */\n initEvent() {\n // Do nothing.\n },\n}\n\n// `constructor` is not enumerable.\nObject.defineProperty(Event.prototype, \"constructor\", {\n value: Event,\n configurable: true,\n writable: true,\n})\n\n// Ensure `event instanceof window.Event` is `true`.\nif (typeof window !== \"undefined\" && typeof window.Event !== \"undefined\") {\n Object.setPrototypeOf(Event.prototype, window.Event.prototype)\n\n // Make association for wrappers.\n wrappers.set(window.Event.prototype, Event)\n}\n\n/**\n * Get the property descriptor to redirect a given property.\n * @param {string} key Property name to define property descriptor.\n * @returns {PropertyDescriptor} The property descriptor to redirect the property.\n * @private\n */\nfunction defineRedirectDescriptor(key) {\n return {\n get() {\n return pd(this).event[key]\n },\n set(value) {\n pd(this).event[key] = value\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Get the property descriptor to call a given method property.\n * @param {string} key Property name to define property descriptor.\n * @returns {PropertyDescriptor} The property descriptor to call the method property.\n * @private\n */\nfunction defineCallDescriptor(key) {\n return {\n value() {\n const event = pd(this).event\n return event[key].apply(event, arguments)\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Define new wrapper class.\n * @param {Function} BaseEvent The base wrapper class.\n * @param {Object} proto The prototype of the original event.\n * @returns {Function} The defined wrapper class.\n * @private\n */\nfunction defineWrapper(BaseEvent, proto) {\n const keys = Object.keys(proto)\n if (keys.length === 0) {\n return BaseEvent\n }\n\n /** CustomEvent */\n function CustomEvent(eventTarget, event) {\n BaseEvent.call(this, eventTarget, event)\n }\n\n CustomEvent.prototype = Object.create(BaseEvent.prototype, {\n constructor: { value: CustomEvent, configurable: true, writable: true },\n })\n\n // Define accessors.\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i]\n if (!(key in BaseEvent.prototype)) {\n const descriptor = Object.getOwnPropertyDescriptor(proto, key)\n const isFunc = typeof descriptor.value === \"function\"\n Object.defineProperty(\n CustomEvent.prototype,\n key,\n isFunc\n ? defineCallDescriptor(key)\n : defineRedirectDescriptor(key)\n )\n }\n }\n\n return CustomEvent\n}\n\n/**\n * Get the wrapper class of a given prototype.\n * @param {Object} proto The prototype of the original event to get its wrapper.\n * @returns {Function} The wrapper class.\n * @private\n */\nfunction getWrapper(proto) {\n if (proto == null || proto === Object.prototype) {\n return Event\n }\n\n let wrapper = wrappers.get(proto)\n if (wrapper == null) {\n wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto)\n wrappers.set(proto, wrapper)\n }\n return wrapper\n}\n\n/**\n * Wrap a given event to management a dispatching.\n * @param {EventTarget} eventTarget The event target of this dispatching.\n * @param {Object} event The event to wrap.\n * @returns {Event} The wrapper instance.\n * @private\n */\nexport function wrapEvent(eventTarget, event) {\n const Wrapper = getWrapper(Object.getPrototypeOf(event))\n return new Wrapper(eventTarget, event)\n}\n\n/**\n * Get the immediateStopped flag of a given event.\n * @param {Event} event The event to get.\n * @returns {boolean} The flag to stop propagation immediately.\n * @private\n */\nexport function isStopped(event) {\n return pd(event).immediateStopped\n}\n\n/**\n * Set the current event phase of a given event.\n * @param {Event} event The event to set current target.\n * @param {number} eventPhase New event phase.\n * @returns {void}\n * @private\n */\nexport function setEventPhase(event, eventPhase) {\n pd(event).eventPhase = eventPhase\n}\n\n/**\n * Set the current target of a given event.\n * @param {Event} event The event to set current target.\n * @param {EventTarget|null} currentTarget New current target.\n * @returns {void}\n * @private\n */\nexport function setCurrentTarget(event, currentTarget) {\n pd(event).currentTarget = currentTarget\n}\n\n/**\n * Set a passive listener of a given event.\n * @param {Event} event The event to set current target.\n * @param {Function|null} passiveListener New passive listener.\n * @returns {void}\n * @private\n */\nexport function setPassiveListener(event, passiveListener) {\n pd(event).passiveListener = passiveListener\n}\n","import {\n isStopped,\n setCurrentTarget,\n setEventPhase,\n setPassiveListener,\n wrapEvent,\n} from \"./event.mjs\"\n\n/**\n * @typedef {object} ListenerNode\n * @property {Function} listener\n * @property {1|2|3} listenerType\n * @property {boolean} passive\n * @property {boolean} once\n * @property {ListenerNode|null} next\n * @private\n */\n\n/**\n * @type {WeakMap>}\n * @private\n */\nconst listenersMap = new WeakMap()\n\n// Listener types\nconst CAPTURE = 1\nconst BUBBLE = 2\nconst ATTRIBUTE = 3\n\n/**\n * Check whether a given value is an object or not.\n * @param {any} x The value to check.\n * @returns {boolean} `true` if the value is an object.\n */\nfunction isObject(x) {\n return x !== null && typeof x === \"object\" //eslint-disable-line no-restricted-syntax\n}\n\n/**\n * Get listeners.\n * @param {EventTarget} eventTarget The event target to get.\n * @returns {Map} The listeners.\n * @private\n */\nfunction getListeners(eventTarget) {\n const listeners = listenersMap.get(eventTarget)\n if (listeners == null) {\n throw new TypeError(\n \"'this' is expected an EventTarget object, but got another value.\"\n )\n }\n return listeners\n}\n\n/**\n * Get the property descriptor for the event attribute of a given event.\n * @param {string} eventName The event name to get property descriptor.\n * @returns {PropertyDescriptor} The property descriptor.\n * @private\n */\nfunction defineEventAttributeDescriptor(eventName) {\n return {\n get() {\n const listeners = getListeners(this)\n let node = listeners.get(eventName)\n while (node != null) {\n if (node.listenerType === ATTRIBUTE) {\n return node.listener\n }\n node = node.next\n }\n return null\n },\n\n set(listener) {\n if (typeof listener !== \"function\" && !isObject(listener)) {\n listener = null // eslint-disable-line no-param-reassign\n }\n const listeners = getListeners(this)\n\n // Traverse to the tail while removing old value.\n let prev = null\n let node = listeners.get(eventName)\n while (node != null) {\n if (node.listenerType === ATTRIBUTE) {\n // Remove old value.\n if (prev !== null) {\n prev.next = node.next\n } else if (node.next !== null) {\n listeners.set(eventName, node.next)\n } else {\n listeners.delete(eventName)\n }\n } else {\n prev = node\n }\n\n node = node.next\n }\n\n // Add new value.\n if (listener !== null) {\n const newNode = {\n listener,\n listenerType: ATTRIBUTE,\n passive: false,\n once: false,\n next: null,\n }\n if (prev === null) {\n listeners.set(eventName, newNode)\n } else {\n prev.next = newNode\n }\n }\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Define an event attribute (e.g. `eventTarget.onclick`).\n * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite.\n * @param {string} eventName The event name to define.\n * @returns {void}\n */\nfunction defineEventAttribute(eventTargetPrototype, eventName) {\n Object.defineProperty(\n eventTargetPrototype,\n `on${eventName}`,\n defineEventAttributeDescriptor(eventName)\n )\n}\n\n/**\n * Define a custom EventTarget with event attributes.\n * @param {string[]} eventNames Event names for event attributes.\n * @returns {EventTarget} The custom EventTarget.\n * @private\n */\nfunction defineCustomEventTarget(eventNames) {\n /** CustomEventTarget */\n function CustomEventTarget() {\n EventTarget.call(this)\n }\n\n CustomEventTarget.prototype = Object.create(EventTarget.prototype, {\n constructor: {\n value: CustomEventTarget,\n configurable: true,\n writable: true,\n },\n })\n\n for (let i = 0; i < eventNames.length; ++i) {\n defineEventAttribute(CustomEventTarget.prototype, eventNames[i])\n }\n\n return CustomEventTarget\n}\n\n/**\n * EventTarget.\n *\n * - This is constructor if no arguments.\n * - This is a function which returns a CustomEventTarget constructor if there are arguments.\n *\n * For example:\n *\n * class A extends EventTarget {}\n * class B extends EventTarget(\"message\") {}\n * class C extends EventTarget(\"message\", \"error\") {}\n * class D extends EventTarget([\"message\", \"error\"]) {}\n */\nfunction EventTarget() {\n /*eslint-disable consistent-return */\n if (this instanceof EventTarget) {\n listenersMap.set(this, new Map())\n return\n }\n if (arguments.length === 1 && Array.isArray(arguments[0])) {\n return defineCustomEventTarget(arguments[0])\n }\n if (arguments.length > 0) {\n const types = new Array(arguments.length)\n for (let i = 0; i < arguments.length; ++i) {\n types[i] = arguments[i]\n }\n return defineCustomEventTarget(types)\n }\n throw new TypeError(\"Cannot call a class as a function\")\n /*eslint-enable consistent-return */\n}\n\n// Should be enumerable, but class methods are not enumerable.\nEventTarget.prototype = {\n /**\n * Add a given listener to this event target.\n * @param {string} eventName The event name to add.\n * @param {Function} listener The listener to add.\n * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.\n * @returns {void}\n */\n addEventListener(eventName, listener, options) {\n if (listener == null) {\n return\n }\n if (typeof listener !== \"function\" && !isObject(listener)) {\n throw new TypeError(\"'listener' should be a function or an object.\")\n }\n\n const listeners = getListeners(this)\n const optionsIsObj = isObject(options)\n const capture = optionsIsObj\n ? Boolean(options.capture)\n : Boolean(options)\n const listenerType = capture ? CAPTURE : BUBBLE\n const newNode = {\n listener,\n listenerType,\n passive: optionsIsObj && Boolean(options.passive),\n once: optionsIsObj && Boolean(options.once),\n next: null,\n }\n\n // Set it as the first node if the first node is null.\n let node = listeners.get(eventName)\n if (node === undefined) {\n listeners.set(eventName, newNode)\n return\n }\n\n // Traverse to the tail while checking duplication..\n let prev = null\n while (node != null) {\n if (\n node.listener === listener &&\n node.listenerType === listenerType\n ) {\n // Should ignore duplication.\n return\n }\n prev = node\n node = node.next\n }\n\n // Add it.\n prev.next = newNode\n },\n\n /**\n * Remove a given listener from this event target.\n * @param {string} eventName The event name to remove.\n * @param {Function} listener The listener to remove.\n * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.\n * @returns {void}\n */\n removeEventListener(eventName, listener, options) {\n if (listener == null) {\n return\n }\n\n const listeners = getListeners(this)\n const capture = isObject(options)\n ? Boolean(options.capture)\n : Boolean(options)\n const listenerType = capture ? CAPTURE : BUBBLE\n\n let prev = null\n let node = listeners.get(eventName)\n while (node != null) {\n if (\n node.listener === listener &&\n node.listenerType === listenerType\n ) {\n if (prev !== null) {\n prev.next = node.next\n } else if (node.next !== null) {\n listeners.set(eventName, node.next)\n } else {\n listeners.delete(eventName)\n }\n return\n }\n\n prev = node\n node = node.next\n }\n },\n\n /**\n * Dispatch a given event.\n * @param {Event|{type:string}} event The event to dispatch.\n * @returns {boolean} `false` if canceled.\n */\n dispatchEvent(event) {\n if (event == null || typeof event.type !== \"string\") {\n throw new TypeError('\"event.type\" should be a string.')\n }\n\n // If listeners aren't registered, terminate.\n const listeners = getListeners(this)\n const eventName = event.type\n let node = listeners.get(eventName)\n if (node == null) {\n return true\n }\n\n // Since we cannot rewrite several properties, so wrap object.\n const wrappedEvent = wrapEvent(this, event)\n\n // This doesn't process capturing phase and bubbling phase.\n // This isn't participating in a tree.\n let prev = null\n while (node != null) {\n // Remove this listener if it's once\n if (node.once) {\n if (prev !== null) {\n prev.next = node.next\n } else if (node.next !== null) {\n listeners.set(eventName, node.next)\n } else {\n listeners.delete(eventName)\n }\n } else {\n prev = node\n }\n\n // Call this listener\n setPassiveListener(\n wrappedEvent,\n node.passive ? node.listener : null\n )\n if (typeof node.listener === \"function\") {\n try {\n node.listener.call(this, wrappedEvent)\n } catch (err) {\n if (\n typeof console !== \"undefined\" &&\n typeof console.error === \"function\"\n ) {\n console.error(err)\n }\n }\n } else if (\n node.listenerType !== ATTRIBUTE &&\n typeof node.listener.handleEvent === \"function\"\n ) {\n node.listener.handleEvent(wrappedEvent)\n }\n\n // Break if `event.stopImmediatePropagation` was called.\n if (isStopped(wrappedEvent)) {\n break\n }\n\n node = node.next\n }\n setPassiveListener(wrappedEvent, null)\n setEventPhase(wrappedEvent, 0)\n setCurrentTarget(wrappedEvent, null)\n\n return !wrappedEvent.defaultPrevented\n },\n}\n\n// `constructor` is not enumerable.\nObject.defineProperty(EventTarget.prototype, \"constructor\", {\n value: EventTarget,\n configurable: true,\n writable: true,\n})\n\n// Ensure `eventTarget instanceof window.EventTarget` is `true`.\nif (\n typeof window !== \"undefined\" &&\n typeof window.EventTarget !== \"undefined\"\n) {\n Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype)\n}\n\nexport { defineEventAttribute, EventTarget }\nexport default EventTarget\n"],"names":[],"mappings":"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"} \ No newline at end of file diff --git a/node_modules/event-target-shim/dist/event-target-shim.umd.js b/node_modules/event-target-shim/dist/event-target-shim.umd.js new file mode 100644 index 0000000..e7cf5d4 --- /dev/null +++ b/node_modules/event-target-shim/dist/event-target-shim.umd.js @@ -0,0 +1,6 @@ +/** + * @author Toru Nagashima + * @copyright 2015 Toru Nagashima. All rights reserved. + * See LICENSE file in root directory for full license. + */(function(a,b){"object"==typeof exports&&"undefined"!=typeof module?b(exports):"function"==typeof define&&define.amd?define(["exports"],b):(a=a||self,b(a.EventTargetShim={}))})(this,function(a){"use strict";function b(a){return b="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(a){return typeof a}:function(a){return a&&"function"==typeof Symbol&&a.constructor===Symbol&&a!==Symbol.prototype?"symbol":typeof a},b(a)}function c(a){var b=u.get(a);return console.assert(null!=b,"'this' is expected an Event object, but got",a),b}function d(a){return null==a.passiveListener?void(!a.event.cancelable||(a.canceled=!0,"function"==typeof a.event.preventDefault&&a.event.preventDefault())):void("undefined"!=typeof console&&"function"==typeof console.error&&console.error("Unable to preventDefault inside passive event listener invocation.",a.passiveListener))}function e(a,b){u.set(this,{eventTarget:a,event:b,eventPhase:2,currentTarget:a,canceled:!1,stopped:!1,immediateStopped:!1,passiveListener:null,timeStamp:b.timeStamp||Date.now()}),Object.defineProperty(this,"isTrusted",{value:!1,enumerable:!0});for(var c,d=Object.keys(b),e=0;e}\n * @private\n */\nconst privateData = new WeakMap()\n\n/**\n * Cache for wrapper classes.\n * @type {WeakMap}\n * @private\n */\nconst wrappers = new WeakMap()\n\n/**\n * Get private data.\n * @param {Event} event The event object to get private data.\n * @returns {PrivateData} The private data of the event.\n * @private\n */\nfunction pd(event) {\n const retv = privateData.get(event)\n console.assert(\n retv != null,\n \"'this' is expected an Event object, but got\",\n event\n )\n return retv\n}\n\n/**\n * https://dom.spec.whatwg.org/#set-the-canceled-flag\n * @param data {PrivateData} private data.\n */\nfunction setCancelFlag(data) {\n if (data.passiveListener != null) {\n if (\n typeof console !== \"undefined\" &&\n typeof console.error === \"function\"\n ) {\n console.error(\n \"Unable to preventDefault inside passive event listener invocation.\",\n data.passiveListener\n )\n }\n return\n }\n if (!data.event.cancelable) {\n return\n }\n\n data.canceled = true\n if (typeof data.event.preventDefault === \"function\") {\n data.event.preventDefault()\n }\n}\n\n/**\n * @see https://dom.spec.whatwg.org/#interface-event\n * @private\n */\n/**\n * The event wrapper.\n * @constructor\n * @param {EventTarget} eventTarget The event target of this dispatching.\n * @param {Event|{type:string}} event The original event to wrap.\n */\nfunction Event(eventTarget, event) {\n privateData.set(this, {\n eventTarget,\n event,\n eventPhase: 2,\n currentTarget: eventTarget,\n canceled: false,\n stopped: false,\n immediateStopped: false,\n passiveListener: null,\n timeStamp: event.timeStamp || Date.now(),\n })\n\n // https://heycam.github.io/webidl/#Unforgeable\n Object.defineProperty(this, \"isTrusted\", { value: false, enumerable: true })\n\n // Define accessors\n const keys = Object.keys(event)\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i]\n if (!(key in this)) {\n Object.defineProperty(this, key, defineRedirectDescriptor(key))\n }\n }\n}\n\n// Should be enumerable, but class methods are not enumerable.\nEvent.prototype = {\n /**\n * The type of this event.\n * @type {string}\n */\n get type() {\n return pd(this).event.type\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n */\n get target() {\n return pd(this).eventTarget\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n */\n get currentTarget() {\n return pd(this).currentTarget\n },\n\n /**\n * @returns {EventTarget[]} The composed path of this event.\n */\n composedPath() {\n const currentTarget = pd(this).currentTarget\n if (currentTarget == null) {\n return []\n }\n return [currentTarget]\n },\n\n /**\n * Constant of NONE.\n * @type {number}\n */\n get NONE() {\n return 0\n },\n\n /**\n * Constant of CAPTURING_PHASE.\n * @type {number}\n */\n get CAPTURING_PHASE() {\n return 1\n },\n\n /**\n * Constant of AT_TARGET.\n * @type {number}\n */\n get AT_TARGET() {\n return 2\n },\n\n /**\n * Constant of BUBBLING_PHASE.\n * @type {number}\n */\n get BUBBLING_PHASE() {\n return 3\n },\n\n /**\n * The target of this event.\n * @type {number}\n */\n get eventPhase() {\n return pd(this).eventPhase\n },\n\n /**\n * Stop event bubbling.\n * @returns {void}\n */\n stopPropagation() {\n const data = pd(this)\n\n data.stopped = true\n if (typeof data.event.stopPropagation === \"function\") {\n data.event.stopPropagation()\n }\n },\n\n /**\n * Stop event bubbling.\n * @returns {void}\n */\n stopImmediatePropagation() {\n const data = pd(this)\n\n data.stopped = true\n data.immediateStopped = true\n if (typeof data.event.stopImmediatePropagation === \"function\") {\n data.event.stopImmediatePropagation()\n }\n },\n\n /**\n * The flag to be bubbling.\n * @type {boolean}\n */\n get bubbles() {\n return Boolean(pd(this).event.bubbles)\n },\n\n /**\n * The flag to be cancelable.\n * @type {boolean}\n */\n get cancelable() {\n return Boolean(pd(this).event.cancelable)\n },\n\n /**\n * Cancel this event.\n * @returns {void}\n */\n preventDefault() {\n setCancelFlag(pd(this))\n },\n\n /**\n * The flag to indicate cancellation state.\n * @type {boolean}\n */\n get defaultPrevented() {\n return pd(this).canceled\n },\n\n /**\n * The flag to be composed.\n * @type {boolean}\n */\n get composed() {\n return Boolean(pd(this).event.composed)\n },\n\n /**\n * The unix time of this event.\n * @type {number}\n */\n get timeStamp() {\n return pd(this).timeStamp\n },\n\n /**\n * The target of this event.\n * @type {EventTarget}\n * @deprecated\n */\n get srcElement() {\n return pd(this).eventTarget\n },\n\n /**\n * The flag to stop event bubbling.\n * @type {boolean}\n * @deprecated\n */\n get cancelBubble() {\n return pd(this).stopped\n },\n set cancelBubble(value) {\n if (!value) {\n return\n }\n const data = pd(this)\n\n data.stopped = true\n if (typeof data.event.cancelBubble === \"boolean\") {\n data.event.cancelBubble = true\n }\n },\n\n /**\n * The flag to indicate cancellation state.\n * @type {boolean}\n * @deprecated\n */\n get returnValue() {\n return !pd(this).canceled\n },\n set returnValue(value) {\n if (!value) {\n setCancelFlag(pd(this))\n }\n },\n\n /**\n * Initialize this event object. But do nothing under event dispatching.\n * @param {string} type The event type.\n * @param {boolean} [bubbles=false] The flag to be possible to bubble up.\n * @param {boolean} [cancelable=false] The flag to be possible to cancel.\n * @deprecated\n */\n initEvent() {\n // Do nothing.\n },\n}\n\n// `constructor` is not enumerable.\nObject.defineProperty(Event.prototype, \"constructor\", {\n value: Event,\n configurable: true,\n writable: true,\n})\n\n// Ensure `event instanceof window.Event` is `true`.\nif (typeof window !== \"undefined\" && typeof window.Event !== \"undefined\") {\n Object.setPrototypeOf(Event.prototype, window.Event.prototype)\n\n // Make association for wrappers.\n wrappers.set(window.Event.prototype, Event)\n}\n\n/**\n * Get the property descriptor to redirect a given property.\n * @param {string} key Property name to define property descriptor.\n * @returns {PropertyDescriptor} The property descriptor to redirect the property.\n * @private\n */\nfunction defineRedirectDescriptor(key) {\n return {\n get() {\n return pd(this).event[key]\n },\n set(value) {\n pd(this).event[key] = value\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Get the property descriptor to call a given method property.\n * @param {string} key Property name to define property descriptor.\n * @returns {PropertyDescriptor} The property descriptor to call the method property.\n * @private\n */\nfunction defineCallDescriptor(key) {\n return {\n value() {\n const event = pd(this).event\n return event[key].apply(event, arguments)\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Define new wrapper class.\n * @param {Function} BaseEvent The base wrapper class.\n * @param {Object} proto The prototype of the original event.\n * @returns {Function} The defined wrapper class.\n * @private\n */\nfunction defineWrapper(BaseEvent, proto) {\n const keys = Object.keys(proto)\n if (keys.length === 0) {\n return BaseEvent\n }\n\n /** CustomEvent */\n function CustomEvent(eventTarget, event) {\n BaseEvent.call(this, eventTarget, event)\n }\n\n CustomEvent.prototype = Object.create(BaseEvent.prototype, {\n constructor: { value: CustomEvent, configurable: true, writable: true },\n })\n\n // Define accessors.\n for (let i = 0; i < keys.length; ++i) {\n const key = keys[i]\n if (!(key in BaseEvent.prototype)) {\n const descriptor = Object.getOwnPropertyDescriptor(proto, key)\n const isFunc = typeof descriptor.value === \"function\"\n Object.defineProperty(\n CustomEvent.prototype,\n key,\n isFunc\n ? defineCallDescriptor(key)\n : defineRedirectDescriptor(key)\n )\n }\n }\n\n return CustomEvent\n}\n\n/**\n * Get the wrapper class of a given prototype.\n * @param {Object} proto The prototype of the original event to get its wrapper.\n * @returns {Function} The wrapper class.\n * @private\n */\nfunction getWrapper(proto) {\n if (proto == null || proto === Object.prototype) {\n return Event\n }\n\n let wrapper = wrappers.get(proto)\n if (wrapper == null) {\n wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto)\n wrappers.set(proto, wrapper)\n }\n return wrapper\n}\n\n/**\n * Wrap a given event to management a dispatching.\n * @param {EventTarget} eventTarget The event target of this dispatching.\n * @param {Object} event The event to wrap.\n * @returns {Event} The wrapper instance.\n * @private\n */\nexport function wrapEvent(eventTarget, event) {\n const Wrapper = getWrapper(Object.getPrototypeOf(event))\n return new Wrapper(eventTarget, event)\n}\n\n/**\n * Get the immediateStopped flag of a given event.\n * @param {Event} event The event to get.\n * @returns {boolean} The flag to stop propagation immediately.\n * @private\n */\nexport function isStopped(event) {\n return pd(event).immediateStopped\n}\n\n/**\n * Set the current event phase of a given event.\n * @param {Event} event The event to set current target.\n * @param {number} eventPhase New event phase.\n * @returns {void}\n * @private\n */\nexport function setEventPhase(event, eventPhase) {\n pd(event).eventPhase = eventPhase\n}\n\n/**\n * Set the current target of a given event.\n * @param {Event} event The event to set current target.\n * @param {EventTarget|null} currentTarget New current target.\n * @returns {void}\n * @private\n */\nexport function setCurrentTarget(event, currentTarget) {\n pd(event).currentTarget = currentTarget\n}\n\n/**\n * Set a passive listener of a given event.\n * @param {Event} event The event to set current target.\n * @param {Function|null} passiveListener New passive listener.\n * @returns {void}\n * @private\n */\nexport function setPassiveListener(event, passiveListener) {\n pd(event).passiveListener = passiveListener\n}\n","import {\n isStopped,\n setCurrentTarget,\n setEventPhase,\n setPassiveListener,\n wrapEvent,\n} from \"./event.mjs\"\n\n/**\n * @typedef {object} ListenerNode\n * @property {Function} listener\n * @property {1|2|3} listenerType\n * @property {boolean} passive\n * @property {boolean} once\n * @property {ListenerNode|null} next\n * @private\n */\n\n/**\n * @type {WeakMap>}\n * @private\n */\nconst listenersMap = new WeakMap()\n\n// Listener types\nconst CAPTURE = 1\nconst BUBBLE = 2\nconst ATTRIBUTE = 3\n\n/**\n * Check whether a given value is an object or not.\n * @param {any} x The value to check.\n * @returns {boolean} `true` if the value is an object.\n */\nfunction isObject(x) {\n return x !== null && typeof x === \"object\" //eslint-disable-line no-restricted-syntax\n}\n\n/**\n * Get listeners.\n * @param {EventTarget} eventTarget The event target to get.\n * @returns {Map} The listeners.\n * @private\n */\nfunction getListeners(eventTarget) {\n const listeners = listenersMap.get(eventTarget)\n if (listeners == null) {\n throw new TypeError(\n \"'this' is expected an EventTarget object, but got another value.\"\n )\n }\n return listeners\n}\n\n/**\n * Get the property descriptor for the event attribute of a given event.\n * @param {string} eventName The event name to get property descriptor.\n * @returns {PropertyDescriptor} The property descriptor.\n * @private\n */\nfunction defineEventAttributeDescriptor(eventName) {\n return {\n get() {\n const listeners = getListeners(this)\n let node = listeners.get(eventName)\n while (node != null) {\n if (node.listenerType === ATTRIBUTE) {\n return node.listener\n }\n node = node.next\n }\n return null\n },\n\n set(listener) {\n if (typeof listener !== \"function\" && !isObject(listener)) {\n listener = null // eslint-disable-line no-param-reassign\n }\n const listeners = getListeners(this)\n\n // Traverse to the tail while removing old value.\n let prev = null\n let node = listeners.get(eventName)\n while (node != null) {\n if (node.listenerType === ATTRIBUTE) {\n // Remove old value.\n if (prev !== null) {\n prev.next = node.next\n } else if (node.next !== null) {\n listeners.set(eventName, node.next)\n } else {\n listeners.delete(eventName)\n }\n } else {\n prev = node\n }\n\n node = node.next\n }\n\n // Add new value.\n if (listener !== null) {\n const newNode = {\n listener,\n listenerType: ATTRIBUTE,\n passive: false,\n once: false,\n next: null,\n }\n if (prev === null) {\n listeners.set(eventName, newNode)\n } else {\n prev.next = newNode\n }\n }\n },\n configurable: true,\n enumerable: true,\n }\n}\n\n/**\n * Define an event attribute (e.g. `eventTarget.onclick`).\n * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite.\n * @param {string} eventName The event name to define.\n * @returns {void}\n */\nfunction defineEventAttribute(eventTargetPrototype, eventName) {\n Object.defineProperty(\n eventTargetPrototype,\n `on${eventName}`,\n defineEventAttributeDescriptor(eventName)\n )\n}\n\n/**\n * Define a custom EventTarget with event attributes.\n * @param {string[]} eventNames Event names for event attributes.\n * @returns {EventTarget} The custom EventTarget.\n * @private\n */\nfunction defineCustomEventTarget(eventNames) {\n /** CustomEventTarget */\n function CustomEventTarget() {\n EventTarget.call(this)\n }\n\n CustomEventTarget.prototype = Object.create(EventTarget.prototype, {\n constructor: {\n value: CustomEventTarget,\n configurable: true,\n writable: true,\n },\n })\n\n for (let i = 0; i < eventNames.length; ++i) {\n defineEventAttribute(CustomEventTarget.prototype, eventNames[i])\n }\n\n return CustomEventTarget\n}\n\n/**\n * EventTarget.\n *\n * - This is constructor if no arguments.\n * - This is a function which returns a CustomEventTarget constructor if there are arguments.\n *\n * For example:\n *\n * class A extends EventTarget {}\n * class B extends EventTarget(\"message\") {}\n * class C extends EventTarget(\"message\", \"error\") {}\n * class D extends EventTarget([\"message\", \"error\"]) {}\n */\nfunction EventTarget() {\n /*eslint-disable consistent-return */\n if (this instanceof EventTarget) {\n listenersMap.set(this, new Map())\n return\n }\n if (arguments.length === 1 && Array.isArray(arguments[0])) {\n return defineCustomEventTarget(arguments[0])\n }\n if (arguments.length > 0) {\n const types = new Array(arguments.length)\n for (let i = 0; i < arguments.length; ++i) {\n types[i] = arguments[i]\n }\n return defineCustomEventTarget(types)\n }\n throw new TypeError(\"Cannot call a class as a function\")\n /*eslint-enable consistent-return */\n}\n\n// Should be enumerable, but class methods are not enumerable.\nEventTarget.prototype = {\n /**\n * Add a given listener to this event target.\n * @param {string} eventName The event name to add.\n * @param {Function} listener The listener to add.\n * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.\n * @returns {void}\n */\n addEventListener(eventName, listener, options) {\n if (listener == null) {\n return\n }\n if (typeof listener !== \"function\" && !isObject(listener)) {\n throw new TypeError(\"'listener' should be a function or an object.\")\n }\n\n const listeners = getListeners(this)\n const optionsIsObj = isObject(options)\n const capture = optionsIsObj\n ? Boolean(options.capture)\n : Boolean(options)\n const listenerType = capture ? CAPTURE : BUBBLE\n const newNode = {\n listener,\n listenerType,\n passive: optionsIsObj && Boolean(options.passive),\n once: optionsIsObj && Boolean(options.once),\n next: null,\n }\n\n // Set it as the first node if the first node is null.\n let node = listeners.get(eventName)\n if (node === undefined) {\n listeners.set(eventName, newNode)\n return\n }\n\n // Traverse to the tail while checking duplication..\n let prev = null\n while (node != null) {\n if (\n node.listener === listener &&\n node.listenerType === listenerType\n ) {\n // Should ignore duplication.\n return\n }\n prev = node\n node = node.next\n }\n\n // Add it.\n prev.next = newNode\n },\n\n /**\n * Remove a given listener from this event target.\n * @param {string} eventName The event name to remove.\n * @param {Function} listener The listener to remove.\n * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener.\n * @returns {void}\n */\n removeEventListener(eventName, listener, options) {\n if (listener == null) {\n return\n }\n\n const listeners = getListeners(this)\n const capture = isObject(options)\n ? Boolean(options.capture)\n : Boolean(options)\n const listenerType = capture ? CAPTURE : BUBBLE\n\n let prev = null\n let node = listeners.get(eventName)\n while (node != null) {\n if (\n node.listener === listener &&\n node.listenerType === listenerType\n ) {\n if (prev !== null) {\n prev.next = node.next\n } else if (node.next !== null) {\n listeners.set(eventName, node.next)\n } else {\n listeners.delete(eventName)\n }\n return\n }\n\n prev = node\n node = node.next\n }\n },\n\n /**\n * Dispatch a given event.\n * @param {Event|{type:string}} event The event to dispatch.\n * @returns {boolean} `false` if canceled.\n */\n dispatchEvent(event) {\n if (event == null || typeof event.type !== \"string\") {\n throw new TypeError('\"event.type\" should be a string.')\n }\n\n // If listeners aren't registered, terminate.\n const listeners = getListeners(this)\n const eventName = event.type\n let node = listeners.get(eventName)\n if (node == null) {\n return true\n }\n\n // Since we cannot rewrite several properties, so wrap object.\n const wrappedEvent = wrapEvent(this, event)\n\n // This doesn't process capturing phase and bubbling phase.\n // This isn't participating in a tree.\n let prev = null\n while (node != null) {\n // Remove this listener if it's once\n if (node.once) {\n if (prev !== null) {\n prev.next = node.next\n } else if (node.next !== null) {\n listeners.set(eventName, node.next)\n } else {\n listeners.delete(eventName)\n }\n } else {\n prev = node\n }\n\n // Call this listener\n setPassiveListener(\n wrappedEvent,\n node.passive ? node.listener : null\n )\n if (typeof node.listener === \"function\") {\n try {\n node.listener.call(this, wrappedEvent)\n } catch (err) {\n if (\n typeof console !== \"undefined\" &&\n typeof console.error === \"function\"\n ) {\n console.error(err)\n }\n }\n } else if (\n node.listenerType !== ATTRIBUTE &&\n typeof node.listener.handleEvent === \"function\"\n ) {\n node.listener.handleEvent(wrappedEvent)\n }\n\n // Break if `event.stopImmediatePropagation` was called.\n if (isStopped(wrappedEvent)) {\n break\n }\n\n node = node.next\n }\n setPassiveListener(wrappedEvent, null)\n setEventPhase(wrappedEvent, 0)\n setCurrentTarget(wrappedEvent, null)\n\n return !wrappedEvent.defaultPrevented\n },\n}\n\n// `constructor` is not enumerable.\nObject.defineProperty(EventTarget.prototype, \"constructor\", {\n value: EventTarget,\n configurable: true,\n writable: true,\n})\n\n// Ensure `eventTarget instanceof window.EventTarget` is `true`.\nif (\n typeof window !== \"undefined\" &&\n typeof window.EventTarget !== \"undefined\"\n) {\n Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype)\n}\n\nexport { defineEventAttribute, EventTarget }\nexport default EventTarget\n"],"names":["pd","event","retv","privateData","get","console","assert","setCancelFlag","data","passiveListener","cancelable","canceled","preventDefault","error","Event","eventTarget","set","eventPhase","currentTarget","stopped","immediateStopped","timeStamp","Date","now","Object","defineProperty","value","enumerable","key","keys","i","length","defineRedirectDescriptor","configurable","defineCallDescriptor","apply","arguments","defineWrapper","BaseEvent","proto","CustomEvent","call","prototype","create","constructor","writable","descriptor","getOwnPropertyDescriptor","isFunc","getWrapper","wrapper","wrappers","getPrototypeOf","wrapEvent","Wrapper","isStopped","setEventPhase","setCurrentTarget","setPassiveListener","isObject","x","_typeof","getListeners","listeners","listenersMap","TypeError","defineEventAttributeDescriptor","eventName","node","listenerType","listener","next","prev","delete","newNode","passive","once","defineEventAttribute","eventTargetPrototype","defineCustomEventTarget","eventNames","CustomEventTarget","EventTarget","Map","Array","isArray","types","WeakMap","type","target","composedPath","NONE","CAPTURING_PHASE","AT_TARGET","BUBBLING_PHASE","stopPropagation","stopImmediatePropagation","bubbles","defaultPrevented","composed","srcElement","cancelBubble","returnValue","initEvent","window","setPrototypeOf","CAPTURE","BUBBLE","addEventListener","options","optionsIsObj","capture","removeEventListener","dispatchEvent","wrappedEvent","err","handleEvent"],"mappings":"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"} \ No newline at end of file diff --git a/node_modules/event-target-shim/index.d.ts b/node_modules/event-target-shim/index.d.ts new file mode 100644 index 0000000..a303097 --- /dev/null +++ b/node_modules/event-target-shim/index.d.ts @@ -0,0 +1,399 @@ +export as namespace EventTargetShim + +/** + * `Event` interface. + * @see https://dom.spec.whatwg.org/#event + */ +export interface Event { + /** + * The type of this event. + */ + readonly type: string + + /** + * The target of this event. + */ + readonly target: EventTarget<{}, {}, "standard"> | null + + /** + * The current target of this event. + */ + readonly currentTarget: EventTarget<{}, {}, "standard"> | null + + /** + * The target of this event. + * @deprecated + */ + readonly srcElement: any | null + + /** + * The composed path of this event. + */ + composedPath(): EventTarget<{}, {}, "standard">[] + + /** + * Constant of NONE. + */ + readonly NONE: number + + /** + * Constant of CAPTURING_PHASE. + */ + readonly CAPTURING_PHASE: number + + /** + * Constant of BUBBLING_PHASE. + */ + readonly BUBBLING_PHASE: number + + /** + * Constant of AT_TARGET. + */ + readonly AT_TARGET: number + + /** + * Indicates which phase of the event flow is currently being evaluated. + */ + readonly eventPhase: number + + /** + * Stop event bubbling. + */ + stopPropagation(): void + + /** + * Stop event bubbling. + */ + stopImmediatePropagation(): void + + /** + * Initialize event. + * @deprecated + */ + initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void + + /** + * The flag indicating bubbling. + */ + readonly bubbles: boolean + + /** + * Stop event bubbling. + * @deprecated + */ + cancelBubble: boolean + + /** + * Set or get cancellation flag. + * @deprecated + */ + returnValue: boolean + + /** + * The flag indicating whether the event can be canceled. + */ + readonly cancelable: boolean + + /** + * Cancel this event. + */ + preventDefault(): void + + /** + * The flag to indicating whether the event was canceled. + */ + readonly defaultPrevented: boolean + + /** + * The flag to indicating if event is composed. + */ + readonly composed: boolean + + /** + * Indicates whether the event was dispatched by the user agent. + */ + readonly isTrusted: boolean + + /** + * The unix time of this event. + */ + readonly timeStamp: number +} + +/** + * The constructor of `EventTarget` interface. + */ +export type EventTargetConstructor< + TEvents extends EventTarget.EventDefinition = {}, + TEventAttributes extends EventTarget.EventDefinition = {}, + TMode extends EventTarget.Mode = "loose" +> = { + prototype: EventTarget + new(): EventTarget +} + +/** + * `EventTarget` interface. + * @see https://dom.spec.whatwg.org/#interface-eventtarget + */ +export type EventTarget< + TEvents extends EventTarget.EventDefinition = {}, + TEventAttributes extends EventTarget.EventDefinition = {}, + TMode extends EventTarget.Mode = "loose" +> = EventTarget.EventAttributes & { + /** + * Add a given listener to this event target. + * @param eventName The event name to add. + * @param listener The listener to add. + * @param options The options for this listener. + */ + addEventListener>( + type: TEventType, + listener: + | EventTarget.Listener> + | null, + options?: boolean | EventTarget.AddOptions + ): void + + /** + * Remove a given listener from this event target. + * @param eventName The event name to remove. + * @param listener The listener to remove. + * @param options The options for this listener. + */ + removeEventListener>( + type: TEventType, + listener: + | EventTarget.Listener> + | null, + options?: boolean | EventTarget.RemoveOptions + ): void + + /** + * Dispatch a given event. + * @param event The event to dispatch. + * @returns `false` if canceled. + */ + dispatchEvent>( + event: EventTarget.EventData + ): boolean +} + +export const EventTarget: EventTargetConstructor & { + /** + * Create an `EventTarget` instance with detailed event definition. + * + * The detailed event definition requires to use `defineEventAttribute()` + * function later. + * + * Unfortunately, the second type parameter `TEventAttributes` was needed + * because we cannot compute string literal types. + * + * @example + * const signal = new EventTarget<{ abort: Event }, { onabort: Event }>() + * defineEventAttribute(signal, "abort") + */ + new < + TEvents extends EventTarget.EventDefinition, + TEventAttributes extends EventTarget.EventDefinition, + TMode extends EventTarget.Mode = "loose" + >(): EventTarget + + /** + * Define an `EventTarget` constructor with attribute events and detailed event definition. + * + * Unfortunately, the second type parameter `TEventAttributes` was needed + * because we cannot compute string literal types. + * + * @example + * class AbortSignal extends EventTarget<{ abort: Event }, { onabort: Event }>("abort") { + * abort(): void {} + * } + * + * @param events Optional event attributes (e.g. passing in `"click"` adds `onclick` to prototype). + */ + < + TEvents extends EventTarget.EventDefinition = {}, + TEventAttributes extends EventTarget.EventDefinition = {}, + TMode extends EventTarget.Mode = "loose" + >(events: string[]): EventTargetConstructor< + TEvents, + TEventAttributes, + TMode + > + + /** + * Define an `EventTarget` constructor with attribute events and detailed event definition. + * + * Unfortunately, the second type parameter `TEventAttributes` was needed + * because we cannot compute string literal types. + * + * @example + * class AbortSignal extends EventTarget<{ abort: Event }, { onabort: Event }>("abort") { + * abort(): void {} + * } + * + * @param events Optional event attributes (e.g. passing in `"click"` adds `onclick` to prototype). + */ + < + TEvents extends EventTarget.EventDefinition = {}, + TEventAttributes extends EventTarget.EventDefinition = {}, + TMode extends EventTarget.Mode = "loose" + >(event0: string, ...events: string[]): EventTargetConstructor< + TEvents, + TEventAttributes, + TMode + > +} + +export namespace EventTarget { + /** + * Options of `removeEventListener()` method. + */ + export interface RemoveOptions { + /** + * The flag to indicate that the listener is for the capturing phase. + */ + capture?: boolean + } + + /** + * Options of `addEventListener()` method. + */ + export interface AddOptions extends RemoveOptions { + /** + * The flag to indicate that the listener doesn't support + * `event.preventDefault()` operation. + */ + passive?: boolean + /** + * The flag to indicate that the listener will be removed on the first + * event. + */ + once?: boolean + } + + /** + * The type of regular listeners. + */ + export interface FunctionListener { + (event: TEvent): void + } + + /** + * The type of object listeners. + */ + export interface ObjectListener { + handleEvent(event: TEvent): void + } + + /** + * The type of listeners. + */ + export type Listener = + | FunctionListener + | ObjectListener + + /** + * Event definition. + */ + export type EventDefinition = { + readonly [key: string]: Event + } + + /** + * Mapped type for event attributes. + */ + export type EventAttributes = { + [P in keyof TEventAttributes]: + | FunctionListener + | null + } + + /** + * The type of event data for `dispatchEvent()` method. + */ + export type EventData< + TEvents extends EventDefinition, + TEventType extends keyof TEvents | string, + TMode extends Mode + > = + TEventType extends keyof TEvents + ? ( + // Require properties which are not generated automatically. + & Pick< + TEvents[TEventType], + Exclude + > + // Properties which are generated automatically are optional. + & Partial> + ) + : ( + TMode extends "standard" + ? Event + : Event | NonStandardEvent + ) + + /** + * The string literal types of the properties which are generated + * automatically in `dispatchEvent()` method. + */ + export type OmittableEventKeys = Exclude + + /** + * The type of event data. + */ + export type NonStandardEvent = { + [key: string]: any + type: string + } + + /** + * The type of listeners. + */ + export type PickEvent< + TEvents extends EventDefinition, + TEventType extends keyof TEvents | string, + > = + TEventType extends keyof TEvents + ? TEvents[TEventType] + : Event + + /** + * Event type candidates. + */ + export type EventType< + TEvents extends EventDefinition, + TMode extends Mode + > = + TMode extends "strict" + ? keyof TEvents + : keyof TEvents | string + + /** + * - `"strict"` ..... Methods don't accept unknown events. + * `dispatchEvent()` accepts partial objects. + * - `"loose"` ...... Methods accept unknown events. + * `dispatchEvent()` accepts partial objects. + * - `"standard"` ... Methods accept unknown events. + * `dispatchEvent()` doesn't accept partial objects. + */ + export type Mode = "strict" | "standard" | "loose" +} + +/** + * Specialized `type` property. + */ +export type Type = { type: T } + +/** + * Define an event attribute (e.g. `eventTarget.onclick`). + * @param prototype The event target prototype to define an event attribute. + * @param eventName The event name to define. + */ +export function defineEventAttribute( + prototype: EventTarget, + eventName: string +): void + +export default EventTarget diff --git a/node_modules/event-target-shim/package.json b/node_modules/event-target-shim/package.json new file mode 100644 index 0000000..148085c --- /dev/null +++ b/node_modules/event-target-shim/package.json @@ -0,0 +1,109 @@ +{ + "_from": "event-target-shim@^5.0.0", + "_id": "event-target-shim@5.0.1", + "_inBundle": false, + "_integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==", + "_location": "/event-target-shim", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "event-target-shim@^5.0.0", + "name": "event-target-shim", + "escapedName": "event-target-shim", + "rawSpec": "^5.0.0", + "saveSpec": null, + "fetchSpec": "^5.0.0" + }, + "_requiredBy": [ + "/abort-controller" + ], + "_resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", + "_shasum": "5d4d3ebdf9583d63a5333ce2deb7480ab2b05789", + "_spec": "event-target-shim@^5.0.0", + "_where": "/Users/cday/Code/zendesk/fetch-build-from-gcb/node_modules/abort-controller", + "author": { + "name": "Toru Nagashima" + }, + "bugs": { + "url": "https://github.com/mysticatea/event-target-shim/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "An implementation of WHATWG EventTarget interface.", + "devDependencies": { + "@babel/core": "^7.2.2", + "@babel/plugin-transform-modules-commonjs": "^7.2.0", + "@babel/preset-env": "^7.2.3", + "@babel/register": "^7.0.0", + "@mysticatea/eslint-plugin": "^8.0.1", + "@mysticatea/spy": "^0.1.2", + "assert": "^1.4.1", + "codecov": "^3.1.0", + "eslint": "^5.12.1", + "karma": "^3.1.4", + "karma-chrome-launcher": "^2.2.0", + "karma-coverage": "^1.1.2", + "karma-firefox-launcher": "^1.0.0", + "karma-growl-reporter": "^1.0.0", + "karma-ie-launcher": "^1.0.0", + "karma-mocha": "^1.3.0", + "karma-rollup-preprocessor": "^7.0.0-rc.2", + "mocha": "^5.2.0", + "npm-run-all": "^4.1.5", + "nyc": "^13.1.0", + "opener": "^1.5.1", + "rimraf": "^2.6.3", + "rollup": "^1.1.1", + "rollup-plugin-babel": "^4.3.2", + "rollup-plugin-babel-minify": "^7.0.0", + "rollup-plugin-commonjs": "^9.2.0", + "rollup-plugin-json": "^3.1.0", + "rollup-plugin-node-resolve": "^4.0.0", + "rollup-watch": "^4.3.1", + "type-tester": "^1.0.0", + "typescript": "^3.2.4" + }, + "engines": { + "node": ">=6" + }, + "files": [ + "dist", + "index.d.ts" + ], + "homepage": "https://github.com/mysticatea/event-target-shim", + "keywords": [ + "w3c", + "whatwg", + "eventtarget", + "event", + "events", + "shim" + ], + "license": "MIT", + "main": "dist/event-target-shim", + "name": "event-target-shim", + "repository": { + "type": "git", + "url": "git+https://github.com/mysticatea/event-target-shim.git" + }, + "scripts": { + "build": "rollup -c scripts/rollup.config.js", + "clean": "rimraf .nyc_output coverage", + "codecov": "codecov", + "coverage": "nyc report --reporter lcov && opener coverage/lcov-report/index.html", + "lint": "eslint src test scripts --ext .js,.mjs", + "postversion": "git push && git push --tags", + "pretest": "npm run lint", + "preversion": "npm test", + "test": "run-s test:*", + "test:karma": "karma start scripts/karma.conf.js --single-run", + "test:mocha": "nyc --require ./scripts/babel-register mocha test/*.mjs", + "version": "npm run build && git add dist/*", + "watch": "run-p watch:*", + "watch:karma": "karma start scripts/karma.conf.js --watch", + "watch:mocha": "mocha test/*.mjs --require ./scripts/babel-register --watch --watch-extensions js,mjs --growl" + }, + "types": "index.d.ts", + "version": "5.0.1" +} diff --git a/node_modules/extend/.editorconfig b/node_modules/extend/.editorconfig new file mode 100644 index 0000000..bc228f8 --- /dev/null +++ b/node_modules/extend/.editorconfig @@ -0,0 +1,20 @@ +root = true + +[*] +indent_style = tab +indent_size = 4 +end_of_line = lf +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +max_line_length = 150 + +[CHANGELOG.md] +indent_style = space +indent_size = 2 + +[*.json] +max_line_length = off + +[Makefile] +max_line_length = off diff --git a/node_modules/extend/.eslintrc b/node_modules/extend/.eslintrc new file mode 100644 index 0000000..a34cf28 --- /dev/null +++ b/node_modules/extend/.eslintrc @@ -0,0 +1,17 @@ +{ + "root": true, + + "extends": "@ljharb", + + "rules": { + "complexity": [2, 20], + "eqeqeq": [2, "allow-null"], + "func-name-matching": [1], + "max-depth": [1, 4], + "max-statements": [2, 26], + "no-extra-parens": [1], + "no-magic-numbers": [0], + "no-restricted-syntax": [2, "BreakStatement", "ContinueStatement", "DebuggerStatement", "LabeledStatement", "WithStatement"], + "sort-keys": [0], + } +} diff --git a/node_modules/extend/.jscs.json b/node_modules/extend/.jscs.json new file mode 100644 index 0000000..3cce01d --- /dev/null +++ b/node_modules/extend/.jscs.json @@ -0,0 +1,175 @@ +{ + "es3": true, + + "additionalRules": [], + + "requireSemicolons": true, + + "disallowMultipleSpaces": true, + + "disallowIdentifierNames": [], + + "requireCurlyBraces": { + "allExcept": [], + "keywords": ["if", "else", "for", "while", "do", "try", "catch"] + }, + + "requireSpaceAfterKeywords": ["if", "else", "for", "while", "do", "switch", "return", "try", "catch", "function"], + + "disallowSpaceAfterKeywords": [], + + "disallowSpaceBeforeComma": true, + "disallowSpaceAfterComma": false, + "disallowSpaceBeforeSemicolon": true, + + "disallowNodeTypes": [ + "DebuggerStatement", + "LabeledStatement", + "SwitchCase", + "SwitchStatement", + "WithStatement" + ], + + "requireObjectKeysOnNewLine": { "allExcept": ["sameLine"] }, + + "requireSpacesInAnonymousFunctionExpression": { "beforeOpeningRoundBrace": true, "beforeOpeningCurlyBrace": true }, + "requireSpacesInNamedFunctionExpression": { "beforeOpeningCurlyBrace": true }, + "disallowSpacesInNamedFunctionExpression": { "beforeOpeningRoundBrace": true }, + "requireSpacesInFunctionDeclaration": { "beforeOpeningCurlyBrace": true }, + "disallowSpacesInFunctionDeclaration": { "beforeOpeningRoundBrace": true }, + + "requireSpaceBetweenArguments": true, + + "disallowSpacesInsideParentheses": true, + + "disallowSpacesInsideArrayBrackets": true, + + "disallowQuotedKeysInObjects": { "allExcept": ["reserved"] }, + + "disallowSpaceAfterObjectKeys": true, + + "requireCommaBeforeLineBreak": true, + + "disallowSpaceAfterPrefixUnaryOperators": ["++", "--", "+", "-", "~", "!"], + "requireSpaceAfterPrefixUnaryOperators": [], + + "disallowSpaceBeforePostfixUnaryOperators": ["++", "--"], + "requireSpaceBeforePostfixUnaryOperators": [], + + "disallowSpaceBeforeBinaryOperators": [], + "requireSpaceBeforeBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], + + "requireSpaceAfterBinaryOperators": ["+", "-", "/", "*", "=", "==", "===", "!=", "!=="], + "disallowSpaceAfterBinaryOperators": [], + + "disallowImplicitTypeConversion": ["binary", "string"], + + "disallowKeywords": ["with", "eval"], + + "requireKeywordsOnNewLine": [], + "disallowKeywordsOnNewLine": ["else"], + + "requireLineFeedAtFileEnd": true, + + "disallowTrailingWhitespace": true, + + "disallowTrailingComma": true, + + "excludeFiles": ["node_modules/**", "vendor/**"], + + "disallowMultipleLineStrings": true, + + "requireDotNotation": { "allExcept": ["keywords"] }, + + "requireParenthesesAroundIIFE": true, + + "validateLineBreaks": "LF", + + "validateQuoteMarks": { + "escape": true, + "mark": "'" + }, + + "disallowOperatorBeforeLineBreak": [], + + "requireSpaceBeforeKeywords": [ + "do", + "for", + "if", + "else", + "switch", + "case", + "try", + "catch", + "finally", + "while", + "with", + "return" + ], + + "validateAlignedFunctionParameters": { + "lineBreakAfterOpeningBraces": true, + "lineBreakBeforeClosingBraces": true + }, + + "requirePaddingNewLinesBeforeExport": true, + + "validateNewlineAfterArrayElements": { + "maximum": 6 + }, + + "requirePaddingNewLinesAfterUseStrict": true, + + "disallowArrowFunctions": true, + + "disallowMultiLineTernary": true, + + "validateOrderInObjectKeys": false, + + "disallowIdenticalDestructuringNames": true, + + "disallowNestedTernaries": { "maxLevel": 1 }, + + "requireSpaceAfterComma": { "allExcept": ["trailing"] }, + "requireAlignedMultilineParams": false, + + "requireSpacesInGenerator": { + "afterStar": true + }, + + "disallowSpacesInGenerator": { + "beforeStar": true + }, + + "disallowVar": false, + + "requireArrayDestructuring": false, + + "requireEnhancedObjectLiterals": false, + + "requireObjectDestructuring": false, + + "requireEarlyReturn": false, + + "requireCapitalizedConstructorsNew": { + "allExcept": ["Function", "String", "Object", "Symbol", "Number", "Date", "RegExp", "Error", "Boolean", "Array"] + }, + + "requireImportAlphabetized": false, + + "requireSpaceBeforeObjectValues": true, + "requireSpaceBeforeDestructuredValues": true, + + "disallowSpacesInsideTemplateStringPlaceholders": true, + + "disallowArrayDestructuringReturn": false, + + "requireNewlineBeforeSingleStatementsInIf": false, + + "disallowUnusedVariables": true, + + "requireSpacesInsideImportedObjectBraces": true, + + "requireUseStrict": true +} + diff --git a/node_modules/extend/.travis.yml b/node_modules/extend/.travis.yml new file mode 100644 index 0000000..5ccdfc4 --- /dev/null +++ b/node_modules/extend/.travis.yml @@ -0,0 +1,230 @@ +language: node_js +os: + - linux +node_js: + - "10.7" + - "9.11" + - "8.11" + - "7.10" + - "6.14" + - "5.12" + - "4.9" + - "iojs-v3.3" + - "iojs-v2.5" + - "iojs-v1.8" + - "0.12" + - "0.10" + - "0.8" +before_install: + - 'case "${TRAVIS_NODE_VERSION}" in 0.*) export NPM_CONFIG_STRICT_SSL=false ;; esac' + - 'nvm install-latest-npm' +install: + - 'if [ "${TRAVIS_NODE_VERSION}" = "0.6" ] || [ "${TRAVIS_NODE_VERSION}" = "0.9" ]; then nvm install --latest-npm 0.8 && npm install && nvm use "${TRAVIS_NODE_VERSION}"; else npm install; fi;' +script: + - 'if [ -n "${PRETEST-}" ]; then npm run pretest ; fi' + - 'if [ -n "${POSTTEST-}" ]; then npm run posttest ; fi' + - 'if [ -n "${COVERAGE-}" ]; then npm run coverage ; fi' + - 'if [ -n "${TEST-}" ]; then npm run tests-only ; fi' +sudo: false +env: + - TEST=true +matrix: + fast_finish: true + include: + - node_js: "lts/*" + env: PRETEST=true + - node_js: "lts/*" + env: POSTTEST=true + - node_js: "4" + env: COVERAGE=true + - node_js: "10.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "10.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "9.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "8.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "7.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.13" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.12" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "6.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.10" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "5.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.8" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "4.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v3.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v2.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.7" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.5" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.4" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.3" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.2" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.1" + env: TEST=true ALLOW_FAILURE=true + - node_js: "iojs-v1.0" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.11" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.9" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.6" + env: TEST=true ALLOW_FAILURE=true + - node_js: "0.4" + env: TEST=true ALLOW_FAILURE=true + allow_failures: + - os: osx + - env: TEST=true ALLOW_FAILURE=true diff --git a/node_modules/extend/CHANGELOG.md b/node_modules/extend/CHANGELOG.md new file mode 100644 index 0000000..2cf7de6 --- /dev/null +++ b/node_modules/extend/CHANGELOG.md @@ -0,0 +1,83 @@ +3.0.2 / 2018-07-19 +================== + * [Fix] Prevent merging `__proto__` property (#48) + * [Dev Deps] update `eslint`, `@ljharb/eslint-config`, `tape` + * [Tests] up to `node` `v10.7`, `v9.11`, `v8.11`, `v7.10`, `v6.14`, `v4.9`; use `nvm install-latest-npm` + +3.0.1 / 2017-04-27 +================== + * [Fix] deep extending should work with a non-object (#46) + * [Dev Deps] update `tape`, `eslint`, `@ljharb/eslint-config` + * [Tests] up to `node` `v7.9`, `v6.10`, `v4.8`; improve matrix + * [Docs] Switch from vb.teelaun.ch to versionbadg.es for the npm version badge SVG. + * [Docs] Add example to readme (#34) + +3.0.0 / 2015-07-01 +================== + * [Possible breaking change] Use global "strict" directive (#32) + * [Tests] `int` is an ES3 reserved word + * [Tests] Test up to `io.js` `v2.3` + * [Tests] Add `npm run eslint` + * [Dev Deps] Update `covert`, `jscs` + +2.0.1 / 2015-04-25 +================== + * Use an inline `isArray` check, for ES3 browsers. (#27) + * Some old browsers fail when an identifier is `toString` + * Test latest `node` and `io.js` versions on `travis-ci`; speed up builds + * Add license info to package.json (#25) + * Update `tape`, `jscs` + * Adding a CHANGELOG + +2.0.0 / 2014-10-01 +================== + * Increase code coverage to 100%; run code coverage as part of tests + * Add `npm run lint`; Run linter as part of tests + * Remove nodeType and setInterval checks in isPlainObject + * Updating `tape`, `jscs`, `covert` + * General style and README cleanup + +1.3.0 / 2014-06-20 +================== + * Add component.json for browser support (#18) + * Use SVG for badges in README (#16) + * Updating `tape`, `covert` + * Updating travis-ci to work with multiple node versions + * Fix `deep === false` bug (returning target as {}) (#14) + * Fixing constructor checks in isPlainObject + * Adding additional test coverage + * Adding `npm run coverage` + * Add LICENSE (#13) + * Adding a warning about `false`, per #11 + * General style and whitespace cleanup + +1.2.1 / 2013-09-14 +================== + * Fixing hasOwnProperty bugs that would only have shown up in specific browsers. Fixes #8 + * Updating `tape` + +1.2.0 / 2013-09-02 +================== + * Updating the README: add badges + * Adding a missing variable reference. + * Using `tape` instead of `buster` for tests; add more tests (#7) + * Adding node 0.10 to Travis CI (#6) + * Enabling "npm test" and cleaning up package.json (#5) + * Add Travis CI. + +1.1.3 / 2012-12-06 +================== + * Added unit tests. + * Ensure extend function is named. (Looks nicer in a stack trace.) + * README cleanup. + +1.1.1 / 2012-11-07 +================== + * README cleanup. + * Added installation instructions. + * Added a missing semicolon + +1.0.0 / 2012-04-08 +================== + * Initial commit + diff --git a/node_modules/extend/LICENSE b/node_modules/extend/LICENSE new file mode 100644 index 0000000..e16d6a5 --- /dev/null +++ b/node_modules/extend/LICENSE @@ -0,0 +1,23 @@ +The MIT License (MIT) + +Copyright (c) 2014 Stefan Thomas + +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. + diff --git a/node_modules/extend/README.md b/node_modules/extend/README.md new file mode 100644 index 0000000..5b8249a --- /dev/null +++ b/node_modules/extend/README.md @@ -0,0 +1,81 @@ +[![Build Status][travis-svg]][travis-url] +[![dependency status][deps-svg]][deps-url] +[![dev dependency status][dev-deps-svg]][dev-deps-url] + +# extend() for Node.js [![Version Badge][npm-version-png]][npm-url] + +`node-extend` is a port of the classic extend() method from jQuery. It behaves as you expect. It is simple, tried and true. + +Notes: + +* Since Node.js >= 4, + [`Object.assign`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) + now offers the same functionality natively (but without the "deep copy" option). + See [ECMAScript 2015 (ES6) in Node.js](https://nodejs.org/en/docs/es6). +* Some native implementations of `Object.assign` in both Node.js and many + browsers (since NPM modules are for the browser too) may not be fully + spec-compliant. + Check [`object.assign`](https://www.npmjs.com/package/object.assign) module for + a compliant candidate. + +## Installation + +This package is available on [npm][npm-url] as: `extend` + +``` sh +npm install extend +``` + +## Usage + +**Syntax:** extend **(** [`deep`], `target`, `object1`, [`objectN`] **)** + +*Extend one object with one or more others, returning the modified object.* + +**Example:** + +``` js +var extend = require('extend'); +extend(targetObject, object1, object2); +``` + +Keep in mind that the target object will be modified, and will be returned from extend(). + +If a boolean true is specified as the first argument, extend performs a deep copy, recursively copying any objects it finds. Otherwise, the copy will share structure with the original object(s). +Undefined properties are not copied. However, properties inherited from the object's prototype will be copied over. +Warning: passing `false` as the first argument is not supported. + +### Arguments + +* `deep` *Boolean* (optional) +If set, the merge becomes recursive (i.e. deep copy). +* `target` *Object* +The object to extend. +* `object1` *Object* +The object that will be merged into the first. +* `objectN` *Object* (Optional) +More objects to merge into the first. + +## License + +`node-extend` is licensed under the [MIT License][mit-license-url]. + +## Acknowledgements + +All credit to the jQuery authors for perfecting this amazing utility. + +Ported to Node.js by [Stefan Thomas][github-justmoon] with contributions by [Jonathan Buchanan][github-insin] and [Jordan Harband][github-ljharb]. + +[travis-svg]: https://travis-ci.org/justmoon/node-extend.svg +[travis-url]: https://travis-ci.org/justmoon/node-extend +[npm-url]: https://npmjs.org/package/extend +[mit-license-url]: http://opensource.org/licenses/MIT +[github-justmoon]: https://github.com/justmoon +[github-insin]: https://github.com/insin +[github-ljharb]: https://github.com/ljharb +[npm-version-png]: http://versionbadg.es/justmoon/node-extend.svg +[deps-svg]: https://david-dm.org/justmoon/node-extend.svg +[deps-url]: https://david-dm.org/justmoon/node-extend +[dev-deps-svg]: https://david-dm.org/justmoon/node-extend/dev-status.svg +[dev-deps-url]: https://david-dm.org/justmoon/node-extend#info=devDependencies + diff --git a/node_modules/extend/component.json b/node_modules/extend/component.json new file mode 100644 index 0000000..1500a2f --- /dev/null +++ b/node_modules/extend/component.json @@ -0,0 +1,32 @@ +{ + "name": "extend", + "author": "Stefan Thomas (http://www.justmoon.net)", + "version": "3.0.0", + "description": "Port of jQuery.extend for node.js and the browser.", + "scripts": [ + "index.js" + ], + "contributors": [ + { + "name": "Jordan Harband", + "url": "https://github.com/ljharb" + } + ], + "keywords": [ + "extend", + "clone", + "merge" + ], + "repository" : { + "type": "git", + "url": "https://github.com/justmoon/node-extend.git" + }, + "dependencies": { + }, + "devDependencies": { + "tape" : "~3.0.0", + "covert": "~0.4.0", + "jscs": "~1.6.2" + } +} + diff --git a/node_modules/extend/index.js b/node_modules/extend/index.js new file mode 100644 index 0000000..2aa3faa --- /dev/null +++ b/node_modules/extend/index.js @@ -0,0 +1,117 @@ +'use strict'; + +var hasOwn = Object.prototype.hasOwnProperty; +var toStr = Object.prototype.toString; +var defineProperty = Object.defineProperty; +var gOPD = Object.getOwnPropertyDescriptor; + +var isArray = function isArray(arr) { + if (typeof Array.isArray === 'function') { + return Array.isArray(arr); + } + + return toStr.call(arr) === '[object Array]'; +}; + +var isPlainObject = function isPlainObject(obj) { + if (!obj || toStr.call(obj) !== '[object Object]') { + return false; + } + + var hasOwnConstructor = hasOwn.call(obj, 'constructor'); + var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); + // Not own constructor property must be Object + if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { + return false; + } + + // Own properties are enumerated firstly, so to speed up, + // if last one is own, then all properties are own. + var key; + for (key in obj) { /**/ } + + return typeof key === 'undefined' || hasOwn.call(obj, key); +}; + +// If name is '__proto__', and Object.defineProperty is available, define __proto__ as an own property on target +var setProperty = function setProperty(target, options) { + if (defineProperty && options.name === '__proto__') { + defineProperty(target, options.name, { + enumerable: true, + configurable: true, + value: options.newValue, + writable: true + }); + } else { + target[options.name] = options.newValue; + } +}; + +// Return undefined instead of __proto__ if '__proto__' is not an own property +var getProperty = function getProperty(obj, name) { + if (name === '__proto__') { + if (!hasOwn.call(obj, name)) { + return void 0; + } else if (gOPD) { + // In early versions of node, obj['__proto__'] is buggy when obj has + // __proto__ as an own property. Object.getOwnPropertyDescriptor() works. + return gOPD(obj, name).value; + } + } + + return obj[name]; +}; + +module.exports = function extend() { + var options, name, src, copy, copyIsArray, clone; + var target = arguments[0]; + var i = 1; + var length = arguments.length; + var deep = false; + + // Handle a deep copy situation + if (typeof target === 'boolean') { + deep = target; + target = arguments[1] || {}; + // skip the boolean and the target + i = 2; + } + if (target == null || (typeof target !== 'object' && typeof target !== 'function')) { + target = {}; + } + + for (; i < length; ++i) { + options = arguments[i]; + // Only deal with non-null/undefined values + if (options != null) { + // Extend the base object + for (name in options) { + src = getProperty(target, name); + copy = getProperty(options, name); + + // Prevent never-ending loop + if (target !== copy) { + // Recurse if we're merging plain objects or arrays + if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) { + if (copyIsArray) { + copyIsArray = false; + clone = src && isArray(src) ? src : []; + } else { + clone = src && isPlainObject(src) ? src : {}; + } + + // Never move original objects, clone them + setProperty(target, { name: name, newValue: extend(deep, clone, copy) }); + + // Don't bring in undefined values + } else if (typeof copy !== 'undefined') { + setProperty(target, { name: name, newValue: copy }); + } + } + } + } + } + + // Return the modified object + return target; +}; diff --git a/node_modules/extend/package.json b/node_modules/extend/package.json new file mode 100644 index 0000000..b575afd --- /dev/null +++ b/node_modules/extend/package.json @@ -0,0 +1,77 @@ +{ + "_from": "extend@^3.0.2", + "_id": "extend@3.0.2", + "_inBundle": false, + "_integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==", + "_location": "/extend", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "extend@^3.0.2", + "name": "extend", + "escapedName": "extend", + "rawSpec": "^3.0.2", + "saveSpec": null, + "fetchSpec": "^3.0.2" + }, + "_requiredBy": [ + "/gaxios", + "/gcp-metadata/gaxios", + "/gtoken/gaxios" + ], + "_resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "_shasum": "f8b1136b4071fbd8eb140aff858b1019ec2915fa", + "_spec": "extend@^3.0.2", + "_where": "/Users/cday/Code/zendesk/fetch-build-from-gcb/node_modules/gaxios", + "author": { + "name": "Stefan Thomas", + "email": "justmoon@members.fsf.org", + "url": "http://www.justmoon.net" + }, + "bugs": { + "url": "https://github.com/justmoon/node-extend/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Jordan Harband", + "url": "https://github.com/ljharb" + } + ], + "dependencies": {}, + "deprecated": false, + "description": "Port of jQuery.extend for node.js and the browser", + "devDependencies": { + "@ljharb/eslint-config": "^12.2.1", + "covert": "^1.1.0", + "eslint": "^4.19.1", + "jscs": "^3.0.7", + "tape": "^4.9.1" + }, + "homepage": "https://github.com/justmoon/node-extend#readme", + "keywords": [ + "extend", + "clone", + "merge" + ], + "license": "MIT", + "main": "index", + "name": "extend", + "repository": { + "type": "git", + "url": "git+https://github.com/justmoon/node-extend.git" + }, + "scripts": { + "coverage": "covert test/index.js", + "coverage-quiet": "covert test/index.js --quiet", + "eslint": "eslint *.js */*.js", + "jscs": "jscs *.js */*.js", + "lint": "npm run jscs && npm run eslint", + "posttest": "npm run coverage-quiet", + "pretest": "npm run lint", + "test": "npm run tests-only", + "tests-only": "node test" + }, + "version": "3.0.2" +} diff --git a/node_modules/fast-text-encoding/LICENSE b/node_modules/fast-text-encoding/LICENSE new file mode 100644 index 0000000..8dada3e --- /dev/null +++ b/node_modules/fast-text-encoding/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. 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 and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/fast-text-encoding/README.md b/node_modules/fast-text-encoding/README.md new file mode 100644 index 0000000..863c38f --- /dev/null +++ b/node_modules/fast-text-encoding/README.md @@ -0,0 +1,54 @@ +This is a fast polyfill for [`TextEncoder`][1] and [`TextDecoder`][2], which let you encode and decode JavaScript strings into UTF-8 bytes. + +It is fast partially as it does not support any encodings aside UTF-8 (and note that natively, only `TextDecoder` supports alternative encodings anyway). + +[1]: https://developer.mozilla.org/en-US/docs/Web/API/TextEncoder +[2]: https://developer.mozilla.org/en-US/docs/Web/API/TextDecoder + +# Usage + +Include the minified inside a `script` tag or as an ES6 Module for its side-effects. +It will create `TextEncoder` and `TextDecoder` if the symbols are missing on `window`. + +```html + + +``` + +**Note**: Always include `text.min.js`, as it's compiled to ES5 for older environments. + +## Node + +Install via NPM or Yarn (name "fast-text-encoding"), and then import purely for side effects: + +```js +// don't need to save this anywhere, just require before use +require('fast-text-encoding'); + +const buffer = new TextEncoder().encode('Turn me into UTF-8!'); +// buffer is now a Uint8Array of [84, 117, 114, 110, ...] +``` + +However, note that `Buffer.from('Turn me into UTF-8!')` is Node's native version of the text encoding functionality. +You can probably massage [`Buffer`](https://nodejs.org/api/buffer.html) into acting like `TextEncoder` and `TextDecoder`. + +# Supports + +Built for IE11, Edge and Node environments. +Not required for Chrome, Firefox etc, which have native implementations. + +# Release + +Compile code with [Closure Compiler](https://closure-compiler.appspot.com/home). + +``` +// ==ClosureCompiler== +// @compilation_level ADVANCED_OPTIMIZATIONS +// @output_file_name text.min.js +// ==/ClosureCompiler== + +// code here +``` diff --git a/node_modules/fast-text-encoding/package.json b/node_modules/fast-text-encoding/package.json new file mode 100644 index 0000000..3e0450b --- /dev/null +++ b/node_modules/fast-text-encoding/package.json @@ -0,0 +1,48 @@ +{ + "_from": "fast-text-encoding@^1.0.0", + "_id": "fast-text-encoding@1.0.1", + "_inBundle": false, + "_integrity": "sha512-x4FEgaz3zNRtJfLFqJmHWxkMDDvXVtaznj2V9jiP8ACUJrUgist4bP9FmDL2Vew2Y9mEQI/tG4GqabaitYp9CQ==", + "_location": "/fast-text-encoding", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "fast-text-encoding@^1.0.0", + "name": "fast-text-encoding", + "escapedName": "fast-text-encoding", + "rawSpec": "^1.0.0", + "saveSpec": null, + "fetchSpec": "^1.0.0" + }, + "_requiredBy": [ + "/google-auth-library" + ], + "_resolved": "https://registry.npmjs.org/fast-text-encoding/-/fast-text-encoding-1.0.1.tgz", + "_shasum": "4a428566f74fc55ebdd447555b1eb4d9cf514455", + "_spec": "fast-text-encoding@^1.0.0", + "_where": "/Users/cday/Code/zendesk/fetch-build-from-gcb/node_modules/google-auth-library", + "author": { + "name": "Sam Thorogood", + "email": "sam.thorogood@gmail.com" + }, + "bugs": { + "url": "https://github.com/samthor/fast-text-encoder/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Fast polyfill for TextEncoder and TextDecoder, only supports utf-8", + "devDependencies": { + "chai": "^4.2.0", + "mocha": "^7.1.0" + }, + "homepage": "https://github.com/samthor/fast-text-encoder#readme", + "license": "Apache-2", + "main": "text.min.js", + "name": "fast-text-encoding", + "repository": { + "type": "git", + "url": "git+https://github.com/samthor/fast-text-encoder.git" + }, + "version": "1.0.1" +} diff --git a/node_modules/fast-text-encoding/suite.js b/node_modules/fast-text-encoding/suite.js new file mode 100644 index 0000000..95d45db --- /dev/null +++ b/node_modules/fast-text-encoding/suite.js @@ -0,0 +1,108 @@ +function tests(isNative, TextEncoder, TextDecoder) { + const dec = new TextDecoder(); + const enc = new TextEncoder('utf-8'); + + suite(isNative ? 'native' : 'polyfill', () => { + + test('really large string', () => { + const chunks = new Array(64); + for (let i = 0; i < chunks.length; ++i) { + const s = new Array(65535).fill('x'.charCodeAt(0)); + chunks[i] = s; + } + const s = chunks.join(''); + + const buffer = enc.encode(s); + const out = dec.decode(buffer); + + assert.equal(out, s); + + }); + + suite('decoder', () => { + + test('basic', () => { + const buffer = new Uint8Array([104, 101, 108, 108, 111]); + assert.equal(dec.decode(buffer), 'hello'); + }); + + test('constructor', () => { + assert.throws(() => { + new TextDecoder('invalid'); + }, RangeError); + + if (!isNative) { + assert.throws(() => { + new TextDecoder('utf-8', {fatal: true}); + }, Error, 'unsupported', 'fatal is unsupported'); + } + }); + + test('null in middle', () => { + const s = 'pad\x00pad'; + const buffer = new Uint8Array([112, 97, 100, 0, 112, 97, 100]); + assert.deepEqual(dec.decode(buffer), s); + }); + + test('null at ends', () => { + const s = '\x00\x00?\x00\x00'; + const buffer = new Uint8Array([0, 0, 63, 0, 0]); + assert.deepEqual(dec.decode(buffer), s); + }); + + }); + + suite('encoder', () => { + + test('basic', () => { + const buffer = new Uint8Array([104, 101, 108, 108, 111]); + assert.deepEqual(enc.encode('hello'), buffer); + }); + + test('constructor', () => { + const enc2 = new TextEncoder('literally anything can go here'); + const enc3 = new TextEncoder(new Object()); + + // Despite having no difference in functionality, these should not be the + // same object. + assert.notEqual(enc, enc2); + assert.notEqual(enc, enc3); + }); + + test('ie11 .slice', () => { + const originalSlice = Uint8Array.prototype.slice; + try { + Uint8Array.prototype.slice = null; + assert.isNull(Uint8Array.prototype.slice); + + // Confirms that the method works even without .slice. + const buffer = new Uint8Array([194, 161]); + assert.deepEqual(enc.encode('¡'), buffer); + + } finally { + Uint8Array.prototype.slice = originalSlice; + } + }); + + test('null in middle', () => { + const s = 'pad\x00pad'; + const buffer = new Uint8Array([112, 97, 100, 0, 112, 97, 100]); + assert.deepEqual(enc.encode(s), buffer); + }); + + test('null at ends', () => { + const s = '\x00\x00?\x00\x00'; + const buffer = new Uint8Array([0, 0, 63, 0, 0]); + assert.deepEqual(enc.encode(s), buffer); + }); + + }); + + }); + +} + +if (window.NativeTextEncoder && window.NativeTextDecoder) { + tests(true, NativeTextEncoder, NativeTextDecoder); +} +tests(false, TextEncoder, TextDecoder); diff --git a/node_modules/fast-text-encoding/test.html b/node_modules/fast-text-encoding/test.html new file mode 100644 index 0000000..f8b9c9b --- /dev/null +++ b/node_modules/fast-text-encoding/test.html @@ -0,0 +1,115 @@ + + + + + + + + + + + + +
+ + + + diff --git a/node_modules/fast-text-encoding/text.js b/node_modules/fast-text-encoding/text.js new file mode 100644 index 0000000..ba38d73 --- /dev/null +++ b/node_modules/fast-text-encoding/text.js @@ -0,0 +1,210 @@ +/* + * Copyright 2017 Sam Thorogood. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not + * use this file except in compliance with the License. You may obtain a copy of + * the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT + * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the + * License for the specific language governing permissions and limitations under + * the License. + */ + +/** + * @fileoverview Polyfill for TextEncoder and TextDecoder. + * + * You probably want `text.min.js`, and not this file directly. + */ + +(function(scope) { +'use strict'; + +// fail early +if (scope['TextEncoder'] && scope['TextDecoder']) { + return false; +} + +// used for FastTextDecoder +const validUtfLabels = ['utf-8', 'utf8', 'unicode-1-1-utf-8']; + +/** + * @constructor + */ +function FastTextEncoder() { + // This does not accept an encoding, and always uses UTF-8: + // https://www.w3.org/TR/encoding/#dom-textencoder +} + +Object.defineProperty(FastTextEncoder.prototype, 'encoding', {value: 'utf-8'}); + +/** + * @param {string} string + * @param {{stream: boolean}=} options + * @return {!Uint8Array} + */ +FastTextEncoder.prototype.encode = function(string, options={stream: false}) { + if (options.stream) { + throw new Error(`Failed to encode: the 'stream' option is unsupported.`); + } + + let pos = 0; + const len = string.length; + + let at = 0; // output position + let tlen = Math.max(32, len + (len >> 1) + 7); // 1.5x size + let target = new Uint8Array((tlen >> 3) << 3); // ... but at 8 byte offset + + while (pos < len) { + let value = string.charCodeAt(pos++); + if (value >= 0xd800 && value <= 0xdbff) { + // high surrogate + if (pos < len) { + const extra = string.charCodeAt(pos); + if ((extra & 0xfc00) === 0xdc00) { + ++pos; + value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000; + } + } + if (value >= 0xd800 && value <= 0xdbff) { + continue; // drop lone surrogate + } + } + + // expand the buffer if we couldn't write 4 bytes + if (at + 4 > target.length) { + tlen += 8; // minimum extra + tlen *= (1.0 + (pos / string.length) * 2); // take 2x the remaining + tlen = (tlen >> 3) << 3; // 8 byte offset + + const update = new Uint8Array(tlen); + update.set(target); + target = update; + } + + if ((value & 0xffffff80) === 0) { // 1-byte + target[at++] = value; // ASCII + continue; + } else if ((value & 0xfffff800) === 0) { // 2-byte + target[at++] = ((value >> 6) & 0x1f) | 0xc0; + } else if ((value & 0xffff0000) === 0) { // 3-byte + target[at++] = ((value >> 12) & 0x0f) | 0xe0; + target[at++] = ((value >> 6) & 0x3f) | 0x80; + } else if ((value & 0xffe00000) === 0) { // 4-byte + target[at++] = ((value >> 18) & 0x07) | 0xf0; + target[at++] = ((value >> 12) & 0x3f) | 0x80; + target[at++] = ((value >> 6) & 0x3f) | 0x80; + } else { + // FIXME: do we care + continue; + } + + target[at++] = (value & 0x3f) | 0x80; + } + + // Use subarray if slice isn't supported (IE11). This will use more memory + // because the original array still exists. + return target.slice ? target.slice(0, at) : target.subarray(0, at); +} + +/** + * @constructor + * @param {string=} utfLabel + * @param {{fatal: boolean}=} options + */ +function FastTextDecoder(utfLabel='utf-8', options={fatal: false}) { + if (validUtfLabels.indexOf(utfLabel.toLowerCase()) == -1) { + throw new RangeError( + `Failed to construct 'TextDecoder': The encoding label provided ('${utfLabel}') is invalid.`); + } + if (options.fatal) { + throw new Error(`Failed to construct 'TextDecoder': the 'fatal' option is unsupported.`); + } +} + +Object.defineProperty(FastTextDecoder.prototype, 'encoding', {value: 'utf-8'}); + +Object.defineProperty(FastTextDecoder.prototype, 'fatal', {value: false}); + +Object.defineProperty(FastTextDecoder.prototype, 'ignoreBOM', {value: false}); + +/** + * @param {(!ArrayBuffer|!ArrayBufferView)} buffer + * @param {{stream: boolean}=} options + * @return {string} + */ +FastTextDecoder.prototype.decode = function(buffer, options={stream: false}) { + if (options['stream']) { + throw new Error(`Failed to decode: the 'stream' option is unsupported.`); + } + + // Look for ArrayBufferView, which isn't a real type, but basically represents + // all the valid TypedArray types plus DataView. They all have ".buffer" as + // an instance of ArrayBuffer. + if (buffer.buffer instanceof ArrayBuffer) { + buffer = buffer.buffer; + } + + let bytes = new Uint8Array(buffer); + let pos = 0; + let pending = []; + const chunks = []; + + for (;;) { + const more = pos < bytes.length; + + // If there's no more data or we're >65k bytes, create a chunk. + // This isn't done at the end by simply slicing the data into equal sized + // chunks as we might hit a surrogate pair. + if (!more || (pos & 0x10000)) { + chunks.push(String.fromCharCode.apply(null, pending)); + + if (!more) { + return chunks.join(''); + } + + // Move the buffer forward and create another chunk. + pending = []; + bytes = bytes.subarray(pos); + pos = 0; + } + + const byte1 = bytes[pos++]; + if (byte1 === 0) { + pending.push(0); + } else if ((byte1 & 0x80) === 0) { // 1-byte + pending.push(byte1); + } else if ((byte1 & 0xe0) === 0xc0) { // 2-byte + const byte2 = bytes[pos++] & 0x3f; + pending.push(((byte1 & 0x1f) << 6) | byte2); + } else if ((byte1 & 0xf0) === 0xe0) { + const byte2 = bytes[pos++] & 0x3f; + const byte3 = bytes[pos++] & 0x3f; + pending.push(((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3); + } else if ((byte1 & 0xf8) === 0xf0) { + const byte2 = bytes[pos++] & 0x3f; + const byte3 = bytes[pos++] & 0x3f; + const byte4 = bytes[pos++] & 0x3f; + + // this can be > 0xffff, so possibly generate surrogates + let codepoint = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4; + if (codepoint > 0xffff) { + // codepoint &= ~0x10000; + codepoint -= 0x10000; + pending.push((codepoint >>> 10) & 0x3ff | 0xd800); + codepoint = 0xdc00 | codepoint & 0x3ff; + } + pending.push(codepoint); + } else { + // FIXME: we're ignoring this + } + } +} + +scope['TextEncoder'] = FastTextEncoder; +scope['TextDecoder'] = FastTextDecoder; + +}(typeof window !== 'undefined' ? window : (typeof global !== 'undefined' ? global : this))); diff --git a/node_modules/fast-text-encoding/text.min.js b/node_modules/fast-text-encoding/text.min.js new file mode 100644 index 0000000..a17e39a --- /dev/null +++ b/node_modules/fast-text-encoding/text.min.js @@ -0,0 +1,5 @@ +(function(l){function m(){}function k(b,a){b=void 0===b?"utf-8":b;a=void 0===a?{fatal:!1}:a;if(-1==n.indexOf(b.toLowerCase()))throw new RangeError("Failed to construct 'TextDecoder': The encoding label provided ('"+b+"') is invalid.");if(a.fatal)throw Error("Failed to construct 'TextDecoder': the 'fatal' option is unsupported.");}if(l.TextEncoder&&l.TextDecoder)return!1;var n=["utf-8","utf8","unicode-1-1-utf-8"];Object.defineProperty(m.prototype,"encoding",{value:"utf-8"});m.prototype.encode=function(b, +a){a=void 0===a?{stream:!1}:a;if(a.stream)throw Error("Failed to encode: the 'stream' option is unsupported.");a=0;for(var g=b.length,f=0,c=Math.max(32,g+(g>>1)+7),e=new Uint8Array(c>>3<<3);a=d){if(a=d)continue}f+4>e.length&&(c+=8,c*=1+a/b.length*2,c=c>>3<<3,h=new Uint8Array(c),h.set(e),e=h);if(0===(d&4294967168))e[f++]=d;else{if(0===(d&4294965248))e[f++]= +d>>6&31|192;else if(0===(d&4294901760))e[f++]=d>>12&15|224,e[f++]=d>>6&63|128;else if(0===(d&4292870144))e[f++]=d>>18&7|240,e[f++]=d>>12&63|128,e[f++]=d>>6&63|128;else continue;e[f++]=d&63|128}}return e.slice?e.slice(0,f):e.subarray(0,f)};Object.defineProperty(k.prototype,"encoding",{value:"utf-8"});Object.defineProperty(k.prototype,"fatal",{value:!1});Object.defineProperty(k.prototype,"ignoreBOM",{value:!1});k.prototype.decode=function(b,a){a=void 0===a?{stream:!1}:a;if(a.stream)throw Error("Failed to decode: the 'stream' option is unsupported."); +b.buffer instanceof ArrayBuffer&&(b=b.buffer);b=new Uint8Array(b);a=0;for(var g=[],f=[];;){var c=a>>10&1023|55296),c=56320|c&1023);g.push(c)}}};l.TextEncoder=m;l.TextDecoder=k})("undefined"!==typeof window?window:"undefined"!==typeof global?global:this); diff --git a/node_modules/gaxios/CHANGELOG.md b/node_modules/gaxios/CHANGELOG.md new file mode 100644 index 0000000..5ef6d5f --- /dev/null +++ b/node_modules/gaxios/CHANGELOG.md @@ -0,0 +1,114 @@ +# Changelog + +### [3.0.2](https://www.github.com/googleapis/gaxios/compare/v3.0.1...v3.0.2) (2020-03-24) + + +### Bug Fixes + +* continue replacing application/x-www-form-urlencoded with application/json ([#263](https://www.github.com/googleapis/gaxios/issues/263)) ([dca176d](https://www.github.com/googleapis/gaxios/commit/dca176df0990f2c22255f9764405c496ea07ada2)) + +### [3.0.1](https://www.github.com/googleapis/gaxios/compare/v3.0.0...v3.0.1) (2020-03-23) + + +### Bug Fixes + +* allow an alternate JSON content-type to be set ([#257](https://www.github.com/googleapis/gaxios/issues/257)) ([698a29f](https://www.github.com/googleapis/gaxios/commit/698a29ff3b22f30ea99ad190c4592940bef88f1f)) + +## [3.0.0](https://www.github.com/googleapis/gaxios/compare/v2.3.2...v3.0.0) (2020-03-19) + + +### ⚠ BREAKING CHANGES + +* **deps:** TypeScript introduced breaking changes in generated code in 3.7.x +* drop Node 8 from engines field (#254) + +### Features + +* drop Node 8 from engines field ([#254](https://www.github.com/googleapis/gaxios/issues/254)) ([8c9fff7](https://www.github.com/googleapis/gaxios/commit/8c9fff7f92f70f029292c906c62d194c1d58827d)) +* **deps:** updates to latest TypeScript ([#253](https://www.github.com/googleapis/gaxios/issues/253)) ([054267b](https://www.github.com/googleapis/gaxios/commit/054267bf12e1801c134e3b5cae92dcc5ea041fab)) + +### [2.3.2](https://www.github.com/googleapis/gaxios/compare/v2.3.1...v2.3.2) (2020-02-28) + + +### Bug Fixes + +* update github repo in package ([#239](https://www.github.com/googleapis/gaxios/issues/239)) ([7e750cb](https://www.github.com/googleapis/gaxios/commit/7e750cbaaa59812817d725c74fb9d364c4b71096)) + +### [2.3.1](https://www.github.com/googleapis/gaxios/compare/v2.3.0...v2.3.1) (2020-02-13) + + +### Bug Fixes + +* **deps:** update dependency https-proxy-agent to v5 ([#233](https://www.github.com/googleapis/gaxios/issues/233)) ([56de0a8](https://www.github.com/googleapis/gaxios/commit/56de0a824a2f9622e3e4d4bdd41adccd812a30b4)) + +## [2.3.0](https://www.github.com/googleapis/gaxios/compare/v2.2.2...v2.3.0) (2020-01-31) + + +### Features + +* add promise support for onRetryAttempt and shouldRetry ([#223](https://www.github.com/googleapis/gaxios/issues/223)) ([061afa3](https://www.github.com/googleapis/gaxios/commit/061afa381a51d39823e63accf3dacd16e191f3b9)) + +### [2.2.2](https://www.github.com/googleapis/gaxios/compare/v2.2.1...v2.2.2) (2020-01-08) + + +### Bug Fixes + +* **build:** add publication configuration ([#218](https://www.github.com/googleapis/gaxios/issues/218)) ([43e581f](https://www.github.com/googleapis/gaxios/commit/43e581ff4ed5e79d72f6f29748a5eebb6bff1229)) + +### [2.2.1](https://www.github.com/googleapis/gaxios/compare/v2.2.0...v2.2.1) (2020-01-04) + + +### Bug Fixes + +* **deps:** update dependency https-proxy-agent to v4 ([#201](https://www.github.com/googleapis/gaxios/issues/201)) ([5cdeef2](https://www.github.com/googleapis/gaxios/commit/5cdeef288a0c5c544c0dc2659aafbb2215d06c4b)) +* remove retryDelay option ([#203](https://www.github.com/googleapis/gaxios/issues/203)) ([d21e08d](https://www.github.com/googleapis/gaxios/commit/d21e08d2aada980d39bc5ca7093d54452be2d646)) + +## [2.2.0](https://www.github.com/googleapis/gaxios/compare/v2.1.1...v2.2.0) (2019-12-05) + + +### Features + +* populate GaxiosResponse with raw response information (res.url) ([#189](https://www.github.com/googleapis/gaxios/issues/189)) ([53a7f54](https://www.github.com/googleapis/gaxios/commit/53a7f54cc0f20320d7a6a21a9a9f36050cec2eec)) + + +### Bug Fixes + +* don't retry a request that is aborted intentionally ([#190](https://www.github.com/googleapis/gaxios/issues/190)) ([ba9777b](https://www.github.com/googleapis/gaxios/commit/ba9777b15b5262f8288a8bb3cca49a1de8427d8e)) +* **deps:** pin TypeScript below 3.7.0 ([5373f07](https://www.github.com/googleapis/gaxios/commit/5373f0793a765965a8221ecad2f99257ed1b7444)) + +### [2.1.1](https://www.github.com/googleapis/gaxios/compare/v2.1.0...v2.1.1) (2019-11-15) + + +### Bug Fixes + +* **docs:** snippets are now replaced in jsdoc comments ([#183](https://www.github.com/googleapis/gaxios/issues/183)) ([8dd1324](https://www.github.com/googleapis/gaxios/commit/8dd1324256590bd2f2e9015c813950e1cd8cb330)) + +## [2.1.0](https://www.github.com/googleapis/gaxios/compare/v2.0.3...v2.1.0) (2019-10-09) + + +### Bug Fixes + +* **deps:** update dependency https-proxy-agent to v3 ([#172](https://www.github.com/googleapis/gaxios/issues/172)) ([4a38f35](https://www.github.com/googleapis/gaxios/commit/4a38f35)) + + +### Features + +* **TypeScript:** agent can now be passed as builder method, rather than agent instance ([c84ddd6](https://www.github.com/googleapis/gaxios/commit/c84ddd6)) + +### [2.0.3](https://www.github.com/googleapis/gaxios/compare/v2.0.2...v2.0.3) (2019-09-11) + + +### Bug Fixes + +* do not override content-type if its given ([#158](https://www.github.com/googleapis/gaxios/issues/158)) ([f49e0e6](https://www.github.com/googleapis/gaxios/commit/f49e0e6)) +* improve stream detection logic ([6c41537](https://www.github.com/googleapis/gaxios/commit/6c41537)) +* revert header change ([#161](https://www.github.com/googleapis/gaxios/issues/161)) ([b0f6a8b](https://www.github.com/googleapis/gaxios/commit/b0f6a8b)) + +### [2.0.2](https://www.github.com/googleapis/gaxios/compare/v2.0.1...v2.0.2) (2019-07-23) + + +### Bug Fixes + +* check for existence of fetch before using it ([#138](https://www.github.com/googleapis/gaxios/issues/138)) ([79eb58d](https://www.github.com/googleapis/gaxios/commit/79eb58d)) +* **docs:** make anchors work in jsdoc ([#139](https://www.github.com/googleapis/gaxios/issues/139)) ([85103bb](https://www.github.com/googleapis/gaxios/commit/85103bb)) +* prevent double option processing ([#142](https://www.github.com/googleapis/gaxios/issues/142)) ([19b4b3c](https://www.github.com/googleapis/gaxios/commit/19b4b3c)) diff --git a/node_modules/gaxios/LICENSE b/node_modules/gaxios/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/node_modules/gaxios/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. 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 and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/gaxios/README.md b/node_modules/gaxios/README.md new file mode 100644 index 0000000..a25f3bd --- /dev/null +++ b/node_modules/gaxios/README.md @@ -0,0 +1,138 @@ +# gaxios + +[![npm version](https://img.shields.io/npm/v/gaxios.svg)](https://www.npmjs.org/package/gaxios) +[![codecov](https://codecov.io/gh/googleapis/gaxios/branch/master/graph/badge.svg)](https://codecov.io/gh/googleapis/gaxios) +[![Code Style: Google](https://img.shields.io/badge/code%20style-google-blueviolet.svg)](https://github.com/google/gts) + +> An HTTP request client that provides an `axios` like interface over top of `node-fetch`. + +## Install +```sh +$ npm install gaxios +``` + +## Example + +```js +const {request} = require('gaxios'); +const res = await request({ + url: 'https://www.googleapis.com/discovery/v1/apis/' +}); +``` + +## Setting Defaults +Gaxios supports setting default properties both on the default instance, and on additional instances. This is often useful when making many requests to the same domain with the same base settings. For example: + +```js +const gaxios = require('gaxios'); +gaxios.instance.defaults = { + baseURL: 'https://example.com' + headers: { + Authorization: 'SOME_TOKEN' + } +} +gaxios.request({url: '/data'}).then(...); +``` + +## Request Options + +```js +{ + // The url to which the request should be sent. Required. + url: string, + + // The HTTP method to use for the request. Defaults to `GET`. + method: 'GET', + + // The base Url to use for the request. Prepended to the `url` property above. + baseURL: 'https://example.com'; + + // The HTTP methods to be sent with the request. + headers: { 'some': 'header' }, + + // The data to send in the body of the request. Data objects will be serialized as JSON. + data: { + some: 'data' + }, + + // The max size of the http response content in bytes allowed. + // Defaults to `0`, which is the same as unset. + maxContentLength: 2000, + + // The max number of HTTP redirects to follow. + // Defaults to 100. + maxRedirects: 100, + + // The querystring parameters that will be encoded using `qs` and + // appended to the url + params: { + querystring: 'parameters' + }, + + // By default, we use the `querystring` package in node core to serialize + // querystring parameters. You can override that and provide your + // own implementation. + paramsSerializer: (params) => { + return qs.stringify(params); + }, + + // The timeout for the HTTP request. Defaults to 0. + timeout: 1000, + + // Optional method to override making the actual HTTP request. Useful + // for writing tests. + adapter?: (options) => { + return { + data: 'your data' + } + }; + + // The expected return type of the request. Options are: + // json | stream | blob | arraybuffer | text + // Defaults to `json`. + responseType: 'json', + + // The node.js http agent to use for the request. + agent: someHttpsAgent, + + // Custom function to determine if the response is valid based on the + // status code. Defaults to (>= 200 && < 300) + validateStatus: (status: number) => true, + + // Configuration for retrying of requests. + retryConfig: { + // The number of times to retry the request. Defaults to 3. + retry?: number; + + // The number of retries already attempted. + currentRetryAttempt?: number; + + // The HTTP Methods that will be automatically retried. + // Defaults to ['GET','PUT','HEAD','OPTIONS','DELETE'] + httpMethodsToRetry?: string[]; + + // The HTTP response status codes that will automatically be retried. + // Defaults to: [[100, 199], [429, 429], [500, 599]] + statusCodesToRetry?: number[][]; + + // Function to invoke when a retry attempt is made. + onRetryAttempt?: (err: GaxiosError) => Promise | void; + + // Function to invoke which determines if you should retry + shouldRetry?: (err: GaxiosError) => Promise | boolean; + + // When there is no response, the number of retries to attempt. Defaults to 2. + noResponseRetries?: number; + }, + + // Enables default configuration for retries. + retry: boolean, + + // Cancelling a request requires the `abort-controller` library. + // See https://github.com/bitinn/node-fetch#request-cancellation-with-abortsignal + signal?: AbortSignal +} +``` + +## License +[Apache-2.0](https://github.com/googleapis/gaxios/blob/master/LICENSE) diff --git a/node_modules/gaxios/build/src/common.d.ts b/node_modules/gaxios/build/src/common.d.ts new file mode 100644 index 0000000..f6635b2 --- /dev/null +++ b/node_modules/gaxios/build/src/common.d.ts @@ -0,0 +1,104 @@ +/// +import { AbortSignal } from 'abort-controller'; +import { Agent } from 'http'; +import { URL } from 'url'; +export declare class GaxiosError extends Error { + code?: string; + response?: GaxiosResponse; + config: GaxiosOptions; + constructor(message: string, options: GaxiosOptions, response: GaxiosResponse); +} +export interface Headers { + [index: string]: any; +} +export declare type GaxiosPromise = Promise>; +export interface GaxiosXMLHttpRequest { + responseURL: string; +} +export interface GaxiosResponse { + config: GaxiosOptions; + data: T; + status: number; + statusText: string; + headers: Headers; + request: GaxiosXMLHttpRequest; +} +/** + * Request options that are used to form the request. + */ +export interface GaxiosOptions { + /** + * Optional method to override making the actual HTTP request. Useful + * for writing tests. + */ + adapter?: (options: GaxiosOptions) => GaxiosPromise; + url?: string; + baseUrl?: string; + baseURL?: string; + method?: 'GET' | 'HEAD' | 'POST' | 'DELETE' | 'PUT' | 'CONNECT' | 'OPTIONS' | 'TRACE' | 'PATCH'; + headers?: Headers; + data?: any; + body?: any; + /** + * The maximum size of the http response content in bytes allowed. + */ + maxContentLength?: number; + /** + * The maximum number of redirects to follow. Defaults to 20. + */ + maxRedirects?: number; + follow?: number; + params?: any; + paramsSerializer?: (params: { + [index: string]: string | number; + }) => string; + timeout?: number; + onUploadProgress?: (progressEvent: any) => void; + responseType?: 'arraybuffer' | 'blob' | 'json' | 'text' | 'stream'; + agent?: Agent | ((parsedUrl: URL) => Agent); + validateStatus?: (status: number) => boolean; + retryConfig?: RetryConfig; + retry?: boolean; + signal?: AbortSignal; + size?: number; +} +/** + * Configuration for the Gaxios `request` method. + */ +export interface RetryConfig { + /** + * The number of times to retry the request. Defaults to 3. + */ + retry?: number; + /** + * The number of retries already attempted. + */ + currentRetryAttempt?: number; + /** + * The amount of time to initially delay the retry. Defaults to 100. + * @deprecated + */ + retryDelay?: number; + /** + * The HTTP Methods that will be automatically retried. + * Defaults to ['GET','PUT','HEAD','OPTIONS','DELETE'] + */ + httpMethodsToRetry?: string[]; + /** + * The HTTP response status codes that will automatically be retried. + * Defaults to: [[100, 199], [429, 429], [500, 599]] + */ + statusCodesToRetry?: number[][]; + /** + * Function to invoke when a retry attempt is made. + */ + onRetryAttempt?: (err: GaxiosError) => Promise | void; + /** + * Function to invoke which determines if you should retry + */ + shouldRetry?: (err: GaxiosError) => Promise | boolean; + /** + * When there is no response, the number of retries to attempt. Defaults to 2. + */ + noResponseRetries?: number; +} diff --git a/node_modules/gaxios/build/src/common.js b/node_modules/gaxios/build/src/common.js new file mode 100644 index 0000000..2a45ed9 --- /dev/null +++ b/node_modules/gaxios/build/src/common.js @@ -0,0 +1,25 @@ +"use strict"; +// Copyright 2018 Google LLC +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +/* eslint-disable @typescript-eslint/no-explicit-any */ +class GaxiosError extends Error { + constructor(message, options, response) { + super(message); + this.response = response; + this.config = options; + this.code = response.status.toString(); + } +} +exports.GaxiosError = GaxiosError; +//# sourceMappingURL=common.js.map \ No newline at end of file diff --git a/node_modules/gaxios/build/src/common.js.map b/node_modules/gaxios/build/src/common.js.map new file mode 100644 index 0000000..772aab6 --- /dev/null +++ b/node_modules/gaxios/build/src/common.js.map @@ -0,0 +1 @@ +{"version":3,"file":"common.js","sourceRoot":"","sources":["../../src/common.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,gDAAgD;AAChD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;AAMjC,uDAAuD;AAEvD,MAAa,WAAqB,SAAQ,KAAK;IAI7C,YACE,OAAe,EACf,OAAsB,EACtB,QAA2B;QAE3B,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC;QACtB,IAAI,CAAC,IAAI,GAAG,QAAQ,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC;IACzC,CAAC;CACF;AAdD,kCAcC"} \ No newline at end of file diff --git a/node_modules/gaxios/build/src/gaxios.d.ts b/node_modules/gaxios/build/src/gaxios.d.ts new file mode 100644 index 0000000..46b112a --- /dev/null +++ b/node_modules/gaxios/build/src/gaxios.d.ts @@ -0,0 +1,40 @@ +import { GaxiosOptions, GaxiosPromise } from './common'; +export declare class Gaxios { + private agentCache; + /** + * Default HTTP options that will be used for every HTTP request. + */ + defaults: GaxiosOptions; + /** + * The Gaxios class is responsible for making HTTP requests. + * @param defaults The default set of options to be used for this instance. + */ + constructor(defaults?: GaxiosOptions); + /** + * Perform an HTTP request with the given options. + * @param opts Set of HTTP options that will be used for this HTTP request. + */ + request(opts?: GaxiosOptions): GaxiosPromise; + /** + * Internal, retryable version of the `request` method. + * @param opts Set of HTTP options that will be used for this HTTP request. + */ + private _request; + private getResponseData; + /** + * Validates the options, and merges them with defaults. + * @param opts The original options passed from the client. + */ + private validateOpts; + /** + * By default, throw for any non-2xx status code + * @param status status code from the HTTP response + */ + private validateStatus; + /** + * Encode a set of key/value pars into a querystring format (?foo=bar&baz=boo) + * @param params key value pars to encode + */ + private paramsSerializer; + private translateResponse; +} diff --git a/node_modules/gaxios/build/src/gaxios.js b/node_modules/gaxios/build/src/gaxios.js new file mode 100644 index 0000000..852beb1 --- /dev/null +++ b/node_modules/gaxios/build/src/gaxios.js @@ -0,0 +1,227 @@ +"use strict"; +// Copyright 2018 Google LLC +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const extend_1 = __importDefault(require("extend")); +const node_fetch_1 = __importDefault(require("node-fetch")); +const querystring_1 = __importDefault(require("querystring")); +const is_stream_1 = __importDefault(require("is-stream")); +const url_1 = __importDefault(require("url")); +const common_1 = require("./common"); +const retry_1 = require("./retry"); +/* eslint-disable @typescript-eslint/no-explicit-any */ +/* eslint-disable node/no-unsupported-features/node-builtins */ +const URL = hasURL() ? window.URL : url_1.default.URL; +const fetch = hasFetch() ? window.fetch : node_fetch_1.default; +function hasWindow() { + return typeof window !== 'undefined' && !!window; +} +function hasURL() { + return hasWindow() && !!window.URL; +} +function hasFetch() { + return hasWindow() && !!window.fetch; +} +let HttpsProxyAgent; +// Figure out if we should be using a proxy. Only if it's required, load +// the https-proxy-agent module as it adds startup cost. +function loadProxy() { + const proxy = process.env.HTTPS_PROXY || + process.env.https_proxy || + process.env.HTTP_PROXY || + process.env.http_proxy; + if (proxy) { + HttpsProxyAgent = require('https-proxy-agent'); + } + return proxy; +} +loadProxy(); +class Gaxios { + /** + * The Gaxios class is responsible for making HTTP requests. + * @param defaults The default set of options to be used for this instance. + */ + constructor(defaults) { + this.agentCache = new Map(); + this.defaults = defaults || {}; + } + /** + * Perform an HTTP request with the given options. + * @param opts Set of HTTP options that will be used for this HTTP request. + */ + async request(opts = {}) { + opts = this.validateOpts(opts); + return this._request(opts); + } + /** + * Internal, retryable version of the `request` method. + * @param opts Set of HTTP options that will be used for this HTTP request. + */ + async _request(opts = {}) { + try { + let translatedResponse; + if (opts.adapter) { + translatedResponse = await opts.adapter(opts); + } + else { + const res = await fetch(opts.url, opts); + const data = await this.getResponseData(opts, res); + translatedResponse = this.translateResponse(opts, res, data); + } + if (!opts.validateStatus(translatedResponse.status)) { + throw new common_1.GaxiosError(`Request failed with status code ${translatedResponse.status}`, opts, translatedResponse); + } + return translatedResponse; + } + catch (e) { + const err = e; + err.config = opts; + const { shouldRetry, config } = await retry_1.getRetryConfig(e); + if (shouldRetry && config) { + err.config.retryConfig.currentRetryAttempt = config.retryConfig.currentRetryAttempt; + return this._request(err.config); + } + throw err; + } + } + async getResponseData(opts, res) { + switch (opts.responseType) { + case 'stream': + return res.body; + case 'json': { + let data = await res.text(); + try { + data = JSON.parse(data); + } + catch (_a) { + // continue + } + return data; + } + case 'arraybuffer': + return res.arrayBuffer(); + case 'blob': + return res.blob(); + default: + return res.text(); + } + } + /** + * Validates the options, and merges them with defaults. + * @param opts The original options passed from the client. + */ + validateOpts(options) { + const opts = extend_1.default(true, {}, this.defaults, options); + if (!opts.url) { + throw new Error('URL is required.'); + } + // baseUrl has been deprecated, remove in 2.0 + const baseUrl = opts.baseUrl || opts.baseURL; + if (baseUrl) { + opts.url = baseUrl + opts.url; + } + const parsedUrl = new URL(opts.url); + opts.url = `${parsedUrl.origin}${parsedUrl.pathname}`; + opts.params = extend_1.default(querystring_1.default.parse(parsedUrl.search.substr(1)), // removes leading ? + opts.params); + opts.paramsSerializer = opts.paramsSerializer || this.paramsSerializer; + if (opts.params) { + parsedUrl.search = opts.paramsSerializer(opts.params); + } + opts.url = parsedUrl.href; + if (typeof options.maxContentLength === 'number') { + opts.size = options.maxContentLength; + } + if (typeof options.maxRedirects === 'number') { + opts.follow = options.maxRedirects; + } + opts.headers = opts.headers || {}; + if (opts.data) { + if (is_stream_1.default.readable(opts.data)) { + opts.body = opts.data; + } + else if (typeof opts.data === 'object') { + opts.body = JSON.stringify(opts.data); + // Allow the user to specifiy their own content type, + // such as application/json-patch+json; for historical reasons this + // content type must currently be a json type, as we are relying on + // application/x-www-form-urlencoded (which is incompatible with + // upstream GCP APIs) being rewritten to application/json. + // + // TODO: refactor upstream dependencies to stop relying on this + // side-effect. + if (!opts.headers['Content-Type'] || + !opts.headers['Content-Type'].includes('json')) { + opts.headers['Content-Type'] = 'application/json'; + } + } + else { + opts.body = opts.data; + } + } + opts.validateStatus = opts.validateStatus || this.validateStatus; + opts.responseType = opts.responseType || 'json'; + if (!opts.headers['Accept'] && opts.responseType === 'json') { + opts.headers['Accept'] = 'application/json'; + } + opts.method = opts.method || 'GET'; + const proxy = loadProxy(); + if (proxy) { + if (this.agentCache.has(proxy)) { + opts.agent = this.agentCache.get(proxy); + } + else { + opts.agent = new HttpsProxyAgent(proxy); + this.agentCache.set(proxy, opts.agent); + } + } + return opts; + } + /** + * By default, throw for any non-2xx status code + * @param status status code from the HTTP response + */ + validateStatus(status) { + return status >= 200 && status < 300; + } + /** + * Encode a set of key/value pars into a querystring format (?foo=bar&baz=boo) + * @param params key value pars to encode + */ + paramsSerializer(params) { + return querystring_1.default.stringify(params); + } + translateResponse(opts, res, data) { + // headers need to be converted from a map to an obj + const headers = {}; + res.headers.forEach((value, key) => { + headers[key] = value; + }); + return { + config: opts, + data: data, + headers, + status: res.status, + statusText: res.statusText, + // XMLHttpRequestLike + request: { + responseURL: res.url, + }, + }; + } +} +exports.Gaxios = Gaxios; +//# sourceMappingURL=gaxios.js.map \ No newline at end of file diff --git a/node_modules/gaxios/build/src/gaxios.js.map b/node_modules/gaxios/build/src/gaxios.js.map new file mode 100644 index 0000000..4e9e1cd --- /dev/null +++ b/node_modules/gaxios/build/src/gaxios.js.map @@ -0,0 +1 @@ +{"version":3,"file":"gaxios.js","sourceRoot":"","sources":["../../src/gaxios.ts"],"names":[],"mappings":"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"} \ No newline at end of file diff --git a/node_modules/gaxios/build/src/index.d.ts b/node_modules/gaxios/build/src/index.d.ts new file mode 100644 index 0000000..033aff5 --- /dev/null +++ b/node_modules/gaxios/build/src/index.d.ts @@ -0,0 +1,14 @@ +import { GaxiosOptions } from './common'; +import { Gaxios } from './gaxios'; +export { GaxiosError, GaxiosPromise, GaxiosResponse, Headers, RetryConfig, } from './common'; +export { Gaxios, GaxiosOptions }; +/** + * The default instance used when the `request` method is directly + * invoked. + */ +export declare const instance: Gaxios; +/** + * Make an HTTP request using the given options. + * @param opts Options for the request + */ +export declare function request(opts: GaxiosOptions): Promise>; diff --git a/node_modules/gaxios/build/src/index.js b/node_modules/gaxios/build/src/index.js new file mode 100644 index 0000000..71c3ece --- /dev/null +++ b/node_modules/gaxios/build/src/index.js @@ -0,0 +1,32 @@ +"use strict"; +// Copyright 2018 Google LLC +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +const gaxios_1 = require("./gaxios"); +exports.Gaxios = gaxios_1.Gaxios; +var common_1 = require("./common"); +exports.GaxiosError = common_1.GaxiosError; +/** + * The default instance used when the `request` method is directly + * invoked. + */ +exports.instance = new gaxios_1.Gaxios(); +/** + * Make an HTTP request using the given options. + * @param opts Options for the request + */ +async function request(opts) { + return exports.instance.request(opts); +} +exports.request = request; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/gaxios/build/src/index.js.map b/node_modules/gaxios/build/src/index.js.map new file mode 100644 index 0000000..af85752 --- /dev/null +++ b/node_modules/gaxios/build/src/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,gDAAgD;AAChD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;AAGjC,qCAAgC;AASxB,iBATA,eAAM,CASA;AAPd,mCAMkB;AALhB,+BAAA,WAAW,CAAA;AAQb;;;GAGG;AACU,QAAA,QAAQ,GAAG,IAAI,eAAM,EAAE,CAAC;AAErC;;;GAGG;AACI,KAAK,UAAU,OAAO,CAAI,IAAmB;IAClD,OAAO,gBAAQ,CAAC,OAAO,CAAI,IAAI,CAAC,CAAC;AACnC,CAAC;AAFD,0BAEC"} \ No newline at end of file diff --git a/node_modules/gaxios/build/src/retry.d.ts b/node_modules/gaxios/build/src/retry.d.ts new file mode 100644 index 0000000..cfc5ee2 --- /dev/null +++ b/node_modules/gaxios/build/src/retry.d.ts @@ -0,0 +1,8 @@ +import { GaxiosError } from './common'; +export declare function getRetryConfig(err: GaxiosError): Promise<{ + shouldRetry: boolean; + config?: undefined; +} | { + shouldRetry: boolean; + config: import("./common").GaxiosOptions; +}>; diff --git a/node_modules/gaxios/build/src/retry.js b/node_modules/gaxios/build/src/retry.js new file mode 100644 index 0000000..b25b9ad --- /dev/null +++ b/node_modules/gaxios/build/src/retry.js @@ -0,0 +1,132 @@ +"use strict"; +// Copyright 2018 Google LLC +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +async function getRetryConfig(err) { + let config = getConfig(err); + if (!err || !err.config || (!config && !err.config.retry)) { + return { shouldRetry: false }; + } + config = config || {}; + config.currentRetryAttempt = config.currentRetryAttempt || 0; + config.retry = + config.retry === undefined || config.retry === null ? 3 : config.retry; + config.httpMethodsToRetry = config.httpMethodsToRetry || [ + 'GET', + 'HEAD', + 'PUT', + 'OPTIONS', + 'DELETE', + ]; + config.noResponseRetries = + config.noResponseRetries === undefined || config.noResponseRetries === null + ? 2 + : config.noResponseRetries; + // If this wasn't in the list of status codes where we want + // to automatically retry, return. + const retryRanges = [ + // https://en.wikipedia.org/wiki/List_of_HTTP_status_codes + // 1xx - Retry (Informational, request still processing) + // 2xx - Do not retry (Success) + // 3xx - Do not retry (Redirect) + // 4xx - Do not retry (Client errors) + // 429 - Retry ("Too Many Requests") + // 5xx - Retry (Server errors) + [100, 199], + [429, 429], + [500, 599], + ]; + config.statusCodesToRetry = config.statusCodesToRetry || retryRanges; + // Put the config back into the err + err.config.retryConfig = config; + // Determine if we should retry the request + const shouldRetryFn = config.shouldRetry || shouldRetryRequest; + if (!(await shouldRetryFn(err))) { + return { shouldRetry: false, config: err.config }; + } + // Calculate time to wait with exponential backoff. + // Formula: (2^c - 1 / 2) * 1000 + const delay = ((Math.pow(2, config.currentRetryAttempt) - 1) / 2) * 1000; + // We're going to retry! Incremenent the counter. + err.config.retryConfig.currentRetryAttempt += 1; + // Create a promise that invokes the retry after the backOffDelay + const backoff = new Promise(resolve => { + setTimeout(resolve, delay); + }); + // Notify the user if they added an `onRetryAttempt` handler + if (config.onRetryAttempt) { + config.onRetryAttempt(err); + } + // Return the promise in which recalls Gaxios to retry the request + await backoff; + return { shouldRetry: true, config: err.config }; +} +exports.getRetryConfig = getRetryConfig; +/** + * Determine based on config if we should retry the request. + * @param err The GaxiosError passed to the interceptor. + */ +function shouldRetryRequest(err) { + const config = getConfig(err); + // node-fetch raises an AbortError if signaled: + // https://github.com/bitinn/node-fetch#request-cancellation-with-abortsignal + if (err.name === 'AbortError') { + return false; + } + // If there's no config, or retries are disabled, return. + if (!config || config.retry === 0) { + return false; + } + // Check if this error has no response (ETIMEDOUT, ENOTFOUND, etc) + if (!err.response && + (config.currentRetryAttempt || 0) >= config.noResponseRetries) { + return false; + } + // Only retry with configured HttpMethods. + if (!err.config.method || + config.httpMethodsToRetry.indexOf(err.config.method.toUpperCase()) < 0) { + return false; + } + // If this wasn't in the list of status codes where we want + // to automatically retry, return. + if (err.response && err.response.status) { + let isInRange = false; + for (const [min, max] of config.statusCodesToRetry) { + const status = err.response.status; + if (status >= min && status <= max) { + isInRange = true; + break; + } + } + if (!isInRange) { + return false; + } + } + // If we are out of retry attempts, return + config.currentRetryAttempt = config.currentRetryAttempt || 0; + if (config.currentRetryAttempt >= config.retry) { + return false; + } + return true; +} +/** + * Acquire the raxConfig object from an GaxiosError if available. + * @param err The Gaxios error with a config object. + */ +function getConfig(err) { + if (err && err.config && err.config.retryConfig) { + return err.config.retryConfig; + } + return; +} +//# sourceMappingURL=retry.js.map \ No newline at end of file diff --git a/node_modules/gaxios/build/src/retry.js.map b/node_modules/gaxios/build/src/retry.js.map new file mode 100644 index 0000000..e90a53f --- /dev/null +++ b/node_modules/gaxios/build/src/retry.js.map @@ -0,0 +1 @@ +{"version":3,"file":"retry.js","sourceRoot":"","sources":["../../src/retry.ts"],"names":[],"mappings":"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"} \ No newline at end of file diff --git a/node_modules/gaxios/package.json b/node_modules/gaxios/package.json new file mode 100644 index 0000000..022b388 --- /dev/null +++ b/node_modules/gaxios/package.json @@ -0,0 +1,129 @@ +{ + "_from": "gaxios@^3.0.0", + "_id": "gaxios@3.0.2", + "_inBundle": false, + "_integrity": "sha512-cLOetrsKOBLPwjzVyFzirYaGjrhtYjbKUHp6fQpsio2HH8Mil35JTFQLgkV5D3CCXV7Gnd5V69/m4C9rMBi9bA==", + "_location": "/gaxios", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "gaxios@^3.0.0", + "name": "gaxios", + "escapedName": "gaxios", + "rawSpec": "^3.0.0", + "saveSpec": null, + "fetchSpec": "^3.0.0" + }, + "_requiredBy": [ + "/google-auth-library" + ], + "_resolved": "https://registry.npmjs.org/gaxios/-/gaxios-3.0.2.tgz", + "_shasum": "ec49d0b93713d9efdc51e7a6499536854d8958fd", + "_spec": "gaxios@^3.0.0", + "_where": "/Users/cday/Code/zendesk/fetch-build-from-gcb/node_modules/google-auth-library", + "author": { + "name": "Google, LLC" + }, + "bugs": { + "url": "https://github.com/googleapis/gaxios/issues" + }, + "bundleDependencies": false, + "dependencies": { + "abort-controller": "^3.0.0", + "extend": "^3.0.2", + "https-proxy-agent": "^5.0.0", + "is-stream": "^2.0.0", + "node-fetch": "^2.3.0" + }, + "deprecated": false, + "description": "A simple common HTTP client specifically for Google APIs and services.", + "devDependencies": { + "@compodoc/compodoc": "^1.1.9", + "@types/execa": "^0.9.0", + "@types/express": "^4.16.1", + "@types/extend": "^3.0.1", + "@types/mocha": "^7.0.0", + "@types/mv": "^2.1.0", + "@types/ncp": "^2.0.1", + "@types/nock": "^10.0.0", + "@types/node": "^11.9.5", + "@types/node-fetch": "^2.1.6", + "@types/sinon": "^7.0.7", + "@types/tmp": "0.1.0", + "assert-rejects": "^1.0.0", + "c8": "^7.0.0", + "codecov": "^3.2.0", + "execa": "^4.0.0", + "express": "^4.16.4", + "gts": "2.0.0-alpha.4", + "is-docker": "^2.0.0", + "karma": "^4.0.0", + "karma-chrome-launcher": "^3.0.0", + "karma-coverage": "^2.0.0", + "karma-firefox-launcher": "^1.1.0", + "karma-mocha": "^1.3.0", + "karma-remap-coverage": "^0.1.5", + "karma-sourcemap-loader": "^0.3.7", + "karma-webpack": "^4.0.0", + "linkinator": "^2.0.0", + "mocha": "^7.0.0", + "mv": "^2.1.1", + "ncp": "^2.0.0", + "nock": "^12.0.0", + "null-loader": "^3.0.0", + "puppeteer": "^2.0.0", + "sinon": "^9.0.0", + "tmp": "0.1.0", + "ts-loader": "^6.0.0", + "typescript": "^3.8.3", + "webpack": "^4.29.5", + "webpack-cli": "^3.2.3" + }, + "engines": { + "node": ">=10" + }, + "files": [ + "build/src" + ], + "homepage": "https://github.com/googleapis/gaxios#readme", + "keywords": [ + "google" + ], + "license": "Apache-2.0", + "main": "build/src/index.js", + "name": "gaxios", + "repository": { + "type": "git", + "url": "git+https://github.com/googleapis/gaxios.git" + }, + "scripts": { + "browser-test": "node build/browser-test/browser-test-runner.js", + "compile": "tsc -p .", + "docs": "compodoc src/", + "docs-test": "linkinator docs", + "fix": "gts fix", + "lint": "gts check", + "prebrowser-test": "npm run compile", + "predocs-test": "npm run docs", + "prelint": "cd samples; npm link ../; npm i", + "prepare": "npm run compile", + "presystem-test": "npm run compile", + "pretest": "npm run compile", + "samples-test": "cd samples/ && npm link ../ && npm test && cd ../", + "system-test": "mocha build/system-test --timeout 40000", + "test": "c8 mocha build/test", + "webpack": "webpack" + }, + "types": "build/src/index.d.ts", + "version": "3.0.2", + "warnings": [ + { + "code": "ENOTSUP", + "required": { + "node": ">=10" + }, + "pkgid": "gaxios@3.0.2" + } + ] +} diff --git a/node_modules/gcp-metadata/CHANGELOG.md b/node_modules/gcp-metadata/CHANGELOG.md new file mode 100644 index 0000000..f554984 --- /dev/null +++ b/node_modules/gcp-metadata/CHANGELOG.md @@ -0,0 +1,315 @@ +# Changelog + +[npm history][1] + +[1]: https://www.npmjs.com/package/gcp-metadata?activeTab=versions + +## [4.0.0](https://www.github.com/googleapis/gcp-metadata/compare/v3.5.0...v4.0.0) (2020-03-19) + + +### ⚠ BREAKING CHANGES + +* typescript@3.7.x has breaking changes; compiler now targets es2015 +* drops Node 8 from engines field (#315) + +### Features + +* drops Node 8 from engines field ([#315](https://www.github.com/googleapis/gcp-metadata/issues/315)) ([acb6233](https://www.github.com/googleapis/gcp-metadata/commit/acb62337e8ba7f0b259ae4e553f19c5786207d84)) + + +### Build System + +* switch to latest typescirpt/gts ([#317](https://www.github.com/googleapis/gcp-metadata/issues/317)) ([fbb7158](https://www.github.com/googleapis/gcp-metadata/commit/fbb7158be62c9f1949b69079e35113be1e10495c)) + +## [3.5.0](https://www.github.com/googleapis/gcp-metadata/compare/v3.4.0...v3.5.0) (2020-03-03) + + +### Features + +* add ECONNREFUSED to list of known errors for isAvailable() ([#309](https://www.github.com/googleapis/gcp-metadata/issues/309)) ([17ff6ea](https://www.github.com/googleapis/gcp-metadata/commit/17ff6ea361d02de31463532d4ab4040bf6276e0b)) + +## [3.4.0](https://www.github.com/googleapis/gcp-metadata/compare/v3.3.1...v3.4.0) (2020-02-24) + + +### Features + +* significantly increase timeout if GCF environment detected ([#300](https://www.github.com/googleapis/gcp-metadata/issues/300)) ([8e507c6](https://www.github.com/googleapis/gcp-metadata/commit/8e507c645f69a11f508884b3181dc4414e579fcc)) + +### [3.3.1](https://www.github.com/googleapis/gcp-metadata/compare/v3.3.0...v3.3.1) (2020-01-30) + + +### Bug Fixes + +* **isAvailable:** handle EHOSTDOWN and EHOSTUNREACH error codes ([#291](https://www.github.com/googleapis/gcp-metadata/issues/291)) ([ba8d9f5](https://www.github.com/googleapis/gcp-metadata/commit/ba8d9f50eac6cf8b439c1b66c48ace146c75f6e2)) + +## [3.3.0](https://www.github.com/googleapis/gcp-metadata/compare/v3.2.3...v3.3.0) (2019-12-16) + + +### Features + +* add environment variable for configuring environment detection ([#275](https://www.github.com/googleapis/gcp-metadata/issues/275)) ([580cfa4](https://www.github.com/googleapis/gcp-metadata/commit/580cfa4a5f5d0041aa09ae85cfc5a4575dd3957f)) +* cache response from isAvailable() method ([#274](https://www.github.com/googleapis/gcp-metadata/issues/274)) ([a05e13f](https://www.github.com/googleapis/gcp-metadata/commit/a05e13f1d1d61b1f9b9b1703bc37cdbdc022c93b)) + + +### Bug Fixes + +* fastFailMetadataRequest should not reject, if response already happened ([#273](https://www.github.com/googleapis/gcp-metadata/issues/273)) ([a6590c4](https://www.github.com/googleapis/gcp-metadata/commit/a6590c4fd8bc2dff3995c83d4c9175d5bd9f5e4a)) + +### [3.2.3](https://www.github.com/googleapis/gcp-metadata/compare/v3.2.2...v3.2.3) (2019-12-12) + + +### Bug Fixes + +* **deps:** pin TypeScript below 3.7.0 ([e4bf622](https://www.github.com/googleapis/gcp-metadata/commit/e4bf622e6654a51ddffc0921a15250130591db2f)) + +### [3.2.2](https://www.github.com/googleapis/gcp-metadata/compare/v3.2.1...v3.2.2) (2019-11-13) + + +### Bug Fixes + +* **docs:** add jsdoc-region-tag plugin ([#264](https://www.github.com/googleapis/gcp-metadata/issues/264)) ([af8362b](https://www.github.com/googleapis/gcp-metadata/commit/af8362b5a35d270af00cb3696bbf7344810e9b0c)) + +### [3.2.1](https://www.github.com/googleapis/gcp-metadata/compare/v3.2.0...v3.2.1) (2019-11-08) + + +### Bug Fixes + +* **deps:** update gaxios ([#257](https://www.github.com/googleapis/gcp-metadata/issues/257)) ([ba6e0b6](https://www.github.com/googleapis/gcp-metadata/commit/ba6e0b668635b4aa4ed10535ff021c02b2edf5ea)) + +## [3.2.0](https://www.github.com/googleapis/gcp-metadata/compare/v3.1.0...v3.2.0) (2019-10-10) + + +### Features + +* add DEBUG_AUTH for digging into authentication issues ([#254](https://www.github.com/googleapis/gcp-metadata/issues/254)) ([804156d](https://www.github.com/googleapis/gcp-metadata/commit/804156d)) + +## [3.1.0](https://www.github.com/googleapis/gcp-metadata/compare/v3.0.0...v3.1.0) (2019-10-07) + + +### Features + +* don't throw on ENETUNREACH ([#250](https://www.github.com/googleapis/gcp-metadata/issues/250)) ([88f2101](https://www.github.com/googleapis/gcp-metadata/commit/88f2101)) + +## [3.0.0](https://www.github.com/googleapis/gcp-metadata/compare/v2.0.4...v3.0.0) (2019-09-17) + + +### ⚠ BREAKING CHANGES + +* isAvailable now tries both DNS and IP, choosing whichever responds first (#239) + +### Features + +* isAvailable now tries both DNS and IP, choosing whichever responds first ([#239](https://www.github.com/googleapis/gcp-metadata/issues/239)) ([25bc116](https://www.github.com/googleapis/gcp-metadata/commit/25bc116)) + +### [2.0.4](https://www.github.com/googleapis/gcp-metadata/compare/v2.0.3...v2.0.4) (2019-09-13) + + +### Bug Fixes + +* IP address takes 15 seconds to timeout, vs., metadata returning immediately ([#235](https://www.github.com/googleapis/gcp-metadata/issues/235)) ([d04207b](https://www.github.com/googleapis/gcp-metadata/commit/d04207b)) +* use 3s timeout rather than 15 default ([#237](https://www.github.com/googleapis/gcp-metadata/issues/237)) ([231ca5c](https://www.github.com/googleapis/gcp-metadata/commit/231ca5c)) + +### [2.0.3](https://www.github.com/googleapis/gcp-metadata/compare/v2.0.2...v2.0.3) (2019-09-12) + + +### Bug Fixes + +* use IP for metadata server ([#233](https://www.github.com/googleapis/gcp-metadata/issues/233)) ([20a15cb](https://www.github.com/googleapis/gcp-metadata/commit/20a15cb)) + +### [2.0.2](https://www.github.com/googleapis/gcp-metadata/compare/v2.0.1...v2.0.2) (2019-08-26) + + +### Bug Fixes + +* allow calls with no request, add JSON proto ([#224](https://www.github.com/googleapis/gcp-metadata/issues/224)) ([dc758b1](https://www.github.com/googleapis/gcp-metadata/commit/dc758b1)) + +### [2.0.1](https://www.github.com/googleapis/gcp-metadata/compare/v2.0.0...v2.0.1) (2019-06-26) + + +### Bug Fixes + +* **docs:** make anchors work in jsdoc ([#212](https://www.github.com/googleapis/gcp-metadata/issues/212)) ([9174b43](https://www.github.com/googleapis/gcp-metadata/commit/9174b43)) + +## [2.0.0](https://www.github.com/googleapis/gcp-metadata/compare/v1.0.0...v2.0.0) (2019-05-07) + + +### Bug Fixes + +* **deps:** update dependency gaxios to v2 ([#191](https://www.github.com/googleapis/gcp-metadata/issues/191)) ([ac8c1ef](https://www.github.com/googleapis/gcp-metadata/commit/ac8c1ef)) + + +### Build System + +* upgrade engines field to >=8.10.0 ([#194](https://www.github.com/googleapis/gcp-metadata/issues/194)) ([97c23c8](https://www.github.com/googleapis/gcp-metadata/commit/97c23c8)) + + +### BREAKING CHANGES + +* upgrade engines field to >=8.10.0 (#194) + +## v1.0.0 + +02-14-2019 16:00 PST + +### Bug Fixes +- fix: ask gaxios for text and not json ([#152](https://github.com/googleapis/gcp-metadata/pull/152)) + +### Documentation +- docs: update links in contrib guide ([#168](https://github.com/googleapis/gcp-metadata/pull/168)) +- docs: add lint/fix example to contributing guide ([#160](https://github.com/googleapis/gcp-metadata/pull/160)) + +### Internal / Testing Changes +- build: use linkinator for docs test ([#166](https://github.com/googleapis/gcp-metadata/pull/166)) +- chore(deps): update dependency @types/tmp to v0.0.34 ([#167](https://github.com/googleapis/gcp-metadata/pull/167)) +- build: create docs test npm scripts ([#165](https://github.com/googleapis/gcp-metadata/pull/165)) +- test: run system tests on GCB ([#157](https://github.com/googleapis/gcp-metadata/pull/157)) +- build: test using @grpc/grpc-js in CI ([#164](https://github.com/googleapis/gcp-metadata/pull/164)) +- chore: move CONTRIBUTING.md to root ([#162](https://github.com/googleapis/gcp-metadata/pull/162)) +- chore(deps): update dependency gcx to v0.1.1 ([#159](https://github.com/googleapis/gcp-metadata/pull/159)) +- chore(deps): update dependency gcx to v0.1.0 ([#158](https://github.com/googleapis/gcp-metadata/pull/158)) +- chore(deps): update dependency gcx to v0.0.4 ([#155](https://github.com/googleapis/gcp-metadata/pull/155)) +- chore(deps): update dependency googleapis to v37 ([#156](https://github.com/googleapis/gcp-metadata/pull/156)) +- build: ignore googleapis.com in doc link check ([#153](https://github.com/googleapis/gcp-metadata/pull/153)) +- build: check broken links in generated docs ([#149](https://github.com/googleapis/gcp-metadata/pull/149)) +- chore(build): inject yoshi automation key ([#148](https://github.com/googleapis/gcp-metadata/pull/148)) + +## v0.9.3 + +12-10-2018 16:16 PST + +### Dependencies +- chore(deps): update dependency googleapis to v36 ([#135](https://github.com/googleapis/gcp-metadata/pull/135)) +- chore(deps): use gaxios for http requests ([#121](https://github.com/googleapis/gcp-metadata/pull/121)) +- chore(deps): update dependency gts to ^0.9.0 ([#123](https://github.com/googleapis/gcp-metadata/pull/123)) + +### Internal / Testing Changes +- fix(build): fix Kokoro release script ([#141](https://github.com/googleapis/gcp-metadata/pull/141)) +- Release v0.9.2 ([#140](https://github.com/googleapis/gcp-metadata/pull/140)) +- build: add Kokoro configs for autorelease ([#138](https://github.com/googleapis/gcp-metadata/pull/138)) +- Release gcp-metadata v0.9.1 ([#139](https://github.com/googleapis/gcp-metadata/pull/139)) +- chore: always nyc report before calling codecov ([#134](https://github.com/googleapis/gcp-metadata/pull/134)) +- chore: nyc ignore build/test by default ([#133](https://github.com/googleapis/gcp-metadata/pull/133)) +- Sync repo build files ([#131](https://github.com/googleapis/gcp-metadata/pull/131)) +- fix(build): fix system key decryption ([#128](https://github.com/googleapis/gcp-metadata/pull/128)) +- refactor: use execa, move post install test to system ([#127](https://github.com/googleapis/gcp-metadata/pull/127)) +- chore: add a synth.metadata +- test: add a system test ([#126](https://github.com/googleapis/gcp-metadata/pull/126)) +- chore: update eslintignore config ([#122](https://github.com/googleapis/gcp-metadata/pull/122)) +- chore: use latest npm on Windows ([#120](https://github.com/googleapis/gcp-metadata/pull/120)) +- chore: update CircleCI config ([#119](https://github.com/googleapis/gcp-metadata/pull/119)) +- chore: include build in eslintignore ([#115](https://github.com/googleapis/gcp-metadata/pull/115)) + +## v0.9.2 + +12-10-2018 14:01 PST + +- chore(deps): update dependency googleapis to v36 ([#135](https://github.com/googleapis/gcp-metadata/pull/135)) +- chore: always nyc report before calling codecov ([#134](https://github.com/googleapis/gcp-metadata/pull/134)) +- chore: nyc ignore build/test by default ([#133](https://github.com/googleapis/gcp-metadata/pull/133)) +- chore: Re-generated to pick up changes in the API or client library generator. ([#131](https://github.com/googleapis/gcp-metadata/pull/131)) +- fix(build): fix system key decryption ([#128](https://github.com/googleapis/gcp-metadata/pull/128)) +- chore(deps): use gaxios for http requests ([#121](https://github.com/googleapis/gcp-metadata/pull/121)) +- refactor: use execa, move post install test to system ([#127](https://github.com/googleapis/gcp-metadata/pull/127)) +- chore: add a synth.metadata +- test: add a system test ([#126](https://github.com/googleapis/gcp-metadata/pull/126)) +- chore(deps): update dependency gts to ^0.9.0 ([#123](https://github.com/googleapis/gcp-metadata/pull/123)) +- chore: update eslintignore config ([#122](https://github.com/googleapis/gcp-metadata/pull/122)) +- chore: use latest npm on Windows ([#120](https://github.com/googleapis/gcp-metadata/pull/120)) +- chore: update CircleCI config ([#119](https://github.com/googleapis/gcp-metadata/pull/119)) +- chore: include build in eslintignore ([#115](https://github.com/googleapis/gcp-metadata/pull/115)) +- build: add Kokoro configs for autorelease ([#138](https://github.com/googleapis/gcp-metadata/pull/138)) + +## v0.9.1 + +12-10-2018 11:53 PST + +- chore(deps): update dependency googleapis to v36 ([#135](https://github.com/googleapis/gcp-metadata/pull/135)) +- chore: always nyc report before calling codecov ([#134](https://github.com/googleapis/gcp-metadata/pull/134)) +- chore: nyc ignore build/test by default ([#133](https://github.com/googleapis/gcp-metadata/pull/133)) +- chore: Re-generated to pick up changes in the API or client library generator. ([#131](https://github.com/googleapis/gcp-metadata/pull/131)) +- fix(build): fix system key decryption ([#128](https://github.com/googleapis/gcp-metadata/pull/128)) +- chore(deps): use gaxios for http requests ([#121](https://github.com/googleapis/gcp-metadata/pull/121)) +- refactor: use execa, move post install test to system ([#127](https://github.com/googleapis/gcp-metadata/pull/127)) +- chore: add a synth.metadata +- test: add a system test ([#126](https://github.com/googleapis/gcp-metadata/pull/126)) +- chore(deps): update dependency gts to ^0.9.0 ([#123](https://github.com/googleapis/gcp-metadata/pull/123)) +- chore: update eslintignore config ([#122](https://github.com/googleapis/gcp-metadata/pull/122)) +- chore: use latest npm on Windows ([#120](https://github.com/googleapis/gcp-metadata/pull/120)) +- chore: update CircleCI config ([#119](https://github.com/googleapis/gcp-metadata/pull/119)) +- chore: include build in eslintignore ([#115](https://github.com/googleapis/gcp-metadata/pull/115)) + +## v0.9.0 + +10-26-2018 13:10 PDT + +- feat: allow custom headers ([#109](https://github.com/googleapis/gcp-metadata/pull/109)) +- chore: update issue templates ([#108](https://github.com/googleapis/gcp-metadata/pull/108)) +- chore: remove old issue template ([#106](https://github.com/googleapis/gcp-metadata/pull/106)) +- build: run tests on node11 ([#105](https://github.com/googleapis/gcp-metadata/pull/105)) +- chores(build): do not collect sponge.xml from windows builds ([#104](https://github.com/googleapis/gcp-metadata/pull/104)) +- chores(build): run codecov on continuous builds ([#102](https://github.com/googleapis/gcp-metadata/pull/102)) +- chore(deps): update dependency nock to v10 ([#103](https://github.com/googleapis/gcp-metadata/pull/103)) +- chore: update new issue template ([#101](https://github.com/googleapis/gcp-metadata/pull/101)) +- build: fix codecov uploading on Kokoro ([#97](https://github.com/googleapis/gcp-metadata/pull/97)) +- Update kokoro config ([#95](https://github.com/googleapis/gcp-metadata/pull/95)) +- Update CI config ([#93](https://github.com/googleapis/gcp-metadata/pull/93)) +- Update kokoro config ([#91](https://github.com/googleapis/gcp-metadata/pull/91)) +- Re-generate library using /synth.py ([#90](https://github.com/googleapis/gcp-metadata/pull/90)) +- test: remove appveyor config ([#89](https://github.com/googleapis/gcp-metadata/pull/89)) +- Update kokoro config ([#88](https://github.com/googleapis/gcp-metadata/pull/88)) +- Enable prefer-const in the eslint config ([#87](https://github.com/googleapis/gcp-metadata/pull/87)) +- Enable no-var in eslint ([#86](https://github.com/googleapis/gcp-metadata/pull/86)) + +### New Features + +A new option, `headers`, has been added to allow metadata queries to be sent with custom headers. + +## v0.8.0 + +**This release has breaking changes**. Please take care when upgrading to the latest version. + +#### Dropped support for Node.js 4.x and 9.x +This library is no longer tested against versions 4.x and 9.x of Node.js. Please upgrade to the latest supported LTS version! + +#### Return type of `instance()` and `project()` has changed +The `instance()` and `project()` methods are much more selective about which properties they will accept. + +The only accepted properties are `params` and `properties`. The `instance()` and `project()` methods also now directly return the data instead of a response object. + +#### Changes in how large number valued properties are handled + +Previously large number-valued properties were being silently losing precision when +returned by this library (as a number). In the cases where a number valued property +returned by the metadata service is too large to represent as a JavaScript number, we +will now return the value as a BigNumber (from the bignumber.js) library. Numbers that +do fit into the JavaScript number range will continue to be returned as numbers. +For more details see [#74](https://github.com/googleapis/gcp-metadata/pull/74). + +### Breaking Changes +- chore: drop support for node.js 4 and 9 ([#68](https://github.com/googleapis/gcp-metadata/pull/68)) +- fix: quarantine axios config ([#62](https://github.com/googleapis/gcp-metadata/pull/62)) + +### Implementation Changes +- fix: properly handle large numbers in responses ([#74](https://github.com/googleapis/gcp-metadata/pull/74)) + +### Dependencies +- chore(deps): update dependency pify to v4 ([#73](https://github.com/googleapis/gcp-metadata/pull/73)) + +### Internal / Testing Changes +- Move to the new github org ([#84](https://github.com/googleapis/gcp-metadata/pull/84)) +- Update CI config ([#83](https://github.com/googleapis/gcp-metadata/pull/83)) +- Retry npm install in CI ([#81](https://github.com/googleapis/gcp-metadata/pull/81)) +- Update CI config ([#79](https://github.com/googleapis/gcp-metadata/pull/79)) +- chore(deps): update dependency nyc to v13 ([#77](https://github.com/googleapis/gcp-metadata/pull/77)) +- add key for system tests +- increase kitchen test timeout +- add a lint npm script +- update npm scripts +- add a synth file and run it ([#75](https://github.com/googleapis/gcp-metadata/pull/75)) +- chore(deps): update dependency assert-rejects to v1 ([#72](https://github.com/googleapis/gcp-metadata/pull/72)) +- chore: ignore package-log.json ([#71](https://github.com/googleapis/gcp-metadata/pull/71)) +- chore: update renovate config ([#70](https://github.com/googleapis/gcp-metadata/pull/70)) +- test: throw on deprecation +- chore(deps): update dependency typescript to v3 ([#67](https://github.com/googleapis/gcp-metadata/pull/67)) +- chore: make it OSPO compliant ([#66](https://github.com/googleapis/gcp-metadata/pull/66)) +- chore(deps): update dependency gts to ^0.8.0 ([#65](https://github.com/googleapis/gcp-metadata/pull/65)) diff --git a/node_modules/gcp-metadata/LICENSE b/node_modules/gcp-metadata/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/node_modules/gcp-metadata/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. 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 and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/gcp-metadata/README.md b/node_modules/gcp-metadata/README.md new file mode 100644 index 0000000..b444f6c --- /dev/null +++ b/node_modules/gcp-metadata/README.md @@ -0,0 +1,65 @@ +# gcp-metadata +> Get the metadata from a Google Cloud Platform environment. + +[![NPM Version][npm-image]][npm-url] +[![codecov][codecov-image]][codecov-url] + +```sh +$ npm install --save gcp-metadata +``` +```js +const gcpMetadata = require('gcp-metadata'); +``` + +#### Check to see if the metadata server is available +```js +const isAvailable = await gcpMetadata.isAvailable(); +``` + +#### Access all metadata +```js +const data = await gcpMetadata.instance(); +console.log(data); // ... All metadata properties +``` + +#### Access specific properties +```js +const data = await gcpMetadata.instance('hostname'); +console.log(data) // ...Instance hostname +``` + +#### Access specific properties with query parameters +```js +const data = await gcpMetadata.instance({ + property: 'tags', + params: { alt: 'text' } +}); +console.log(data) // ...Tags as newline-delimited list +``` + +#### Access with custom headers +```js +await gcpMetadata.instance({ + headers: { 'no-trace': '1' } +}); // ...Request is untraced +``` + +### Take care with large number valued properties + +In some cases number valued properties returned by the Metadata Service may be +too large to be representable as JavaScript numbers. In such cases we return +those values as `BigNumber` objects (from the [bignumber.js][] library). Numbers +that fit within the JavaScript number range will be returned as normal number +values. + +```js +const id = await gcpMetadata.instance('id'); +console.log(id) // ... BigNumber { s: 1, e: 18, c: [ 45200, 31799277581759 ] } +console.log(id.toString()) // ... 4520031799277581759 +``` + +[bignumber.js]: https://github.com/MikeMcl/bignumber.js +[codecov-image]: https://codecov.io/gh/googleapis/gcp-metadata/branch/master/graph/badge.svg +[codecov-url]: https://codecov.io/gh/googleapis/gcp-metadata +[npm-image]: https://img.shields.io/npm/v/gcp-metadata.svg +[npm-url]: https://www.npmjs.com/package/gcp-metadata \ No newline at end of file diff --git a/node_modules/gcp-metadata/build/src/index.d.ts b/node_modules/gcp-metadata/build/src/index.d.ts new file mode 100644 index 0000000..6874a93 --- /dev/null +++ b/node_modules/gcp-metadata/build/src/index.d.ts @@ -0,0 +1,33 @@ +/** + * Copyright 2018 Google LLC + * + * Distributed under MIT license. + * See file LICENSE for detail or copy at https://opensource.org/licenses/MIT + */ +/// +import { OutgoingHttpHeaders } from 'http'; +export declare const HOST_ADDRESS = "http://169.254.169.254"; +export declare const BASE_PATH = "/computeMetadata/v1"; +export declare const BASE_URL: string; +export declare const SECONDARY_HOST_ADDRESS = "http://metadata.google.internal."; +export declare const SECONDARY_BASE_URL: string; +export declare const HEADER_NAME = "Metadata-Flavor"; +export declare const HEADER_VALUE = "Google"; +export declare const HEADERS: Readonly<{ + "Metadata-Flavor": string; +}>; +export interface Options { + params?: { + [index: string]: string; + }; + property?: string; + headers?: OutgoingHttpHeaders; +} +export declare function instance(options?: string | Options): Promise; +export declare function project(options?: string | Options): Promise; +export declare function isAvailable(): Promise; +/** + * reset the memoized isAvailable() lookup. + */ +export declare function resetIsAvailableCache(): void; +export declare function requestTimeout(): number; diff --git a/node_modules/gcp-metadata/build/src/index.js b/node_modules/gcp-metadata/build/src/index.js new file mode 100644 index 0000000..c625a5b --- /dev/null +++ b/node_modules/gcp-metadata/build/src/index.js @@ -0,0 +1,217 @@ +"use strict"; +/** + * Copyright 2018 Google LLC + * + * Distributed under MIT license. + * See file LICENSE for detail or copy at https://opensource.org/licenses/MIT + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const gaxios_1 = require("gaxios"); +const jsonBigint = require('json-bigint'); // eslint-disable-line +exports.HOST_ADDRESS = 'http://169.254.169.254'; +exports.BASE_PATH = '/computeMetadata/v1'; +exports.BASE_URL = exports.HOST_ADDRESS + exports.BASE_PATH; +exports.SECONDARY_HOST_ADDRESS = 'http://metadata.google.internal.'; +exports.SECONDARY_BASE_URL = exports.SECONDARY_HOST_ADDRESS + exports.BASE_PATH; +exports.HEADER_NAME = 'Metadata-Flavor'; +exports.HEADER_VALUE = 'Google'; +exports.HEADERS = Object.freeze({ [exports.HEADER_NAME]: exports.HEADER_VALUE }); +// Accepts an options object passed from the user to the API. In previous +// versions of the API, it referred to a `Request` or an `Axios` request +// options object. Now it refers to an object with very limited property +// names. This is here to help ensure users don't pass invalid options when +// they upgrade from 0.4 to 0.5 to 0.8. +function validate(options) { + Object.keys(options).forEach(key => { + switch (key) { + case 'params': + case 'property': + case 'headers': + break; + case 'qs': + throw new Error(`'qs' is not a valid configuration option. Please use 'params' instead.`); + default: + throw new Error(`'${key}' is not a valid configuration option.`); + } + }); +} +async function metadataAccessor(type, options, noResponseRetries = 3, fastFail = false) { + options = options || {}; + if (typeof options === 'string') { + options = { property: options }; + } + let property = ''; + if (typeof options === 'object' && options.property) { + property = '/' + options.property; + } + validate(options); + try { + const requestMethod = fastFail ? fastFailMetadataRequest : gaxios_1.request; + const res = await requestMethod({ + url: `${exports.BASE_URL}/${type}${property}`, + headers: Object.assign({}, exports.HEADERS, options.headers), + retryConfig: { noResponseRetries }, + params: options.params, + responseType: 'text', + timeout: requestTimeout(), + }); + // NOTE: node.js converts all incoming headers to lower case. + if (res.headers[exports.HEADER_NAME.toLowerCase()] !== exports.HEADER_VALUE) { + throw new Error(`Invalid response from metadata service: incorrect ${exports.HEADER_NAME} header.`); + } + else if (!res.data) { + throw new Error('Invalid response from the metadata service'); + } + if (typeof res.data === 'string') { + try { + return jsonBigint.parse(res.data); + } + catch (_a) { + /* ignore */ + } + } + return res.data; + } + catch (e) { + if (e.response && e.response.status !== 200) { + e.message = `Unsuccessful response status code. ${e.message}`; + } + throw e; + } +} +async function fastFailMetadataRequest(options) { + const secondaryOptions = { + ...options, + url: options.url.replace(exports.BASE_URL, exports.SECONDARY_BASE_URL), + }; + // We race a connection between DNS/IP to metadata server. There are a couple + // reasons for this: + // + // 1. the DNS is slow in some GCP environments; by checking both, we might + // detect the runtime environment signficantly faster. + // 2. we can't just check the IP, which is tarpitted and slow to respond + // on a user's local machine. + // + // Additional logic has been added to make sure that we don't create an + // unhandled rejection in scenarios where a failure happens sometime + // after a success. + // + // Note, however, if a failure happens prior to a success, a rejection should + // occur, this is for folks running locally. + // + let responded = false; + const r1 = gaxios_1.request(options) + .then(res => { + responded = true; + return res; + }) + .catch(err => { + if (responded) { + return r2; + } + else { + responded = true; + throw err; + } + }); + const r2 = gaxios_1.request(secondaryOptions) + .then(res => { + responded = true; + return res; + }) + .catch(err => { + if (responded) { + return r1; + } + else { + responded = true; + throw err; + } + }); + return Promise.race([r1, r2]); +} +// tslint:disable-next-line no-any +function instance(options) { + return metadataAccessor('instance', options); +} +exports.instance = instance; +// tslint:disable-next-line no-any +function project(options) { + return metadataAccessor('project', options); +} +exports.project = project; +/* + * How many times should we retry detecting GCP environment. + */ +function detectGCPAvailableRetries() { + return process.env.DETECT_GCP_RETRIES + ? Number(process.env.DETECT_GCP_RETRIES) + : 0; +} +/** + * Determine if the metadata server is currently available. + */ +let cachedIsAvailableResponse; +async function isAvailable() { + try { + // If a user is instantiating several GCP libraries at the same time, + // this may result in multiple calls to isAvailable(), to detect the + // runtime environment. We use the same promise for each of these calls + // to reduce the network load. + if (cachedIsAvailableResponse === undefined) { + cachedIsAvailableResponse = metadataAccessor('instance', undefined, detectGCPAvailableRetries(), true); + } + await cachedIsAvailableResponse; + return true; + } + catch (err) { + if (process.env.DEBUG_AUTH) { + console.info(err); + } + if (err.type === 'request-timeout') { + // If running in a GCP environment, metadata endpoint should return + // within ms. + return false; + } + else if (err.code && + [ + 'EHOSTDOWN', + 'EHOSTUNREACH', + 'ENETUNREACH', + 'ENOENT', + 'ENOTFOUND', + 'ECONNREFUSED', + ].includes(err.code)) { + // Failure to resolve the metadata service means that it is not available. + return false; + } + else if (err.response && err.response.status === 404) { + return false; + } + // Throw unexpected errors. + throw err; + } +} +exports.isAvailable = isAvailable; +/** + * reset the memoized isAvailable() lookup. + */ +function resetIsAvailableCache() { + cachedIsAvailableResponse = undefined; +} +exports.resetIsAvailableCache = resetIsAvailableCache; +function requestTimeout() { + // In testing, we were able to reproduce behavior similar to + // https://github.com/googleapis/google-auth-library-nodejs/issues/798 + // by making many concurrent network requests. Requests do not actually fail, + // rather they take significantly longer to complete (and we hit our + // default 3000ms timeout). + // + // This logic detects a GCF environment, using the documented environment + // variables K_SERVICE and FUNCTION_NAME: + // https://cloud.google.com/functions/docs/env-var and, in a GCF environment + // eliminates timeouts (by setting the value to 0 to disable). + return process.env.K_SERVICE || process.env.FUNCTION_NAME ? 0 : 3000; +} +exports.requestTimeout = requestTimeout; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/gcp-metadata/build/src/index.js.map b/node_modules/gcp-metadata/build/src/index.js.map new file mode 100644 index 0000000..5652807 --- /dev/null +++ b/node_modules/gcp-metadata/build/src/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"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"} \ No newline at end of file diff --git a/node_modules/gcp-metadata/node_modules/gaxios/CHANGELOG.md b/node_modules/gcp-metadata/node_modules/gaxios/CHANGELOG.md new file mode 100644 index 0000000..9bd3242 --- /dev/null +++ b/node_modules/gcp-metadata/node_modules/gaxios/CHANGELOG.md @@ -0,0 +1,87 @@ +# Changelog + +### [2.3.2](https://www.github.com/googleapis/gaxios/compare/v2.3.1...v2.3.2) (2020-02-28) + + +### Bug Fixes + +* update github repo in package ([#239](https://www.github.com/googleapis/gaxios/issues/239)) ([7e750cb](https://www.github.com/googleapis/gaxios/commit/7e750cbaaa59812817d725c74fb9d364c4b71096)) + +### [2.3.1](https://www.github.com/googleapis/gaxios/compare/v2.3.0...v2.3.1) (2020-02-13) + + +### Bug Fixes + +* **deps:** update dependency https-proxy-agent to v5 ([#233](https://www.github.com/googleapis/gaxios/issues/233)) ([56de0a8](https://www.github.com/googleapis/gaxios/commit/56de0a824a2f9622e3e4d4bdd41adccd812a30b4)) + +## [2.3.0](https://www.github.com/googleapis/gaxios/compare/v2.2.2...v2.3.0) (2020-01-31) + + +### Features + +* add promise support for onRetryAttempt and shouldRetry ([#223](https://www.github.com/googleapis/gaxios/issues/223)) ([061afa3](https://www.github.com/googleapis/gaxios/commit/061afa381a51d39823e63accf3dacd16e191f3b9)) + +### [2.2.2](https://www.github.com/googleapis/gaxios/compare/v2.2.1...v2.2.2) (2020-01-08) + + +### Bug Fixes + +* **build:** add publication configuration ([#218](https://www.github.com/googleapis/gaxios/issues/218)) ([43e581f](https://www.github.com/googleapis/gaxios/commit/43e581ff4ed5e79d72f6f29748a5eebb6bff1229)) + +### [2.2.1](https://www.github.com/googleapis/gaxios/compare/v2.2.0...v2.2.1) (2020-01-04) + + +### Bug Fixes + +* **deps:** update dependency https-proxy-agent to v4 ([#201](https://www.github.com/googleapis/gaxios/issues/201)) ([5cdeef2](https://www.github.com/googleapis/gaxios/commit/5cdeef288a0c5c544c0dc2659aafbb2215d06c4b)) +* remove retryDelay option ([#203](https://www.github.com/googleapis/gaxios/issues/203)) ([d21e08d](https://www.github.com/googleapis/gaxios/commit/d21e08d2aada980d39bc5ca7093d54452be2d646)) + +## [2.2.0](https://www.github.com/googleapis/gaxios/compare/v2.1.1...v2.2.0) (2019-12-05) + + +### Features + +* populate GaxiosResponse with raw response information (res.url) ([#189](https://www.github.com/googleapis/gaxios/issues/189)) ([53a7f54](https://www.github.com/googleapis/gaxios/commit/53a7f54cc0f20320d7a6a21a9a9f36050cec2eec)) + + +### Bug Fixes + +* don't retry a request that is aborted intentionally ([#190](https://www.github.com/googleapis/gaxios/issues/190)) ([ba9777b](https://www.github.com/googleapis/gaxios/commit/ba9777b15b5262f8288a8bb3cca49a1de8427d8e)) +* **deps:** pin TypeScript below 3.7.0 ([5373f07](https://www.github.com/googleapis/gaxios/commit/5373f0793a765965a8221ecad2f99257ed1b7444)) + +### [2.1.1](https://www.github.com/googleapis/gaxios/compare/v2.1.0...v2.1.1) (2019-11-15) + + +### Bug Fixes + +* **docs:** snippets are now replaced in jsdoc comments ([#183](https://www.github.com/googleapis/gaxios/issues/183)) ([8dd1324](https://www.github.com/googleapis/gaxios/commit/8dd1324256590bd2f2e9015c813950e1cd8cb330)) + +## [2.1.0](https://www.github.com/googleapis/gaxios/compare/v2.0.3...v2.1.0) (2019-10-09) + + +### Bug Fixes + +* **deps:** update dependency https-proxy-agent to v3 ([#172](https://www.github.com/googleapis/gaxios/issues/172)) ([4a38f35](https://www.github.com/googleapis/gaxios/commit/4a38f35)) + + +### Features + +* **TypeScript:** agent can now be passed as builder method, rather than agent instance ([c84ddd6](https://www.github.com/googleapis/gaxios/commit/c84ddd6)) + +### [2.0.3](https://www.github.com/googleapis/gaxios/compare/v2.0.2...v2.0.3) (2019-09-11) + + +### Bug Fixes + +* do not override content-type if its given ([#158](https://www.github.com/googleapis/gaxios/issues/158)) ([f49e0e6](https://www.github.com/googleapis/gaxios/commit/f49e0e6)) +* improve stream detection logic ([6c41537](https://www.github.com/googleapis/gaxios/commit/6c41537)) +* revert header change ([#161](https://www.github.com/googleapis/gaxios/issues/161)) ([b0f6a8b](https://www.github.com/googleapis/gaxios/commit/b0f6a8b)) + +### [2.0.2](https://www.github.com/googleapis/gaxios/compare/v2.0.1...v2.0.2) (2019-07-23) + + +### Bug Fixes + +* check for existence of fetch before using it ([#138](https://www.github.com/googleapis/gaxios/issues/138)) ([79eb58d](https://www.github.com/googleapis/gaxios/commit/79eb58d)) +* **docs:** make anchors work in jsdoc ([#139](https://www.github.com/googleapis/gaxios/issues/139)) ([85103bb](https://www.github.com/googleapis/gaxios/commit/85103bb)) +* prevent double option processing ([#142](https://www.github.com/googleapis/gaxios/issues/142)) ([19b4b3c](https://www.github.com/googleapis/gaxios/commit/19b4b3c)) diff --git a/node_modules/gcp-metadata/node_modules/gaxios/LICENSE b/node_modules/gcp-metadata/node_modules/gaxios/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/node_modules/gcp-metadata/node_modules/gaxios/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. 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 and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/gcp-metadata/node_modules/gaxios/README.md b/node_modules/gcp-metadata/node_modules/gaxios/README.md new file mode 100644 index 0000000..a25f3bd --- /dev/null +++ b/node_modules/gcp-metadata/node_modules/gaxios/README.md @@ -0,0 +1,138 @@ +# gaxios + +[![npm version](https://img.shields.io/npm/v/gaxios.svg)](https://www.npmjs.org/package/gaxios) +[![codecov](https://codecov.io/gh/googleapis/gaxios/branch/master/graph/badge.svg)](https://codecov.io/gh/googleapis/gaxios) +[![Code Style: Google](https://img.shields.io/badge/code%20style-google-blueviolet.svg)](https://github.com/google/gts) + +> An HTTP request client that provides an `axios` like interface over top of `node-fetch`. + +## Install +```sh +$ npm install gaxios +``` + +## Example + +```js +const {request} = require('gaxios'); +const res = await request({ + url: 'https://www.googleapis.com/discovery/v1/apis/' +}); +``` + +## Setting Defaults +Gaxios supports setting default properties both on the default instance, and on additional instances. This is often useful when making many requests to the same domain with the same base settings. For example: + +```js +const gaxios = require('gaxios'); +gaxios.instance.defaults = { + baseURL: 'https://example.com' + headers: { + Authorization: 'SOME_TOKEN' + } +} +gaxios.request({url: '/data'}).then(...); +``` + +## Request Options + +```js +{ + // The url to which the request should be sent. Required. + url: string, + + // The HTTP method to use for the request. Defaults to `GET`. + method: 'GET', + + // The base Url to use for the request. Prepended to the `url` property above. + baseURL: 'https://example.com'; + + // The HTTP methods to be sent with the request. + headers: { 'some': 'header' }, + + // The data to send in the body of the request. Data objects will be serialized as JSON. + data: { + some: 'data' + }, + + // The max size of the http response content in bytes allowed. + // Defaults to `0`, which is the same as unset. + maxContentLength: 2000, + + // The max number of HTTP redirects to follow. + // Defaults to 100. + maxRedirects: 100, + + // The querystring parameters that will be encoded using `qs` and + // appended to the url + params: { + querystring: 'parameters' + }, + + // By default, we use the `querystring` package in node core to serialize + // querystring parameters. You can override that and provide your + // own implementation. + paramsSerializer: (params) => { + return qs.stringify(params); + }, + + // The timeout for the HTTP request. Defaults to 0. + timeout: 1000, + + // Optional method to override making the actual HTTP request. Useful + // for writing tests. + adapter?: (options) => { + return { + data: 'your data' + } + }; + + // The expected return type of the request. Options are: + // json | stream | blob | arraybuffer | text + // Defaults to `json`. + responseType: 'json', + + // The node.js http agent to use for the request. + agent: someHttpsAgent, + + // Custom function to determine if the response is valid based on the + // status code. Defaults to (>= 200 && < 300) + validateStatus: (status: number) => true, + + // Configuration for retrying of requests. + retryConfig: { + // The number of times to retry the request. Defaults to 3. + retry?: number; + + // The number of retries already attempted. + currentRetryAttempt?: number; + + // The HTTP Methods that will be automatically retried. + // Defaults to ['GET','PUT','HEAD','OPTIONS','DELETE'] + httpMethodsToRetry?: string[]; + + // The HTTP response status codes that will automatically be retried. + // Defaults to: [[100, 199], [429, 429], [500, 599]] + statusCodesToRetry?: number[][]; + + // Function to invoke when a retry attempt is made. + onRetryAttempt?: (err: GaxiosError) => Promise | void; + + // Function to invoke which determines if you should retry + shouldRetry?: (err: GaxiosError) => Promise | boolean; + + // When there is no response, the number of retries to attempt. Defaults to 2. + noResponseRetries?: number; + }, + + // Enables default configuration for retries. + retry: boolean, + + // Cancelling a request requires the `abort-controller` library. + // See https://github.com/bitinn/node-fetch#request-cancellation-with-abortsignal + signal?: AbortSignal +} +``` + +## License +[Apache-2.0](https://github.com/googleapis/gaxios/blob/master/LICENSE) diff --git a/node_modules/gcp-metadata/node_modules/gaxios/build/src/common.d.ts b/node_modules/gcp-metadata/node_modules/gaxios/build/src/common.d.ts new file mode 100644 index 0000000..f6635b2 --- /dev/null +++ b/node_modules/gcp-metadata/node_modules/gaxios/build/src/common.d.ts @@ -0,0 +1,104 @@ +/// +import { AbortSignal } from 'abort-controller'; +import { Agent } from 'http'; +import { URL } from 'url'; +export declare class GaxiosError extends Error { + code?: string; + response?: GaxiosResponse; + config: GaxiosOptions; + constructor(message: string, options: GaxiosOptions, response: GaxiosResponse); +} +export interface Headers { + [index: string]: any; +} +export declare type GaxiosPromise = Promise>; +export interface GaxiosXMLHttpRequest { + responseURL: string; +} +export interface GaxiosResponse { + config: GaxiosOptions; + data: T; + status: number; + statusText: string; + headers: Headers; + request: GaxiosXMLHttpRequest; +} +/** + * Request options that are used to form the request. + */ +export interface GaxiosOptions { + /** + * Optional method to override making the actual HTTP request. Useful + * for writing tests. + */ + adapter?: (options: GaxiosOptions) => GaxiosPromise; + url?: string; + baseUrl?: string; + baseURL?: string; + method?: 'GET' | 'HEAD' | 'POST' | 'DELETE' | 'PUT' | 'CONNECT' | 'OPTIONS' | 'TRACE' | 'PATCH'; + headers?: Headers; + data?: any; + body?: any; + /** + * The maximum size of the http response content in bytes allowed. + */ + maxContentLength?: number; + /** + * The maximum number of redirects to follow. Defaults to 20. + */ + maxRedirects?: number; + follow?: number; + params?: any; + paramsSerializer?: (params: { + [index: string]: string | number; + }) => string; + timeout?: number; + onUploadProgress?: (progressEvent: any) => void; + responseType?: 'arraybuffer' | 'blob' | 'json' | 'text' | 'stream'; + agent?: Agent | ((parsedUrl: URL) => Agent); + validateStatus?: (status: number) => boolean; + retryConfig?: RetryConfig; + retry?: boolean; + signal?: AbortSignal; + size?: number; +} +/** + * Configuration for the Gaxios `request` method. + */ +export interface RetryConfig { + /** + * The number of times to retry the request. Defaults to 3. + */ + retry?: number; + /** + * The number of retries already attempted. + */ + currentRetryAttempt?: number; + /** + * The amount of time to initially delay the retry. Defaults to 100. + * @deprecated + */ + retryDelay?: number; + /** + * The HTTP Methods that will be automatically retried. + * Defaults to ['GET','PUT','HEAD','OPTIONS','DELETE'] + */ + httpMethodsToRetry?: string[]; + /** + * The HTTP response status codes that will automatically be retried. + * Defaults to: [[100, 199], [429, 429], [500, 599]] + */ + statusCodesToRetry?: number[][]; + /** + * Function to invoke when a retry attempt is made. + */ + onRetryAttempt?: (err: GaxiosError) => Promise | void; + /** + * Function to invoke which determines if you should retry + */ + shouldRetry?: (err: GaxiosError) => Promise | boolean; + /** + * When there is no response, the number of retries to attempt. Defaults to 2. + */ + noResponseRetries?: number; +} diff --git a/node_modules/gcp-metadata/node_modules/gaxios/build/src/common.js b/node_modules/gcp-metadata/node_modules/gaxios/build/src/common.js new file mode 100644 index 0000000..b9c5a57 --- /dev/null +++ b/node_modules/gcp-metadata/node_modules/gaxios/build/src/common.js @@ -0,0 +1,25 @@ +"use strict"; +// Copyright 2018 Google LLC +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +// tslint:disable no-any +class GaxiosError extends Error { + constructor(message, options, response) { + super(message); + this.response = response; + this.config = options; + this.code = response.status.toString(); + } +} +exports.GaxiosError = GaxiosError; +//# sourceMappingURL=common.js.map \ No newline at end of file diff --git a/node_modules/gcp-metadata/node_modules/gaxios/build/src/common.js.map b/node_modules/gcp-metadata/node_modules/gaxios/build/src/common.js.map new file mode 100644 index 0000000..711ef63 --- /dev/null +++ b/node_modules/gcp-metadata/node_modules/gaxios/build/src/common.js.map @@ -0,0 +1 @@ +{"version":3,"file":"common.js","sourceRoot":"","sources":["../../src/common.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,gDAAgD;AAChD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;AAMjC,wBAAwB;AAExB,MAAa,WAAqB,SAAQ,KAAK;IAI7C,YACE,OAAe,EACf,OAAsB,EACtB,QAA2B;QAE3B,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC;QACtB,IAAI,CAAC,IAAI,GAAG,QAAQ,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC;IACzC,CAAC;CACF;AAdD,kCAcC"} \ No newline at end of file diff --git a/node_modules/gcp-metadata/node_modules/gaxios/build/src/gaxios.d.ts b/node_modules/gcp-metadata/node_modules/gaxios/build/src/gaxios.d.ts new file mode 100644 index 0000000..46b112a --- /dev/null +++ b/node_modules/gcp-metadata/node_modules/gaxios/build/src/gaxios.d.ts @@ -0,0 +1,40 @@ +import { GaxiosOptions, GaxiosPromise } from './common'; +export declare class Gaxios { + private agentCache; + /** + * Default HTTP options that will be used for every HTTP request. + */ + defaults: GaxiosOptions; + /** + * The Gaxios class is responsible for making HTTP requests. + * @param defaults The default set of options to be used for this instance. + */ + constructor(defaults?: GaxiosOptions); + /** + * Perform an HTTP request with the given options. + * @param opts Set of HTTP options that will be used for this HTTP request. + */ + request(opts?: GaxiosOptions): GaxiosPromise; + /** + * Internal, retryable version of the `request` method. + * @param opts Set of HTTP options that will be used for this HTTP request. + */ + private _request; + private getResponseData; + /** + * Validates the options, and merges them with defaults. + * @param opts The original options passed from the client. + */ + private validateOpts; + /** + * By default, throw for any non-2xx status code + * @param status status code from the HTTP response + */ + private validateStatus; + /** + * Encode a set of key/value pars into a querystring format (?foo=bar&baz=boo) + * @param params key value pars to encode + */ + private paramsSerializer; + private translateResponse; +} diff --git a/node_modules/gcp-metadata/node_modules/gaxios/build/src/gaxios.js b/node_modules/gcp-metadata/node_modules/gaxios/build/src/gaxios.js new file mode 100644 index 0000000..4029ebd --- /dev/null +++ b/node_modules/gcp-metadata/node_modules/gaxios/build/src/gaxios.js @@ -0,0 +1,224 @@ +"use strict"; +// Copyright 2018 Google LLC +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const extend_1 = __importDefault(require("extend")); +const node_fetch_1 = __importDefault(require("node-fetch")); +const querystring_1 = __importDefault(require("querystring")); +const is_stream_1 = __importDefault(require("is-stream")); +const url_1 = __importDefault(require("url")); +const common_1 = require("./common"); +const retry_1 = require("./retry"); +// tslint:disable no-any +const URL = hasURL() ? window.URL : url_1.default.URL; +const fetch = hasFetch() ? window.fetch : node_fetch_1.default; +function hasWindow() { + return typeof window !== 'undefined' && !!window; +} +function hasURL() { + return hasWindow() && !!window.URL; +} +function hasFetch() { + return hasWindow() && !!window.fetch; +} +// tslint:disable-next-line variable-name +let HttpsProxyAgent; +// Figure out if we should be using a proxy. Only if it's required, load +// the https-proxy-agent module as it adds startup cost. +function loadProxy() { + const proxy = process.env.HTTPS_PROXY || + process.env.https_proxy || + process.env.HTTP_PROXY || + process.env.http_proxy; + if (proxy) { + HttpsProxyAgent = require('https-proxy-agent'); + } + return proxy; +} +loadProxy(); +class Gaxios { + /** + * The Gaxios class is responsible for making HTTP requests. + * @param defaults The default set of options to be used for this instance. + */ + constructor(defaults) { + this.agentCache = new Map(); + this.defaults = defaults || {}; + } + /** + * Perform an HTTP request with the given options. + * @param opts Set of HTTP options that will be used for this HTTP request. + */ + async request(opts = {}) { + opts = this.validateOpts(opts); + return this._request(opts); + } + /** + * Internal, retryable version of the `request` method. + * @param opts Set of HTTP options that will be used for this HTTP request. + */ + async _request(opts = {}) { + try { + let translatedResponse; + if (opts.adapter) { + translatedResponse = await opts.adapter(opts); + } + else { + const res = await fetch(opts.url, opts); + const data = await this.getResponseData(opts, res); + translatedResponse = this.translateResponse(opts, res, data); + } + if (!opts.validateStatus(translatedResponse.status)) { + throw new common_1.GaxiosError(`Request failed with status code ${translatedResponse.status}`, opts, translatedResponse); + } + return translatedResponse; + } + catch (e) { + const err = e; + err.config = opts; + const { shouldRetry, config } = await retry_1.getRetryConfig(e); + if (shouldRetry && config) { + err.config.retryConfig.currentRetryAttempt = config.retryConfig.currentRetryAttempt; + return this._request(err.config); + } + throw err; + } + } + async getResponseData(opts, res) { + switch (opts.responseType) { + case 'stream': + return res.body; + case 'json': + let data = await res.text(); + try { + data = JSON.parse(data); + } + catch (e) { } + return data; + case 'arraybuffer': + return res.arrayBuffer(); + case 'blob': + return res.blob(); + default: + return res.text(); + } + } + /** + * Validates the options, and merges them with defaults. + * @param opts The original options passed from the client. + */ + validateOpts(options) { + const opts = extend_1.default(true, {}, this.defaults, options); + if (!opts.url) { + throw new Error('URL is required.'); + } + // baseUrl has been deprecated, remove in 2.0 + const baseUrl = opts.baseUrl || opts.baseURL; + if (baseUrl) { + opts.url = baseUrl + opts.url; + } + const parsedUrl = new URL(opts.url); + opts.url = `${parsedUrl.origin}${parsedUrl.pathname}`; + opts.params = extend_1.default(querystring_1.default.parse(parsedUrl.search.substr(1)), // removes leading ? + opts.params); + opts.paramsSerializer = opts.paramsSerializer || this.paramsSerializer; + if (opts.params) { + parsedUrl.search = opts.paramsSerializer(opts.params); + } + opts.url = parsedUrl.href; + if (typeof options.maxContentLength === 'number') { + opts.size = options.maxContentLength; + } + if (typeof options.maxRedirects === 'number') { + opts.follow = options.maxRedirects; + } + opts.headers = opts.headers || {}; + if (opts.data) { + if (is_stream_1.default.readable(opts.data)) { + opts.body = opts.data; + } + else if (typeof opts.data === 'object') { + opts.body = JSON.stringify(opts.data); + // Allow the user to specifiy their own content type, + // such as application/json-patch+json; for historical reasons this + // content type must currently be a json type, as we are relying on + // application/x-www-form-urlencoded (which is incompatible with + // upstream GCP APIs) being rewritten to application/json. + // + // TODO: refactor upstream dependencies to stop relying on this + // side-effect. + if (!opts.headers['Content-Type'] || + !opts.headers['Content-Type'].includes('json')) { + opts.headers['Content-Type'] = 'application/json'; + } + } + else { + opts.body = opts.data; + } + } + opts.validateStatus = opts.validateStatus || this.validateStatus; + opts.responseType = opts.responseType || 'json'; + if (!opts.headers['Accept'] && opts.responseType === 'json') { + opts.headers['Accept'] = 'application/json'; + } + opts.method = opts.method || 'GET'; + const proxy = loadProxy(); + if (proxy) { + if (this.agentCache.has(proxy)) { + opts.agent = this.agentCache.get(proxy); + } + else { + opts.agent = new HttpsProxyAgent(proxy); + this.agentCache.set(proxy, opts.agent); + } + } + return opts; + } + /** + * By default, throw for any non-2xx status code + * @param status status code from the HTTP response + */ + validateStatus(status) { + return status >= 200 && status < 300; + } + /** + * Encode a set of key/value pars into a querystring format (?foo=bar&baz=boo) + * @param params key value pars to encode + */ + paramsSerializer(params) { + return querystring_1.default.stringify(params); + } + translateResponse(opts, res, data) { + // headers need to be converted from a map to an obj + const headers = {}; + res.headers.forEach((value, key) => { + headers[key] = value; + }); + return { + config: opts, + data: data, + headers, + status: res.status, + statusText: res.statusText, + // XMLHttpRequestLike + request: { + responseURL: res.url, + }, + }; + } +} +exports.Gaxios = Gaxios; +//# sourceMappingURL=gaxios.js.map \ No newline at end of file diff --git a/node_modules/gcp-metadata/node_modules/gaxios/build/src/gaxios.js.map b/node_modules/gcp-metadata/node_modules/gaxios/build/src/gaxios.js.map new file mode 100644 index 0000000..9bd574f --- /dev/null +++ b/node_modules/gcp-metadata/node_modules/gaxios/build/src/gaxios.js.map @@ -0,0 +1 @@ +{"version":3,"file":"gaxios.js","sourceRoot":"","sources":["../../src/gaxios.ts"],"names":[],"mappings":"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"} \ No newline at end of file diff --git a/node_modules/gcp-metadata/node_modules/gaxios/build/src/index.d.ts b/node_modules/gcp-metadata/node_modules/gaxios/build/src/index.d.ts new file mode 100644 index 0000000..033aff5 --- /dev/null +++ b/node_modules/gcp-metadata/node_modules/gaxios/build/src/index.d.ts @@ -0,0 +1,14 @@ +import { GaxiosOptions } from './common'; +import { Gaxios } from './gaxios'; +export { GaxiosError, GaxiosPromise, GaxiosResponse, Headers, RetryConfig, } from './common'; +export { Gaxios, GaxiosOptions }; +/** + * The default instance used when the `request` method is directly + * invoked. + */ +export declare const instance: Gaxios; +/** + * Make an HTTP request using the given options. + * @param opts Options for the request + */ +export declare function request(opts: GaxiosOptions): Promise>; diff --git a/node_modules/gcp-metadata/node_modules/gaxios/build/src/index.js b/node_modules/gcp-metadata/node_modules/gaxios/build/src/index.js new file mode 100644 index 0000000..71c3ece --- /dev/null +++ b/node_modules/gcp-metadata/node_modules/gaxios/build/src/index.js @@ -0,0 +1,32 @@ +"use strict"; +// Copyright 2018 Google LLC +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +const gaxios_1 = require("./gaxios"); +exports.Gaxios = gaxios_1.Gaxios; +var common_1 = require("./common"); +exports.GaxiosError = common_1.GaxiosError; +/** + * The default instance used when the `request` method is directly + * invoked. + */ +exports.instance = new gaxios_1.Gaxios(); +/** + * Make an HTTP request using the given options. + * @param opts Options for the request + */ +async function request(opts) { + return exports.instance.request(opts); +} +exports.request = request; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/gcp-metadata/node_modules/gaxios/build/src/index.js.map b/node_modules/gcp-metadata/node_modules/gaxios/build/src/index.js.map new file mode 100644 index 0000000..af85752 --- /dev/null +++ b/node_modules/gcp-metadata/node_modules/gaxios/build/src/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,gDAAgD;AAChD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;AAGjC,qCAAgC;AASxB,iBATA,eAAM,CASA;AAPd,mCAMkB;AALhB,+BAAA,WAAW,CAAA;AAQb;;;GAGG;AACU,QAAA,QAAQ,GAAG,IAAI,eAAM,EAAE,CAAC;AAErC;;;GAGG;AACI,KAAK,UAAU,OAAO,CAAI,IAAmB;IAClD,OAAO,gBAAQ,CAAC,OAAO,CAAI,IAAI,CAAC,CAAC;AACnC,CAAC;AAFD,0BAEC"} \ No newline at end of file diff --git a/node_modules/gcp-metadata/node_modules/gaxios/build/src/retry.d.ts b/node_modules/gcp-metadata/node_modules/gaxios/build/src/retry.d.ts new file mode 100644 index 0000000..cfc5ee2 --- /dev/null +++ b/node_modules/gcp-metadata/node_modules/gaxios/build/src/retry.d.ts @@ -0,0 +1,8 @@ +import { GaxiosError } from './common'; +export declare function getRetryConfig(err: GaxiosError): Promise<{ + shouldRetry: boolean; + config?: undefined; +} | { + shouldRetry: boolean; + config: import("./common").GaxiosOptions; +}>; diff --git a/node_modules/gcp-metadata/node_modules/gaxios/build/src/retry.js b/node_modules/gcp-metadata/node_modules/gaxios/build/src/retry.js new file mode 100644 index 0000000..b25b9ad --- /dev/null +++ b/node_modules/gcp-metadata/node_modules/gaxios/build/src/retry.js @@ -0,0 +1,132 @@ +"use strict"; +// Copyright 2018 Google LLC +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +async function getRetryConfig(err) { + let config = getConfig(err); + if (!err || !err.config || (!config && !err.config.retry)) { + return { shouldRetry: false }; + } + config = config || {}; + config.currentRetryAttempt = config.currentRetryAttempt || 0; + config.retry = + config.retry === undefined || config.retry === null ? 3 : config.retry; + config.httpMethodsToRetry = config.httpMethodsToRetry || [ + 'GET', + 'HEAD', + 'PUT', + 'OPTIONS', + 'DELETE', + ]; + config.noResponseRetries = + config.noResponseRetries === undefined || config.noResponseRetries === null + ? 2 + : config.noResponseRetries; + // If this wasn't in the list of status codes where we want + // to automatically retry, return. + const retryRanges = [ + // https://en.wikipedia.org/wiki/List_of_HTTP_status_codes + // 1xx - Retry (Informational, request still processing) + // 2xx - Do not retry (Success) + // 3xx - Do not retry (Redirect) + // 4xx - Do not retry (Client errors) + // 429 - Retry ("Too Many Requests") + // 5xx - Retry (Server errors) + [100, 199], + [429, 429], + [500, 599], + ]; + config.statusCodesToRetry = config.statusCodesToRetry || retryRanges; + // Put the config back into the err + err.config.retryConfig = config; + // Determine if we should retry the request + const shouldRetryFn = config.shouldRetry || shouldRetryRequest; + if (!(await shouldRetryFn(err))) { + return { shouldRetry: false, config: err.config }; + } + // Calculate time to wait with exponential backoff. + // Formula: (2^c - 1 / 2) * 1000 + const delay = ((Math.pow(2, config.currentRetryAttempt) - 1) / 2) * 1000; + // We're going to retry! Incremenent the counter. + err.config.retryConfig.currentRetryAttempt += 1; + // Create a promise that invokes the retry after the backOffDelay + const backoff = new Promise(resolve => { + setTimeout(resolve, delay); + }); + // Notify the user if they added an `onRetryAttempt` handler + if (config.onRetryAttempt) { + config.onRetryAttempt(err); + } + // Return the promise in which recalls Gaxios to retry the request + await backoff; + return { shouldRetry: true, config: err.config }; +} +exports.getRetryConfig = getRetryConfig; +/** + * Determine based on config if we should retry the request. + * @param err The GaxiosError passed to the interceptor. + */ +function shouldRetryRequest(err) { + const config = getConfig(err); + // node-fetch raises an AbortError if signaled: + // https://github.com/bitinn/node-fetch#request-cancellation-with-abortsignal + if (err.name === 'AbortError') { + return false; + } + // If there's no config, or retries are disabled, return. + if (!config || config.retry === 0) { + return false; + } + // Check if this error has no response (ETIMEDOUT, ENOTFOUND, etc) + if (!err.response && + (config.currentRetryAttempt || 0) >= config.noResponseRetries) { + return false; + } + // Only retry with configured HttpMethods. + if (!err.config.method || + config.httpMethodsToRetry.indexOf(err.config.method.toUpperCase()) < 0) { + return false; + } + // If this wasn't in the list of status codes where we want + // to automatically retry, return. + if (err.response && err.response.status) { + let isInRange = false; + for (const [min, max] of config.statusCodesToRetry) { + const status = err.response.status; + if (status >= min && status <= max) { + isInRange = true; + break; + } + } + if (!isInRange) { + return false; + } + } + // If we are out of retry attempts, return + config.currentRetryAttempt = config.currentRetryAttempt || 0; + if (config.currentRetryAttempt >= config.retry) { + return false; + } + return true; +} +/** + * Acquire the raxConfig object from an GaxiosError if available. + * @param err The Gaxios error with a config object. + */ +function getConfig(err) { + if (err && err.config && err.config.retryConfig) { + return err.config.retryConfig; + } + return; +} +//# sourceMappingURL=retry.js.map \ No newline at end of file diff --git a/node_modules/gcp-metadata/node_modules/gaxios/build/src/retry.js.map b/node_modules/gcp-metadata/node_modules/gaxios/build/src/retry.js.map new file mode 100644 index 0000000..e90a53f --- /dev/null +++ b/node_modules/gcp-metadata/node_modules/gaxios/build/src/retry.js.map @@ -0,0 +1 @@ +{"version":3,"file":"retry.js","sourceRoot":"","sources":["../../src/retry.ts"],"names":[],"mappings":"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"} \ No newline at end of file diff --git a/node_modules/gcp-metadata/node_modules/gaxios/build/src/web.d.ts b/node_modules/gcp-metadata/node_modules/gaxios/build/src/web.d.ts new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/gcp-metadata/node_modules/gaxios/build/src/web.js b/node_modules/gcp-metadata/node_modules/gaxios/build/src/web.js new file mode 100644 index 0000000..0517f5d --- /dev/null +++ b/node_modules/gcp-metadata/node_modules/gaxios/build/src/web.js @@ -0,0 +1,2 @@ +"use strict"; +//# sourceMappingURL=web.js.map \ No newline at end of file diff --git a/node_modules/gcp-metadata/node_modules/gaxios/build/src/web.js.map b/node_modules/gcp-metadata/node_modules/gaxios/build/src/web.js.map new file mode 100644 index 0000000..3677aca --- /dev/null +++ b/node_modules/gcp-metadata/node_modules/gaxios/build/src/web.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web.js","sourceRoot":"","sources":["../../src/web.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/gcp-metadata/node_modules/gaxios/package.json b/node_modules/gcp-metadata/node_modules/gaxios/package.json new file mode 100644 index 0000000..709a209 --- /dev/null +++ b/node_modules/gcp-metadata/node_modules/gaxios/package.json @@ -0,0 +1,130 @@ +{ + "_from": "gaxios@^2.1.0", + "_id": "gaxios@2.3.4", + "_inBundle": false, + "_integrity": "sha512-US8UMj8C5pRnao3Zykc4AAVr+cffoNKRTg9Rsf2GiuZCW69vgJj38VK2PzlPuQU73FZ/nTk9/Av6/JGcE1N9vA==", + "_location": "/gcp-metadata/gaxios", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "gaxios@^2.1.0", + "name": "gaxios", + "escapedName": "gaxios", + "rawSpec": "^2.1.0", + "saveSpec": null, + "fetchSpec": "^2.1.0" + }, + "_requiredBy": [ + "/gcp-metadata" + ], + "_resolved": "https://registry.npmjs.org/gaxios/-/gaxios-2.3.4.tgz", + "_shasum": "eea99353f341c270c5f3c29fc46b8ead56f0a173", + "_spec": "gaxios@^2.1.0", + "_where": "/Users/cday/Code/zendesk/fetch-build-from-gcb/node_modules/gcp-metadata", + "author": { + "name": "Google, LLC" + }, + "bugs": { + "url": "https://github.com/googleapis/gaxios/issues" + }, + "bundleDependencies": false, + "dependencies": { + "abort-controller": "^3.0.0", + "extend": "^3.0.2", + "https-proxy-agent": "^5.0.0", + "is-stream": "^2.0.0", + "node-fetch": "^2.3.0" + }, + "deprecated": false, + "description": "A simple common HTTP client specifically for Google APIs and services.", + "devDependencies": { + "@compodoc/compodoc": "^1.1.9", + "@types/execa": "^0.9.0", + "@types/express": "^4.16.1", + "@types/extend": "^3.0.1", + "@types/mocha": "^7.0.0", + "@types/mv": "^2.1.0", + "@types/ncp": "^2.0.1", + "@types/nock": "^10.0.0", + "@types/node": "^11.9.5", + "@types/node-fetch": "^2.1.6", + "@types/sinon": "^7.0.7", + "@types/tmp": "0.1.0", + "assert-rejects": "^1.0.0", + "c8": "^7.0.0", + "codecov": "^3.2.0", + "execa": "^4.0.0", + "express": "^4.16.4", + "gts": "^1.0.0", + "is-docker": "^2.0.0", + "karma": "^4.0.0", + "karma-chrome-launcher": "^3.0.0", + "karma-coverage": "^2.0.0", + "karma-firefox-launcher": "^1.1.0", + "karma-mocha": "^1.3.0", + "karma-remap-coverage": "^0.1.5", + "karma-sourcemap-loader": "^0.3.7", + "karma-webpack": "^4.0.0", + "linkinator": "^2.0.0", + "mocha": "^7.0.0", + "mv": "^2.1.1", + "ncp": "^2.0.0", + "nock": "^12.0.0", + "null-loader": "^3.0.0", + "puppeteer": "^2.0.0", + "sinon": "^9.0.0", + "tmp": "0.1.0", + "ts-loader": "^6.0.0", + "typescript": "3.6.4", + "webpack": "^4.29.5", + "webpack-cli": "^3.2.3" + }, + "engines": { + "node": ">=8.10.0" + }, + "files": [ + "build/src" + ], + "homepage": "https://github.com/googleapis/gaxios#readme", + "keywords": [ + "google" + ], + "license": "Apache-2.0", + "main": "build/src/index.js", + "name": "gaxios", + "repository": { + "type": "git", + "url": "git+https://github.com/googleapis/gaxios.git" + }, + "scripts": { + "browser-test": "node build/browser-test/browser-test-runner.js", + "clean": "gts clean", + "compile": "tsc -p .", + "docs": "compodoc src/", + "docs-test": "linkinator docs", + "fix": "gts fix", + "lint": "gts check", + "prebrowser-test": "npm run compile", + "predocs-test": "npm run docs", + "prelint": "cd samples; npm link ../; npm i", + "prepare": "npm run compile", + "presystem-test": "npm run compile", + "pretest": "npm run compile", + "samples-test": "cd samples/ && npm link ../ && npm test && cd ../", + "system-test": "mocha build/system-test --timeout 40000", + "test": "c8 mocha build/test", + "webpack": "webpack" + }, + "types": "build/src/index.d.ts", + "version": "2.3.4", + "warnings": [ + { + "code": "ENOTSUP", + "required": { + "node": ">=8.10.0" + }, + "pkgid": "gaxios@2.3.4" + } + ] +} diff --git a/node_modules/gcp-metadata/package.json b/node_modules/gcp-metadata/package.json new file mode 100644 index 0000000..47b3cdd --- /dev/null +++ b/node_modules/gcp-metadata/package.json @@ -0,0 +1,120 @@ +{ + "_from": "gcp-metadata@^4.0.0", + "_id": "gcp-metadata@4.0.0", + "_inBundle": false, + "_integrity": "sha512-bu5APZrp6hXa+N8P6unMn8ZDwsSrbFd8lD83l6itbkx/9AoH0nS/1Zbg9DyYEAgNkk12pg2BS7d83ePZ2UCuGw==", + "_location": "/gcp-metadata", + "_phantomChildren": { + "abort-controller": "3.0.0", + "extend": "3.0.2", + "https-proxy-agent": "5.0.0", + "is-stream": "2.0.0", + "node-fetch": "2.6.0" + }, + "_requested": { + "type": "range", + "registry": true, + "raw": "gcp-metadata@^4.0.0", + "name": "gcp-metadata", + "escapedName": "gcp-metadata", + "rawSpec": "^4.0.0", + "saveSpec": null, + "fetchSpec": "^4.0.0" + }, + "_requiredBy": [ + "/google-auth-library" + ], + "_resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-4.0.0.tgz", + "_shasum": "dbb5cd9aff5f877c2447715380c3bafb093170c9", + "_spec": "gcp-metadata@^4.0.0", + "_where": "/Users/cday/Code/zendesk/fetch-build-from-gcb/node_modules/google-auth-library", + "author": { + "name": "Stephen Sawchuk" + }, + "bugs": { + "url": "https://github.com/googleapis/gcp-metadata/issues" + }, + "bundleDependencies": false, + "dependencies": { + "gaxios": "^2.1.0", + "json-bigint": "^0.3.0" + }, + "deprecated": false, + "description": "Get the metadata from a Google Cloud Platform environment", + "devDependencies": { + "@compodoc/compodoc": "^1.1.10", + "@types/mocha": "^7.0.0", + "@types/ncp": "^2.0.1", + "@types/nock": "^10.0.3", + "@types/node": "^12.7.2", + "@types/tmp": "0.1.0", + "@types/uuid": "^7.0.0", + "c8": "^7.0.0", + "codecov": "^3.5.0", + "eslint": "^6.1.0", + "eslint-config-prettier": "^6.0.0", + "eslint-plugin-node": "^11.0.0", + "eslint-plugin-prettier": "^3.1.0", + "gcbuild": "^1.3.4", + "gcx": "^1.0.0", + "googleapis": "^48.0.0", + "gts": "^2.0.0-alpha.4", + "linkinator": "^2.0.0", + "mocha": "^7.0.0", + "ncp": "^2.0.0", + "nock": "^12.0.0", + "prettier": "^1.18.2", + "tmp": "^0.1.0", + "typescript": "^3.8.3", + "uuid": "^7.0.0" + }, + "engines": { + "node": ">=10" + }, + "files": [ + "build/src" + ], + "homepage": "https://github.com/googleapis/gcp-metadata#readme", + "keywords": [ + "google cloud platform", + "google cloud", + "google", + "app engine", + "compute engine", + "metadata server", + "metadata" + ], + "license": "Apache-2.0", + "main": "./build/src/index.js", + "name": "gcp-metadata", + "repository": { + "type": "git", + "url": "git+https://github.com/googleapis/gcp-metadata.git" + }, + "scripts": { + "compile": "tsc -p .", + "docs": "compodoc src/", + "docs-test": "linkinator docs", + "fix": "gts fix", + "lint": "gts check", + "predocs-test": "npm run docs", + "prelint": "cd samples; npm link ../; npm i", + "prepare": "npm run compile", + "presystem-test": "npm run compile", + "pretest": "npm run compile", + "samples-test": "npm link && cd samples/ && npm link ../ && npm test && cd ../", + "system-test": "mocha build/system-test --timeout 600000", + "test": "c8 mocha --timeout=5000 build/test" + }, + "types": "./build/src/index.d.ts", + "version": "4.0.0", + "warnings": [ + { + "code": "ENOTSUP", + "required": { + "node": ">=10" + }, + "pkgid": "gcp-metadata@4.0.0" + } + ] +} diff --git a/node_modules/google-auth-library/CHANGELOG.md b/node_modules/google-auth-library/CHANGELOG.md new file mode 100644 index 0000000..9016673 --- /dev/null +++ b/node_modules/google-auth-library/CHANGELOG.md @@ -0,0 +1,610 @@ +# Changelog + +[npm history][1] + +[1]: https://www.npmjs.com/package/google-auth-library-nodejs?activeTab=versions + +## [6.0.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.10.1...v6.0.0) (2020-03-26) + + +### ⚠ BREAKING CHANGES + +* typescript@3.7.x introduced some breaking changes in +generated code. +* require node 10 in engines field (#926) +* remove deprecated methods (#906) + +### Features + +* require node 10 in engines field ([#926](https://www.github.com/googleapis/google-auth-library-nodejs/issues/926)) ([d89c59a](https://www.github.com/googleapis/google-auth-library-nodejs/commit/d89c59a316e9ca5b8c351128ee3e2d91e9729d5c)) + + +### Bug Fixes + +* do not warn for SDK creds ([#905](https://www.github.com/googleapis/google-auth-library-nodejs/issues/905)) ([9536840](https://www.github.com/googleapis/google-auth-library-nodejs/commit/9536840f88e77f747bbbc2c1b5b4289018fc23c9)) +* use iamcredentials API to sign blobs ([#908](https://www.github.com/googleapis/google-auth-library-nodejs/issues/908)) ([7b8e4c5](https://www.github.com/googleapis/google-auth-library-nodejs/commit/7b8e4c52e31bb3d448c3ff8c05002188900eaa04)) +* **deps:** update dependency gaxios to v3 ([#917](https://www.github.com/googleapis/google-auth-library-nodejs/issues/917)) ([1f4bf61](https://www.github.com/googleapis/google-auth-library-nodejs/commit/1f4bf6128a0dcf22cfe1ec492b2192f513836cb2)) +* **deps:** update dependency gcp-metadata to v4 ([#918](https://www.github.com/googleapis/google-auth-library-nodejs/issues/918)) ([d337131](https://www.github.com/googleapis/google-auth-library-nodejs/commit/d337131d009cc1f8182f7a1f8a9034433ee3fbf7)) +* **types:** add additional fields to TokenInfo ([#907](https://www.github.com/googleapis/google-auth-library-nodejs/issues/907)) ([5b48eb8](https://www.github.com/googleapis/google-auth-library-nodejs/commit/5b48eb86c108c47d317a0eb96b47c0cae86f98cb)) + + +### Build System + +* update to latest gts and TypeScript ([#927](https://www.github.com/googleapis/google-auth-library-nodejs/issues/927)) ([e11e18c](https://www.github.com/googleapis/google-auth-library-nodejs/commit/e11e18cb33eb60a666980d061c54bb8891cdd242)) + + +### Miscellaneous Chores + +* remove deprecated methods ([#906](https://www.github.com/googleapis/google-auth-library-nodejs/issues/906)) ([f453fb7](https://www.github.com/googleapis/google-auth-library-nodejs/commit/f453fb7d8355e6dc74800b18d6f43c4e91d4acc9)) + +### [5.10.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.10.0...v5.10.1) (2020-02-25) + + +### Bug Fixes + +* if GCF environment detected, increase library timeout ([#899](https://www.github.com/googleapis/google-auth-library-nodejs/issues/899)) ([2577ff2](https://www.github.com/googleapis/google-auth-library-nodejs/commit/2577ff28bf22dfc58bd09e7365471c16f359f109)) + +## [5.10.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.9.2...v5.10.0) (2020-02-20) + + +### Features + +* support for verifying ES256 and retrieving IAP public keys ([#887](https://www.github.com/googleapis/google-auth-library-nodejs/issues/887)) ([a98e386](https://www.github.com/googleapis/google-auth-library-nodejs/commit/a98e38678dc4a5e963356378c75c658e36dccd01)) + + +### Bug Fixes + +* **docs:** correct links in README ([f6a3194](https://www.github.com/googleapis/google-auth-library-nodejs/commit/f6a3194ff6df97d4fd833ae69ec80c05eab46e7b)), closes [#891](https://www.github.com/googleapis/google-auth-library-nodejs/issues/891) + +### [5.9.2](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.9.1...v5.9.2) (2020-01-28) + + +### Bug Fixes + +* populate credentials.refresh_token if provided ([#881](https://www.github.com/googleapis/google-auth-library-nodejs/issues/881)) ([63c4637](https://www.github.com/googleapis/google-auth-library-nodejs/commit/63c4637c57e4113a7b01bf78933a8bff0356c104)) + +### [5.9.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.9.0...v5.9.1) (2020-01-16) + + +### Bug Fixes + +* ensures GCE metadata sets email field for ID tokens ([#874](https://www.github.com/googleapis/google-auth-library-nodejs/issues/874)) ([e45b73d](https://www.github.com/googleapis/google-auth-library-nodejs/commit/e45b73dbb22e1c2d8115882006a21337c7d9bd63)) + +## [5.9.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.8.0...v5.9.0) (2020-01-14) + + +### Features + +* add methods for fetching and using id tokens ([#867](https://www.github.com/googleapis/google-auth-library-nodejs/issues/867)) ([8036f1a](https://www.github.com/googleapis/google-auth-library-nodejs/commit/8036f1a51d1a103b08daf62c7ce372c9f68cd9d4)) +* export LoginTicket and TokenPayload ([#870](https://www.github.com/googleapis/google-auth-library-nodejs/issues/870)) ([539ea5e](https://www.github.com/googleapis/google-auth-library-nodejs/commit/539ea5e804386b79ecf469838fff19465aeb2ca6)) + +## [5.8.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.7.0...v5.8.0) (2020-01-06) + + +### Features + +* cache results of getEnv() ([#857](https://www.github.com/googleapis/google-auth-library-nodejs/issues/857)) ([d4545a9](https://www.github.com/googleapis/google-auth-library-nodejs/commit/d4545a9001184fac0b67e7073e463e3efd345037)) + + +### Bug Fixes + +* **deps:** update dependency jws to v4 ([#851](https://www.github.com/googleapis/google-auth-library-nodejs/issues/851)) ([71366d4](https://www.github.com/googleapis/google-auth-library-nodejs/commit/71366d43406047ce9e1d818d59a14191fb678e3a)) + +## [5.7.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.6.1...v5.7.0) (2019-12-10) + + +### Features + +* make x-goog-user-project work for additional auth clients ([#848](https://www.github.com/googleapis/google-auth-library-nodejs/issues/848)) ([46af865](https://www.github.com/googleapis/google-auth-library-nodejs/commit/46af865172103c6f28712d78b30c2291487cbe86)) + +### [5.6.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.6.0...v5.6.1) (2019-12-05) + + +### Bug Fixes + +* **deps:** pin TypeScript below 3.7.0 ([#845](https://www.github.com/googleapis/google-auth-library-nodejs/issues/845)) ([a9c6e92](https://www.github.com/googleapis/google-auth-library-nodejs/commit/a9c6e9284efe8102974c57c9824ed6275d743c7a)) +* **docs:** improve types and docs for generateCodeVerifierAsync ([#840](https://www.github.com/googleapis/google-auth-library-nodejs/issues/840)) ([04dae9c](https://www.github.com/googleapis/google-auth-library-nodejs/commit/04dae9c271f0099025188489c61fd245d482832b)) + +## [5.6.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.5.1...v5.6.0) (2019-12-02) + + +### Features + +* populate x-goog-user-project for requestAsync ([#837](https://www.github.com/googleapis/google-auth-library-nodejs/issues/837)) ([5a068fb](https://www.github.com/googleapis/google-auth-library-nodejs/commit/5a068fb8f5a3827ab70404f1d9699a97f962bdad)) +* set x-goog-user-project header, with quota_project from default credentials ([#829](https://www.github.com/googleapis/google-auth-library-nodejs/issues/829)) ([3240d16](https://www.github.com/googleapis/google-auth-library-nodejs/commit/3240d16f05171781fe6d70d64c476bceb25805a5)) + + +### Bug Fixes + +* **deps:** update dependency puppeteer to v2 ([#821](https://www.github.com/googleapis/google-auth-library-nodejs/issues/821)) ([2c04117](https://www.github.com/googleapis/google-auth-library-nodejs/commit/2c0411708761cc7debdda1af1e593d82cb4aed31)) +* **docs:** add jsdoc-region-tag plugin ([#826](https://www.github.com/googleapis/google-auth-library-nodejs/issues/826)) ([558677f](https://www.github.com/googleapis/google-auth-library-nodejs/commit/558677fd90d3451e9ac4bf6d0b98907e3313f287)) +* expand on x-goog-user-project to handle auth.getClient() ([#831](https://www.github.com/googleapis/google-auth-library-nodejs/issues/831)) ([3646b7f](https://www.github.com/googleapis/google-auth-library-nodejs/commit/3646b7f9deb296aaff602dd2168ce93f014ce840)) +* use quota_project_id field instead of quota_project ([#832](https://www.github.com/googleapis/google-auth-library-nodejs/issues/832)) ([8933966](https://www.github.com/googleapis/google-auth-library-nodejs/commit/8933966659f3b07f5454a2756fa52d92fea147d2)) + +### [5.5.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.5.0...v5.5.1) (2019-10-22) + + +### Bug Fixes + +* **deps:** update gaxios dependency ([#817](https://www.github.com/googleapis/google-auth-library-nodejs/issues/817)) ([6730698](https://www.github.com/googleapis/google-auth-library-nodejs/commit/6730698b876eb52889acfead33bc4af52a8a7ba5)) +* don't append x-goog-api-client multiple times ([#820](https://www.github.com/googleapis/google-auth-library-nodejs/issues/820)) ([a46b271](https://www.github.com/googleapis/google-auth-library-nodejs/commit/a46b271947b635377eacbdfcd22ae363ce9260a1)) + +## [5.5.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.4.1...v5.5.0) (2019-10-14) + + +### Features + +* **refresh:** add forceRefreshOnFailure flag for refreshing token on error ([#790](https://www.github.com/googleapis/google-auth-library-nodejs/issues/790)) ([54cf477](https://www.github.com/googleapis/google-auth-library-nodejs/commit/54cf4770f487fd1db48f2444c86109ca97608ed1)) + +### [5.4.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.4.0...v5.4.1) (2019-10-10) + + +### Bug Fixes + +* **deps:** updats to gcp-metadata with debug option ([#811](https://www.github.com/googleapis/google-auth-library-nodejs/issues/811)) ([744e3e8](https://www.github.com/googleapis/google-auth-library-nodejs/commit/744e3e8fea223eb4fb115ef0a4d36ad88fc6921a)) + +## [5.4.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.3.0...v5.4.0) (2019-10-08) + + +### Features + +* do not deprecate refreshAccessToken ([#804](https://www.github.com/googleapis/google-auth-library-nodejs/issues/804)) ([f05de11](https://www.github.com/googleapis/google-auth-library-nodejs/commit/f05de11)) + +## [5.3.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.2.2...v5.3.0) (2019-09-27) + + +### Features + +* if token expires soon, force refresh ([#794](https://www.github.com/googleapis/google-auth-library-nodejs/issues/794)) ([fecd4f4](https://www.github.com/googleapis/google-auth-library-nodejs/commit/fecd4f4)) + +### [5.2.2](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.2.1...v5.2.2) (2019-09-17) + + +### Bug Fixes + +* **deps:** update to gcp-metadata and address envDetect performance issues ([#787](https://www.github.com/googleapis/google-auth-library-nodejs/issues/787)) ([651b5d4](https://www.github.com/googleapis/google-auth-library-nodejs/commit/651b5d4)) + +### [5.2.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.2.0...v5.2.1) (2019-09-06) + + +### Bug Fixes + +* **deps:** nock@next has types that work with our libraries ([#783](https://www.github.com/googleapis/google-auth-library-nodejs/issues/783)) ([a253709](https://www.github.com/googleapis/google-auth-library-nodejs/commit/a253709)) +* **docs:** fix variable name in README.md ([#782](https://www.github.com/googleapis/google-auth-library-nodejs/issues/782)) ([d8c70b9](https://www.github.com/googleapis/google-auth-library-nodejs/commit/d8c70b9)) + +## [5.2.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.1.2...v5.2.0) (2019-08-09) + + +### Features + +* populate x-goog-api-client header for auth ([#772](https://www.github.com/googleapis/google-auth-library-nodejs/issues/772)) ([526dcf6](https://www.github.com/googleapis/google-auth-library-nodejs/commit/526dcf6)) + +### [5.1.2](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.1.1...v5.1.2) (2019-08-05) + + +### Bug Fixes + +* **deps:** upgrade to gtoken 4.x ([#763](https://www.github.com/googleapis/google-auth-library-nodejs/issues/763)) ([a1fcc25](https://www.github.com/googleapis/google-auth-library-nodejs/commit/a1fcc25)) + +### [5.1.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.1.0...v5.1.1) (2019-07-29) + + +### Bug Fixes + +* **deps:** update dependency google-auth-library to v5 ([#759](https://www.github.com/googleapis/google-auth-library-nodejs/issues/759)) ([e32a12b](https://www.github.com/googleapis/google-auth-library-nodejs/commit/e32a12b)) + +## [5.1.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v5.0.0...v5.1.0) (2019-07-24) + + +### Features + +* **types:** expose ProjectIdCallback interface ([#753](https://www.github.com/googleapis/google-auth-library-nodejs/issues/753)) ([5577f0d](https://www.github.com/googleapis/google-auth-library-nodejs/commit/5577f0d)) + +## [5.0.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v4.2.6...v5.0.0) (2019-07-23) + + +### ⚠ BREAKING CHANGES + +* getOptions() no longer accepts GoogleAuthOptions (#749) + +### Code Refactoring + +* getOptions() no longer accepts GoogleAuthOptions ([#749](https://www.github.com/googleapis/google-auth-library-nodejs/issues/749)) ([ba58e3b](https://www.github.com/googleapis/google-auth-library-nodejs/commit/ba58e3b)) + +### [4.2.6](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v4.2.5...v4.2.6) (2019-07-23) + + +### Bug Fixes + +* use FUNCTION_TARGET to detect GCF 10 and above ([#748](https://www.github.com/googleapis/google-auth-library-nodejs/issues/748)) ([ca17685](https://www.github.com/googleapis/google-auth-library-nodejs/commit/ca17685)) + +### [4.2.5](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v4.2.4...v4.2.5) (2019-06-26) + + +### Bug Fixes + +* **docs:** make anchors work in jsdoc ([#742](https://www.github.com/googleapis/google-auth-library-nodejs/issues/742)) ([7901456](https://www.github.com/googleapis/google-auth-library-nodejs/commit/7901456)) + +### [4.2.4](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v4.2.3...v4.2.4) (2019-06-25) + + +### Bug Fixes + +* only require fast-text-encoding when needed ([#740](https://www.github.com/googleapis/google-auth-library-nodejs/issues/740)) ([04fcd77](https://www.github.com/googleapis/google-auth-library-nodejs/commit/04fcd77)) + +### [4.2.3](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v4.2.2...v4.2.3) (2019-06-24) + + +### Bug Fixes + +* feature detection to check for browser ([#738](https://www.github.com/googleapis/google-auth-library-nodejs/issues/738)) ([83a5ba5](https://www.github.com/googleapis/google-auth-library-nodejs/commit/83a5ba5)) + +### [4.2.2](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v4.2.1...v4.2.2) (2019-06-18) + + +### Bug Fixes + +* **compute:** correctly specify scopes when fetching token ([#735](https://www.github.com/googleapis/google-auth-library-nodejs/issues/735)) ([4803e3c](https://www.github.com/googleapis/google-auth-library-nodejs/commit/4803e3c)) + +### [4.2.1](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v4.2.0...v4.2.1) (2019-06-14) + + +### Bug Fixes + +* **docs:** move to new client docs URL ([#733](https://www.github.com/googleapis/google-auth-library-nodejs/issues/733)) ([cfbbe2a](https://www.github.com/googleapis/google-auth-library-nodejs/commit/cfbbe2a)) + +## [4.2.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v4.1.0...v4.2.0) (2019-06-05) + + +### Bug Fixes + +* pad base64 strings for base64js ([#722](https://www.github.com/googleapis/google-auth-library-nodejs/issues/722)) ([81e0a23](https://www.github.com/googleapis/google-auth-library-nodejs/commit/81e0a23)) + + +### Features + +* make both crypto implementations support sign ([#727](https://www.github.com/googleapis/google-auth-library-nodejs/issues/727)) ([e445fb3](https://www.github.com/googleapis/google-auth-library-nodejs/commit/e445fb3)) + +## [4.1.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v4.0.0...v4.1.0) (2019-05-29) + + +### Bug Fixes + +* **deps:** update dependency google-auth-library to v4 ([#705](https://www.github.com/googleapis/google-auth-library-nodejs/issues/705)) ([2b13344](https://www.github.com/googleapis/google-auth-library-nodejs/commit/2b13344)) + + +### Features + +* use X-Goog-Api-Key header ([#719](https://www.github.com/googleapis/google-auth-library-nodejs/issues/719)) ([35471d0](https://www.github.com/googleapis/google-auth-library-nodejs/commit/35471d0)) + +## [4.0.0](https://www.github.com/googleapis/google-auth-library-nodejs/compare/v3.1.2...v4.0.0) (2019-05-08) + + +### Bug Fixes + +* **deps:** update dependency arrify to v2 ([#684](https://www.github.com/googleapis/google-auth-library-nodejs/issues/684)) ([1757ee2](https://www.github.com/googleapis/google-auth-library-nodejs/commit/1757ee2)) +* **deps:** update dependency gaxios to v2 ([#681](https://www.github.com/googleapis/google-auth-library-nodejs/issues/681)) ([770ad2f](https://www.github.com/googleapis/google-auth-library-nodejs/commit/770ad2f)) +* **deps:** update dependency gcp-metadata to v2 ([#701](https://www.github.com/googleapis/google-auth-library-nodejs/issues/701)) ([be20528](https://www.github.com/googleapis/google-auth-library-nodejs/commit/be20528)) +* **deps:** update dependency gtoken to v3 ([#702](https://www.github.com/googleapis/google-auth-library-nodejs/issues/702)) ([2c538e5](https://www.github.com/googleapis/google-auth-library-nodejs/commit/2c538e5)) +* re-throw original exception and preserve message in compute client ([#668](https://www.github.com/googleapis/google-auth-library-nodejs/issues/668)) ([dffd1cc](https://www.github.com/googleapis/google-auth-library-nodejs/commit/dffd1cc)) +* surface original stack trace and message with errors ([#651](https://www.github.com/googleapis/google-auth-library-nodejs/issues/651)) ([8fb65eb](https://www.github.com/googleapis/google-auth-library-nodejs/commit/8fb65eb)) +* throw on missing refresh token in all cases ([#670](https://www.github.com/googleapis/google-auth-library-nodejs/issues/670)) ([0a02946](https://www.github.com/googleapis/google-auth-library-nodejs/commit/0a02946)) +* throw when adc cannot acquire a projectId ([#658](https://www.github.com/googleapis/google-auth-library-nodejs/issues/658)) ([ba48164](https://www.github.com/googleapis/google-auth-library-nodejs/commit/ba48164)) +* **deps:** update dependency semver to v6 ([#655](https://www.github.com/googleapis/google-auth-library-nodejs/issues/655)) ([ec56c88](https://www.github.com/googleapis/google-auth-library-nodejs/commit/ec56c88)) + + +### Build System + +* upgrade engines field to >=8.10.0 ([#686](https://www.github.com/googleapis/google-auth-library-nodejs/issues/686)) ([377d5c6](https://www.github.com/googleapis/google-auth-library-nodejs/commit/377d5c6)) + + +### Features + +* support scopes on compute credentials ([#642](https://www.github.com/googleapis/google-auth-library-nodejs/issues/642)) ([1811b7f](https://www.github.com/googleapis/google-auth-library-nodejs/commit/1811b7f)) + + +### BREAKING CHANGES + +* upgrade engines field to >=8.10.0 (#686) + +## v3.1.2 + +03-22-2019 15:38 PDT + +### Implementation Changes +- fix: getCredential(): load credentials with getClient() ([#648](https://github.com/google/google-auth-library-nodejs/pull/648)) + +### Internal / Testing Changes +- chore: publish to npm using wombat ([#645](https://github.com/google/google-auth-library-nodejs/pull/645)) + +## v3.1.1 + +03-18-2019 08:32 PDT + +### Bug Fixes +- fix: Avoid loading fast-text-encoding if not in browser environment ([#627](https://github.com/google/google-auth-library-nodejs/pull/627)) + +### Dependencies +- fix(deps): update dependency gcp-metadata to v1 ([#632](https://github.com/google/google-auth-library-nodejs/pull/632)) + +### Documentation +- docs: update links in contrib guide ([#630](https://github.com/google/google-auth-library-nodejs/pull/630)) + +### Internal / Testing Changes +- build: use per-repo publish token ([#641](https://github.com/google/google-auth-library-nodejs/pull/641)) +- build: Add docuploader credentials to node publish jobs ([#639](https://github.com/google/google-auth-library-nodejs/pull/639)) +- build: use node10 to run samples-test, system-test etc ([#638](https://github.com/google/google-auth-library-nodejs/pull/638)) +- build: update release configuration +- chore(deps): update dependency @types/lru-cache to v5 ([#635](https://github.com/google/google-auth-library-nodejs/pull/635)) +- chore(deps): update dependency mocha to v6 +- chore: fix lint ([#631](https://github.com/google/google-auth-library-nodejs/pull/631)) +- build: use linkinator for docs test ([#628](https://github.com/google/google-auth-library-nodejs/pull/628)) +- chore(deps): update dependency @types/tmp to ^0.0.34 ([#629](https://github.com/google/google-auth-library-nodejs/pull/629)) +- build: create docs test npm scripts ([#625](https://github.com/google/google-auth-library-nodejs/pull/625)) +- build: test using @grpc/grpc-js in CI ([#624](https://github.com/google/google-auth-library-nodejs/pull/624)) + +## v3.1.0 + +02-08-2019 08:29 PST + +### Bug fixes +- fix: use key file when fetching project id ([#618](https://github.com/googleapis/google-auth-library-nodejs/pull/618)) +- fix: Throw error if there is no refresh token despite the necessity of refreshing ([#605](https://github.com/googleapis/google-auth-library-nodejs/pull/605)) + +### New Features +- feat: allow passing constructor options to getClient ([#611](https://github.com/googleapis/google-auth-library-nodejs/pull/611)) + +### Documentation +- docs: update contributing path in README ([#621](https://github.com/googleapis/google-auth-library-nodejs/pull/621)) +- chore: move CONTRIBUTING.md to root ([#619](https://github.com/googleapis/google-auth-library-nodejs/pull/619)) +- docs: add lint/fix example to contributing guide ([#615](https://github.com/googleapis/google-auth-library-nodejs/pull/615)) +- docs: use the People API for samples ([#609](https://github.com/googleapis/google-auth-library-nodejs/pull/609)) + +### Internal / Testing Changes +- chore(deps): update dependency typescript to ~3.3.0 ([#612](https://github.com/googleapis/google-auth-library-nodejs/pull/612)) +- chore(deps): update dependency eslint-config-prettier to v4 ([#604](https://github.com/googleapis/google-auth-library-nodejs/pull/604)) +- build: ignore googleapis.com in doc link check ([#602](https://github.com/googleapis/google-auth-library-nodejs/pull/602)) +- chore(deps): update dependency karma to v4 ([#603](https://github.com/googleapis/google-auth-library-nodejs/pull/603)) + +## v3.0.1 + +01-16-2019 21:04 PST + +### Bug Fixes +- fix(deps): upgrade to the latest gaxios ([#596](https://github.com/googleapis/google-auth-library-nodejs/pull/596)) + +## v3.0.0 + +01-16-2019 10:00 PST + +Welcome to 3.0 🎉 This release has it all. New features, bug fixes, breaking changes, performance improvements - something for everyone! The biggest addition to this release is support for the browser via Webpack. + +**This release has breaking changes.** This release has a few breaking changes. These changes are unlikely to affect most clients. + +#### BREAKING: Migration from `axios` to `gaxios` +The 2.0 version of this library used the [axios](https://github.com/axios/axios) library for making HTTP requests. In the 3.0 release, this has been replaced by a *mostly* API compatible library [gaxios](https://github.com/JustinBeckwith/gaxios). The new request library natively supports proxies, and comes with a smaller dependency chain. While this is mostly an implementation detail, the `request` method was directly exposed via the `GoogleAuth.request` and `OAuth2Client.request` methods. The gaxios library aims to provide an API compatible implementation of axios, but that can never be 100% promised. If you run into bugs or differences that cause issues - please do let us know. + +#### BREAKING: `generateCodeVerifier` is now `generateCodeVerifierAsync` +The `OAuth2Client.generateCodeVerifier` method has been replaced by the `OAuth2Client.generateCodeVerifierAsync` method. It has changed from a synchronous method to an asynchronous method to support async browser crypto APIs required for Webpack support. + +#### BREAKING: `verifySignedJwtWithCerts` is now `verifySignedJwtWithCertsAsync` +The `OAuth2Client.verifySignedJwtWithCerts` method has been replaced by the `OAuth2Client.verifySignedJwtWithCertsAsync` method. It has changed from a synchronous method to an asynchronous method to support async browser crypto APIs required for Webpack support. + + +### New Features +- feat: make it webpackable ([#371](https://github.com/google/google-auth-library-nodejs/pull/371)) + +### Bug Fixes +- fix: accept lowercase env vars ([#578](https://github.com/google/google-auth-library-nodejs/pull/578)) + +### Dependencies +- chore(deps): update gtoken ([#592](https://github.com/google/google-auth-library-nodejs/pull/592)) +- fix(deps): upgrade to gcp-metadata v0.9.3 ([#586](https://github.com/google/google-auth-library-nodejs/pull/586)) + +### Documentation +- docs: update bug report link ([#585](https://github.com/google/google-auth-library-nodejs/pull/585)) +- docs: clarify access and refresh token docs ([#577](https://github.com/google/google-auth-library-nodejs/pull/577)) + +### Internal / Testing Changes +- refactor(deps): use `gaxios` for HTTP requests instead of `axios` ([#593](https://github.com/google/google-auth-library-nodejs/pull/593)) +- fix: some browser fixes ([#590](https://github.com/google/google-auth-library-nodejs/pull/590)) +- chore(deps): update dependency ts-loader to v5 ([#588](https://github.com/google/google-auth-library-nodejs/pull/588)) +- chore(deps): update dependency karma to v3 ([#587](https://github.com/google/google-auth-library-nodejs/pull/587)) +- build: check broken links in generated docs ([#579](https://github.com/google/google-auth-library-nodejs/pull/579)) +- chore(deps): drop unused dep on typedoc ([#583](https://github.com/google/google-auth-library-nodejs/pull/583)) +- build: add browser test running on Kokoro ([#584](https://github.com/google/google-auth-library-nodejs/pull/584)) +- test: improve samples and add tests ([#576](https://github.com/google/google-auth-library-nodejs/pull/576)) + +## v2.0.2 + +12-16-2018 10:48 PST + +### Fixes +- fix(types): export GCPEnv type ([#569](https://github.com/google/google-auth-library-nodejs/pull/569)) +- fix: use post for token revocation ([#524](https://github.com/google/google-auth-library-nodejs/pull/524)) + +### Dependencies +- fix(deps): update dependency lru-cache to v5 ([#541](https://github.com/google/google-auth-library-nodejs/pull/541)) + +### Documentation +- docs: add ref docs again ([#553](https://github.com/google/google-auth-library-nodejs/pull/553)) +- docs: clean up the readme ([#554](https://github.com/google/google-auth-library-nodejs/pull/554)) + +### Internal / Testing Changes +- chore(deps): update dependency @types/sinon to v7 ([#568](https://github.com/google/google-auth-library-nodejs/pull/568)) +- refactor: use execa for install tests, run eslint on samples ([#559](https://github.com/google/google-auth-library-nodejs/pull/559)) +- chore(build): inject yoshi automation key ([#566](https://github.com/google/google-auth-library-nodejs/pull/566)) +- chore: update nyc and eslint configs ([#565](https://github.com/google/google-auth-library-nodejs/pull/565)) +- chore: fix publish.sh permission +x ([#563](https://github.com/google/google-auth-library-nodejs/pull/563)) +- fix(build): fix Kokoro release script ([#562](https://github.com/google/google-auth-library-nodejs/pull/562)) +- build: add Kokoro configs for autorelease ([#561](https://github.com/google/google-auth-library-nodejs/pull/561)) +- chore: always nyc report before calling codecov ([#557](https://github.com/google/google-auth-library-nodejs/pull/557)) +- chore: nyc ignore build/test by default ([#556](https://github.com/google/google-auth-library-nodejs/pull/556)) +- chore(build): update the prettier and renovate config ([#552](https://github.com/google/google-auth-library-nodejs/pull/552)) +- chore: update license file ([#551](https://github.com/google/google-auth-library-nodejs/pull/551)) +- fix(build): fix system key decryption ([#547](https://github.com/google/google-auth-library-nodejs/pull/547)) +- chore(deps): update dependency typescript to ~3.2.0 ([#546](https://github.com/google/google-auth-library-nodejs/pull/546)) +- chore(deps): unpin sinon ([#544](https://github.com/google/google-auth-library-nodejs/pull/544)) +- refactor: drop non-required modules ([#542](https://github.com/google/google-auth-library-nodejs/pull/542)) +- chore: add synth.metadata ([#537](https://github.com/google/google-auth-library-nodejs/pull/537)) +- fix: Pin @types/sinon to last compatible version ([#538](https://github.com/google/google-auth-library-nodejs/pull/538)) +- chore(deps): update dependency gts to ^0.9.0 ([#531](https://github.com/google/google-auth-library-nodejs/pull/531)) +- chore: update eslintignore config ([#530](https://github.com/google/google-auth-library-nodejs/pull/530)) +- chore: drop contributors from multiple places ([#528](https://github.com/google/google-auth-library-nodejs/pull/528)) +- chore: use latest npm on Windows ([#527](https://github.com/google/google-auth-library-nodejs/pull/527)) +- chore: update CircleCI config ([#523](https://github.com/google/google-auth-library-nodejs/pull/523)) +- chore: include build in eslintignore ([#516](https://github.com/google/google-auth-library-nodejs/pull/516)) + +## v2.0.1 + +### Implementation Changes +- fix: verifyIdToken will never return null ([#488](https://github.com/google/google-auth-library-nodejs/pull/488)) +- Update the url to application default credentials ([#470](https://github.com/google/google-auth-library-nodejs/pull/470)) +- Update omitted parameter 'hd' ([#467](https://github.com/google/google-auth-library-nodejs/pull/467)) + +### Dependencies +- chore(deps): update dependency nock to v10 ([#501](https://github.com/google/google-auth-library-nodejs/pull/501)) +- chore(deps): update dependency sinon to v7 ([#502](https://github.com/google/google-auth-library-nodejs/pull/502)) +- chore(deps): update dependency typescript to v3.1.3 ([#503](https://github.com/google/google-auth-library-nodejs/pull/503)) +- chore(deps): update dependency gh-pages to v2 ([#499](https://github.com/google/google-auth-library-nodejs/pull/499)) +- chore(deps): update dependency typedoc to ^0.13.0 ([#497](https://github.com/google/google-auth-library-nodejs/pull/497)) + +### Documentation +- docs: Remove code format from Application Default Credentials ([#483](https://github.com/google/google-auth-library-nodejs/pull/483)) +- docs: replace google/ with googleapis/ in URIs ([#472](https://github.com/google/google-auth-library-nodejs/pull/472)) +- Fix typo in readme ([#469](https://github.com/google/google-auth-library-nodejs/pull/469)) +- Update samples and docs for 2.0 ([#459](https://github.com/google/google-auth-library-nodejs/pull/459)) + +### Internal / Testing Changes +- chore: update issue templates ([#509](https://github.com/google/google-auth-library-nodejs/pull/509)) +- chore: remove old issue template ([#507](https://github.com/google/google-auth-library-nodejs/pull/507)) +- build: run tests on node11 ([#506](https://github.com/google/google-auth-library-nodejs/pull/506)) +- chore(build): drop hard rejection and update gts in the kitchen test ([#504](https://github.com/google/google-auth-library-nodejs/pull/504)) +- chores(build): do not collect sponge.xml from windows builds ([#500](https://github.com/google/google-auth-library-nodejs/pull/500)) +- chores(build): run codecov on continuous builds ([#495](https://github.com/google/google-auth-library-nodejs/pull/495)) +- chore: update new issue template ([#494](https://github.com/google/google-auth-library-nodejs/pull/494)) +- build: fix codecov uploading on Kokoro ([#490](https://github.com/google/google-auth-library-nodejs/pull/490)) +- test: move kitchen sink tests to system-test ([#489](https://github.com/google/google-auth-library-nodejs/pull/489)) +- Update kokoro config ([#482](https://github.com/google/google-auth-library-nodejs/pull/482)) +- fix: export additional typescript types ([#479](https://github.com/google/google-auth-library-nodejs/pull/479)) +- Don't publish sourcemaps ([#478](https://github.com/google/google-auth-library-nodejs/pull/478)) +- test: remove appveyor config ([#477](https://github.com/google/google-auth-library-nodejs/pull/477)) +- Enable prefer-const in the eslint config ([#473](https://github.com/google/google-auth-library-nodejs/pull/473)) +- Enable no-var in eslint ([#471](https://github.com/google/google-auth-library-nodejs/pull/471)) +- Update CI config ([#468](https://github.com/google/google-auth-library-nodejs/pull/468)) +- Retry npm install in CI ([#465](https://github.com/google/google-auth-library-nodejs/pull/465)) +- Update Kokoro config ([#462](https://github.com/google/google-auth-library-nodejs/pull/462)) + +## v2.0.0 + +Well hello 2.0 🎉 **This release has multiple breaking changes**. It also has a lot of bug fixes. + +### Breaking Changes + +#### Support for node.js 4.x and 9.x has been dropped +These versions of node.js are no longer supported. + +#### The `getRequestMetadata` method has been deprecated +The `getRequestMetadata` method has been deprecated on the `IAM`, `OAuth2`, `JWT`, and `JWTAccess` classes. The `getRequestHeaders` method should be used instead. The methods have a subtle difference: the `getRequestMetadata` method returns an object with a headers property, which contains the authorization header. The `getRequestHeaders` method simply returns the headers. + +##### Old code +```js +const client = await auth.getClient(); +const res = await client.getRequestMetadata(); +const headers = res.headers; +``` + +##### New code +```js +const client = await auth.getClient(); +const headers = await client.getRequestHeaders(); +``` + +#### The `createScopedRequired` method has been deprecated +The `createScopedRequired` method has been deprecated on multiple classes. The `createScopedRequired` and `createScoped` methods on the `JWT` class were largely in place to help inform clients when scopes were required in an application default credential scenario. Instead of checking if scopes are required after creating the client, instead scopes should just be passed either into the `GoogleAuth.getClient` method, or directly into the `JWT` constructor. + +##### Old code +```js +auth.getApplicationDefault(function(err, authClient) { + if (err) { + return callback(err); + } + if (authClient.createScopedRequired && authClient.createScopedRequired()) { + authClient = authClient.createScoped([ + 'https://www.googleapis.com/auth/cloud-platform' + ]); + } + callback(null, authClient); +}); +``` + +##### New code +```js +const client = await auth.getClient({ + scopes: ['https://www.googleapis.com/auth/cloud-platform'] +}); +``` + +#### Deprecate `refreshAccessToken` + +_Note: `refreshAccessToken` is no longer deprecated._ + +`getAccessToken`, `getRequestMetadata`, and `request` methods will all refresh the token if needed automatically. + +You should not need to invoke `refreshAccessToken` directly except in [certain edge-cases](https://github.com/googleapis/google-auth-library-nodejs/issues/575). + +### Features +- Set private_key_id in JWT access token header like other google auth libraries. (#450) + +### Bug Fixes +- fix: support HTTPS proxies (#405) +- fix: export missing interfaces (#437) +- fix: Use new auth URIs (#434) +- docs: Fix broken link (#423) +- fix: surface file read streams (#413) +- fix: prevent unhandled rejections by avoid .catch (#404) +- fix: use gcp-metadata for compute credentials (#409) +- Add Code of Conduct +- fix: Warn when using user credentials from the Cloud SDK (#399) +- fix: use `Buffer.from` instead of `new Buffer` (#400) +- fix: Fix link format in README.md (#385) + +### Breaking changes +- chore: deprecate getRequestMetadata (#414) +- fix: deprecate the `createScopedRequired` methods (#410) +- fix: drop support for node.js 4.x and 9.x (#417) +- fix: deprecate the `refreshAccessToken` methods (#411) +- fix: deprecate the `getDefaultProjectId` method (#402) +- fix: drop support for node.js 4 (#401) + +### Build / Test changes +- Run synth to make build tools consistent (#455) +- Add a package.json for samples and cleanup README (#454) +- chore(deps): update dependency typedoc to ^0.12.0 (#453) +- chore: move examples => samples + synth (#448) +- chore(deps): update dependency nyc to v13 (#452) +- chore(deps): update dependency pify to v4 (#447) +- chore(deps): update dependency assert-rejects to v1 (#446) +- chore: ignore package-lock.json (#445) +- chore: update renovate config (#442) +- chore(deps): lock file maintenance (#443) +- chore: remove greenkeeper badge (#440) +- test: throw on deprecation +- chore: add intelli-espower-loader for running tests (#430) +- chore(deps): update dependency typescript to v3 (#432) +- chore(deps): lock file maintenance (#431) +- test: use strictEqual in tests (#425) +- chore(deps): lock file maintenance (#428) +- chore: Configure Renovate (#424) +- chore: Update gts to the latest version 🚀 (#422) +- chore: update gcp-metadata for isAvailable fix (#420) +- refactor: use assert.reject in the tests (#415) +- refactor: cleanup types for certificates (#412) +- test: run tests with hard-rejection (#397) +- cleanup: straighten nested try-catch (#394) +- test: getDefaultProjectId should prefer config (#388) +- chore(package): Update gts to the latest version 🚀 (#387) +- chore(package): update sinon to version 6.0.0 (#386) + +## Upgrading to 1.x +The `1.x` release includes a variety of bug fixes, new features, and breaking changes. Please take care, and see [the release notes](https://github.com/googleapis/google-auth-library-nodejs/releases/tag/v1.0.0) for a list of breaking changes, and the upgrade guide. diff --git a/node_modules/google-auth-library/LICENSE b/node_modules/google-auth-library/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/node_modules/google-auth-library/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. 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 and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/google-auth-library/README.md b/node_modules/google-auth-library/README.md new file mode 100644 index 0000000..09d8fff --- /dev/null +++ b/node_modules/google-auth-library/README.md @@ -0,0 +1,442 @@ +Google Inc. logo + +# Google Auth Library + +[![npm version][npmimg]][npm] +[![codecov][codecov-image]][codecov-url] +[![Dependencies][david-dm-img]][david-dm] +[![Known Vulnerabilities][snyk-image]][snyk-url] + +This is Google's officially supported [node.js][node] client library for using OAuth 2.0 authorization and authentication with Google APIs. + +## Installation +This library is distributed on `npm`. To add it as a dependency, run the following command: + +``` sh +$ npm install google-auth-library +``` + +## Ways to authenticate +This library provides a variety of ways to authenticate to your Google services. +- [Application Default Credentials](#choosing-the-correct-credential-type-automatically) - Use Application Default Credentials when you use a single identity for all users in your application. Especially useful for applications running on Google Cloud. +- [OAuth 2](#oauth2) - Use OAuth2 when you need to perform actions on behalf of the end user. +- [JSON Web Tokens](#json-web-tokens) - Use JWT when you are using a single identity for all users. Especially useful for server->server or server->API communication. +- [Google Compute](#compute) - Directly use a service account on Google Cloud Platform. Useful for server->server or server->API communication. + +## Application Default Credentials +This library provides an implementation of [Application Default Credentials][] for Node.js. The [Application Default Credentials][] provide a simple way to get authorization credentials for use in calling Google APIs. + +They are best suited for cases when the call needs to have the same identity and authorization level for the application independent of the user. This is the recommended approach to authorize calls to Cloud APIs, particularly when you're building an application that uses Google Cloud Platform. + +#### Download your Service Account Credentials JSON file + +To use Application Default Credentials, You first need to download a set of JSON credentials for your project. Go to **APIs & Auth** > **Credentials** in the [Google Developers Console][devconsole] and select **Service account** from the **Add credentials** dropdown. + +> This file is your *only copy* of these credentials. It should never be +> committed with your source code, and should be stored securely. + +Once downloaded, store the path to this file in the `GOOGLE_APPLICATION_CREDENTIALS` environment variable. + +#### Enable the API you want to use + +Before making your API call, you must be sure the API you're calling has been enabled. Go to **APIs & Auth** > **APIs** in the [Google Developers Console][devconsole] and enable the APIs you'd like to call. For the example below, you must enable the `DNS API`. + + +#### Choosing the correct credential type automatically + +Rather than manually creating an OAuth2 client, JWT client, or Compute client, the auth library can create the correct credential type for you, depending upon the environment your code is running under. + +For example, a JWT auth client will be created when your code is running on your local developer machine, and a Compute client will be created when the same code is running on Google Cloud Platform. If you need a specific set of scopes, you can pass those in the form of a string or an array to the `GoogleAuth` constructor. + +The code below shows how to retrieve a default credential type, depending upon the runtime environment. + +```js +const {GoogleAuth} = require('google-auth-library'); + +/** + * Instead of specifying the type of client you'd like to use (JWT, OAuth2, etc) + * this library will automatically choose the right client based on the environment. + */ +async function main() { + const auth = new GoogleAuth({ + scopes: 'https://www.googleapis.com/auth/cloud-platform' + }); + const client = await auth.getClient(); + const projectId = await auth.getProjectId(); + const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`; + const res = await client.request({ url }); + console.log(res.data); +} + +main().catch(console.error); +``` + +## OAuth2 + +This library comes with an [OAuth2][oauth] client that allows you to retrieve an access token and refreshes the token and retry the request seamlessly if you also provide an `expiry_date` and the token is expired. The basics of Google's OAuth2 implementation is explained on [Google Authorization and Authentication documentation][authdocs]. + +In the following examples, you may need a `CLIENT_ID`, `CLIENT_SECRET` and `REDIRECT_URL`. You can find these pieces of information by going to the [Developer Console][devconsole], clicking your project > APIs & auth > credentials. + +For more information about OAuth2 and how it works, [see here][oauth]. + +#### A complete OAuth2 example + +Let's take a look at a complete example. + +``` js +const {OAuth2Client} = require('google-auth-library'); +const http = require('http'); +const url = require('url'); +const open = require('open'); +const destroyer = require('server-destroy'); + +// Download your OAuth2 configuration from the Google +const keys = require('./oauth2.keys.json'); + +/** + * Start by acquiring a pre-authenticated oAuth2 client. + */ +async function main() { + const oAuth2Client = await getAuthenticatedClient(); + // Make a simple request to the People API using our pre-authenticated client. The `request()` method + // takes an GaxiosOptions object. Visit https://github.com/JustinBeckwith/gaxios. + const url = 'https://people.googleapis.com/v1/people/me?personFields=names'; + const res = await oAuth2Client.request({url}); + console.log(res.data); + + // After acquiring an access_token, you may want to check on the audience, expiration, + // or original scopes requested. You can do that with the `getTokenInfo` method. + const tokenInfo = await oAuth2Client.getTokenInfo( + oAuth2Client.credentials.access_token + ); + console.log(tokenInfo); +} + +/** + * Create a new OAuth2Client, and go through the OAuth2 content + * workflow. Return the full client to the callback. + */ +function getAuthenticatedClient() { + return new Promise((resolve, reject) => { + // create an oAuth client to authorize the API call. Secrets are kept in a `keys.json` file, + // which should be downloaded from the Google Developers Console. + const oAuth2Client = new OAuth2Client( + keys.web.client_id, + keys.web.client_secret, + keys.web.redirect_uris[0] + ); + + // Generate the url that will be used for the consent dialog. + const authorizeUrl = oAuth2Client.generateAuthUrl({ + access_type: 'offline', + scope: 'https://www.googleapis.com/auth/userinfo.profile', + }); + + // Open an http server to accept the oauth callback. In this simple example, the + // only request to our webserver is to /oauth2callback?code= + const server = http + .createServer(async (req, res) => { + try { + if (req.url.indexOf('/oauth2callback') > -1) { + // acquire the code from the querystring, and close the web server. + const qs = new url.URL(req.url, 'http://localhost:3000') + .searchParams; + const code = qs.get('code'); + console.log(`Code is ${code}`); + res.end('Authentication successful! Please return to the console.'); + server.destroy(); + + // Now that we have the code, use that to acquire tokens. + const r = await oAuth2Client.getToken(code); + // Make sure to set the credentials on the OAuth2 client. + oAuth2Client.setCredentials(r.tokens); + console.info('Tokens acquired.'); + resolve(oAuth2Client); + } + } catch (e) { + reject(e); + } + }) + .listen(3000, () => { + // open the browser to the authorize url to start the workflow + open(authorizeUrl, {wait: false}).then(cp => cp.unref()); + }); + destroyer(server); + }); +} + +main().catch(console.error); +``` + +#### Handling token events + +This library will automatically obtain an `access_token`, and automatically refresh the `access_token` if a `refresh_token` is present. The `refresh_token` is only returned on the [first authorization](https://github.com/googleapis/google-api-nodejs-client/issues/750#issuecomment-304521450), so if you want to make sure you store it safely. An easy way to make sure you always store the most recent tokens is to use the `tokens` event: + +```js +const client = await auth.getClient(); + +client.on('tokens', (tokens) => { + if (tokens.refresh_token) { + // store the refresh_token in my database! + console.log(tokens.refresh_token); + } + console.log(tokens.access_token); +}); + +const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`; +const res = await client.request({ url }); +// The `tokens` event would now be raised if this was the first request +``` + +#### Retrieve access token +With the code returned, you can ask for an access token as shown below: + +``` js +const tokens = await oauth2Client.getToken(code); +// Now tokens contains an access_token and an optional refresh_token. Save them. +oauth2Client.setCredentials(tokens); +``` + +#### Obtaining a new Refresh Token +If you need to obtain a new `refresh_token`, ensure the call to `generateAuthUrl` sets the `access_type` to `offline`. The refresh token will only be returned for the first authorization by the user. To force consent, set the `prompt` property to `consent`: + +```js +// Generate the url that will be used for the consent dialog. +const authorizeUrl = oAuth2Client.generateAuthUrl({ + // To get a refresh token, you MUST set access_type to `offline`. + access_type: 'offline', + // set the appropriate scopes + scope: 'https://www.googleapis.com/auth/userinfo.profile', + // A refresh token is only returned the first time the user + // consents to providing access. For illustration purposes, + // setting the prompt to 'consent' will force this consent + // every time, forcing a refresh_token to be returned. + prompt: 'consent' +}); +``` + +#### Checking `access_token` information +After obtaining and storing an `access_token`, at a later time you may want to go check the expiration date, +original scopes, or audience for the token. To get the token info, you can use the `getTokenInfo` method: + +```js +// after acquiring an oAuth2Client... +const tokenInfo = await oAuth2Client.getTokenInfo('my-access-token'); + +// take a look at the scopes originally provisioned for the access token +console.log(tokenInfo.scopes); +``` + +This method will throw if the token is invalid. + +#### OAuth2 with Installed Apps (Electron) +If you're authenticating with OAuth2 from an installed application (like Electron), you may not want to embed your `client_secret` inside of the application sources. To work around this restriction, you can choose the `iOS` application type when creating your OAuth2 credentials in the [Google Developers console][devconsole]: + +![application type][apptype] + +If using the `iOS` type, when creating the OAuth2 client you won't need to pass a `client_secret` into the constructor: +```js +const oAuth2Client = new OAuth2Client({ + clientId: , + redirectUri: +}); +``` + +## JSON Web Tokens +The Google Developers Console provides a `.json` file that you can use to configure a JWT auth client and authenticate your requests, for example when using a service account. + +``` js +const {JWT} = require('google-auth-library'); +const keys = require('./jwt.keys.json'); + +async function main() { + const client = new JWT( + keys.client_email, + null, + keys.private_key, + ['https://www.googleapis.com/auth/cloud-platform'], + ); + const url = `https://dns.googleapis.com/dns/v1/projects/${keys.project_id}`; + const res = await client.request({url}); + console.log(res.data); +} + +main().catch(console.error); +``` + +The parameters for the JWT auth client including how to use it with a `.pem` file are explained in [samples/jwt.js](https://github.com/googleapis/google-auth-library-nodejs/blob/master/samples/jwt.js). + +#### Loading credentials from environment variables +Instead of loading credentials from a key file, you can also provide them using an environment variable and the `GoogleAuth.fromJSON()` method. This is particularly convenient for systems that deploy directly from source control (Heroku, App Engine, etc). + +Start by exporting your credentials: + +``` +$ export CREDS='{ + "type": "service_account", + "project_id": "your-project-id", + "private_key_id": "your-private-key-id", + "private_key": "your-private-key", + "client_email": "your-client-email", + "client_id": "your-client-id", + "auth_uri": "https://accounts.google.com/o/oauth2/auth", + "token_uri": "https://accounts.google.com/o/oauth2/token", + "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", + "client_x509_cert_url": "your-cert-url" +}' +``` +Now you can create a new client from the credentials: + +```js +const {auth} = require('google-auth-library'); + +// load the environment variable with our keys +const keysEnvVar = process.env['CREDS']; +if (!keysEnvVar) { + throw new Error('The $CREDS environment variable was not found!'); +} +const keys = JSON.parse(keysEnvVar); + +async function main() { + // load the JWT or UserRefreshClient from the keys + const client = auth.fromJSON(keys); + client.scopes = ['https://www.googleapis.com/auth/cloud-platform']; + const url = `https://dns.googleapis.com/dns/v1/projects/${keys.project_id}`; + const res = await client.request({url}); + console.log(res.data); +} + +main().catch(console.error); +``` + +#### Using a Proxy +You can set the `HTTPS_PROXY` or `https_proxy` environment variables to proxy HTTPS requests. When `HTTPS_PROXY` or `https_proxy` are set, they will be used to proxy SSL requests that do not have an explicit proxy configuration option present. + +## Compute +If your application is running on Google Cloud Platform, you can authenticate using the default service account or by specifying a specific service account. + +**Note**: In most cases, you will want to use [Application Default Credentials](#choosing-the-correct-credential-type-automatically). Direct use of the `Compute` class is for very specific scenarios. + +``` js +const {auth, Compute} = require('google-auth-library'); + +async function main() { + const client = new Compute({ + // Specifying the service account email is optional. + serviceAccountEmail: 'my-service-account@example.com' + }); + const projectId = await auth.getProjectId(); + const url = `https://dns.googleapis.com/dns/v1/projects/${projectId}`; + const res = await client.request({url}); + console.log(res.data); +} + +main().catch(console.error); +``` + +## Working with ID Tokens +### Fetching ID Tokens +If your application is running behind Cloud Run, or using Cloud Identity-Aware +Proxy (IAP), you will need to fetch an ID token to access your application. For +this, use the method `getIdTokenClient` on the `GoogleAuth` client. + +For invoking Cloud Run services, your service account will need the +[`Cloud Run Invoker`](https://cloud.google.com/run/docs/authenticating/service-to-service) +IAM permission. + +``` js +// Make a request to a protected Cloud Run +const {GoogleAuth} = require('google-auth-library'); + +async function main() { + const url = 'https://cloud-run-url.com'; + const auth = new GoogleAuth(); + const client = auth.getIdTokenClient(url); + const res = await client.request({url}); + console.log(res.data); +} + +main().catch(console.error); +``` + +A complete example can be found in [`samples/idtokens-cloudrun.js`](https://github.com/googleapis/google-auth-library-nodejs/blob/master/samples/idtokens-cloudrun.js). + +For invoking Cloud Identity-Aware Proxy, you will need to pass the Client ID +used when you set up your protected resource as the target audience. + +``` js +// Make a request to a protected Cloud Identity-Aware Proxy (IAP) resource +const {GoogleAuth} = require('google-auth-library'); + +async function main() + const targetAudience = 'iap-client-id'; + const url = 'https://iap-url.com'; + const auth = new GoogleAuth(); + const client = auth.getIdTokenClient(targetAudience); + const res = await client.request({url}); + console.log(res.data); +} + +main().catch(console.error); +``` + +A complete example can be found in [`samples/idtokens-iap.js`](https://github.com/googleapis/google-auth-library-nodejs/blob/master/samples/idtokens-iap.js). + +### Verifying ID Tokens + +If you've [secured your IAP app with signed headers](https://cloud.google.com/iap/docs/signed-headers-howto), +you can use this library to verify the IAP header: + +```js +const {OAuth2Client} = require('google-auth-library'); +// Expected audience for App Engine. +const expectedAudience = `/projects/your-project-number/apps/your-project-id`; +// IAP issuer +const issuers = ['https://cloud.google.com/iap']; +// Verify the token. OAuth2Client throws an Error if verification fails +const oAuth2Client = new OAuth2Client(); +const response = await oAuth2Client.getIapCerts(); +const ticket = await oAuth2Client.verifySignedJwtWithCertsAsync( + idToken, + response.pubkeys, + expectedAudience, + issuers +); + +// Print out the info contained in the IAP ID token +console.log(ticket) +``` + +A complete example can be found in [`samples/verifyIdToken-iap.js`](https://github.com/googleapis/google-auth-library-nodejs/blob/master/samples/verifyIdToken-iap.js). + +## Questions/problems? + +* Ask your development related questions on [Stack Overflow][stackoverflow]. +* If you've found an bug/issue, please [file it on GitHub][bugs]. + +## Contributing + +See [CONTRIBUTING][contributing]. + +## License + +This library is licensed under Apache 2.0. Full license text is available in [LICENSE][copying]. + +[Application Default Credentials]: https://cloud.google.com/docs/authentication/getting-started +[apptype]: https://user-images.githubusercontent.com/534619/36553844-3f9a863c-17b2-11e8-904a-29f6cd5f807a.png +[authdocs]: https://developers.google.com/accounts/docs/OAuth2Login +[bugs]: https://github.com/googleapis/google-auth-library-nodejs/issues +[codecov-image]: https://codecov.io/gh/googleapis/google-auth-library-nodejs/branch/master/graph/badge.svg +[codecov-url]: https://codecov.io/gh/googleapis/google-auth-library-nodejs +[contributing]: https://github.com/googleapis/google-auth-library-nodejs/blob/master/CONTRIBUTING.md +[copying]: https://github.com/googleapis/google-auth-library-nodejs/tree/master/LICENSE +[david-dm-img]: https://david-dm.org/googleapis/google-auth-library-nodejs/status.svg +[david-dm]: https://david-dm.org/googleapis/google-auth-library-nodejs +[node]: http://nodejs.org/ +[npmimg]: https://img.shields.io/npm/v/google-auth-library.svg +[npm]: https://www.npmjs.org/package/google-auth-library +[oauth]: https://developers.google.com/identity/protocols/OAuth2 +[snyk-image]: https://snyk.io/test/github/googleapis/google-auth-library-nodejs/badge.svg +[snyk-url]: https://snyk.io/test/github/googleapis/google-auth-library-nodejs +[stackoverflow]: http://stackoverflow.com/questions/tagged/google-auth-library-nodejs +[devconsole]: https://console.cloud.google.com/ diff --git a/node_modules/google-auth-library/build/src/auth/authclient.d.ts b/node_modules/google-auth-library/build/src/auth/authclient.d.ts new file mode 100644 index 0000000..8333fb8 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/authclient.d.ts @@ -0,0 +1,31 @@ +/// +import { EventEmitter } from 'events'; +import { GaxiosOptions, GaxiosPromise } from 'gaxios'; +import { DefaultTransporter } from '../transporters'; +import { Credentials } from './credentials'; +import { Headers } from './oauth2client'; +export declare interface AuthClient { + on(event: 'tokens', listener: (tokens: Credentials) => void): this; +} +export declare abstract class AuthClient extends EventEmitter { + protected quotaProjectId?: string; + transporter: DefaultTransporter; + credentials: Credentials; + /** + * Provides an alternative Gaxios request implementation with auth credentials + */ + abstract request(opts: GaxiosOptions): GaxiosPromise; + /** + * Sets the auth credentials. + */ + setCredentials(credentials: Credentials): void; + /** + * Append additional headers, e.g., x-goog-user-project, shared across the + * classes inheriting AuthClient. This method should be used by any method + * that overrides getRequestMetadataAsync(), which is a shared helper for + * setting request information in both gRPC and HTTP API calls. + * + * @param headers objedcdt to append additional headers to. + */ + protected addSharedMetadataHeaders(headers: Headers): Headers; +} diff --git a/node_modules/google-auth-library/build/src/auth/authclient.js b/node_modules/google-auth-library/build/src/auth/authclient.js new file mode 100644 index 0000000..ec743f2 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/authclient.js @@ -0,0 +1,50 @@ +"use strict"; +// Copyright 2012 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +const events_1 = require("events"); +const transporters_1 = require("../transporters"); +class AuthClient extends events_1.EventEmitter { + constructor() { + super(...arguments); + this.transporter = new transporters_1.DefaultTransporter(); + this.credentials = {}; + } + /** + * Sets the auth credentials. + */ + setCredentials(credentials) { + this.credentials = credentials; + } + /** + * Append additional headers, e.g., x-goog-user-project, shared across the + * classes inheriting AuthClient. This method should be used by any method + * that overrides getRequestMetadataAsync(), which is a shared helper for + * setting request information in both gRPC and HTTP API calls. + * + * @param headers objedcdt to append additional headers to. + */ + addSharedMetadataHeaders(headers) { + // quota_project_id, stored in application_default_credentials.json, is set in + // the x-goog-user-project header, to indicate an alternate account for + // billing and quota: + if (!headers['x-goog-user-project'] && // don't override a value the user sets. + this.quotaProjectId) { + headers['x-goog-user-project'] = this.quotaProjectId; + } + return headers; + } +} +exports.AuthClient = AuthClient; +//# sourceMappingURL=authclient.js.map \ No newline at end of file diff --git a/node_modules/google-auth-library/build/src/auth/computeclient.d.ts b/node_modules/google-auth-library/build/src/auth/computeclient.d.ts new file mode 100644 index 0000000..c3353ec --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/computeclient.d.ts @@ -0,0 +1,37 @@ +import { GaxiosError } from 'gaxios'; +import { GetTokenResponse, OAuth2Client, RefreshOptions } from './oauth2client'; +export interface ComputeOptions extends RefreshOptions { + /** + * The service account email to use, or 'default'. A Compute Engine instance + * may have multiple service accounts. + */ + serviceAccountEmail?: string; + /** + * The scopes that will be requested when acquiring service account + * credentials. Only applicable to modern App Engine and Cloud Function + * runtimes as of March 2019. + */ + scopes?: string | string[]; +} +export declare class Compute extends OAuth2Client { + private serviceAccountEmail; + scopes: string[]; + /** + * Google Compute Engine service account credentials. + * + * Retrieve access token from the metadata server. + * See: https://developers.google.com/compute/docs/authentication + */ + constructor(options?: ComputeOptions); + /** + * Refreshes the access token. + * @param refreshToken Unused parameter + */ + protected refreshTokenNoCache(refreshToken?: string | null): Promise; + /** + * Fetches an ID token. + * @param targetAudience the audience for the fetched ID token. + */ + fetchIdToken(targetAudience: string): Promise; + protected wrapError(e: GaxiosError): void; +} diff --git a/node_modules/google-auth-library/build/src/auth/computeclient.js b/node_modules/google-auth-library/build/src/auth/computeclient.js new file mode 100644 index 0000000..ed47c2d --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/computeclient.js @@ -0,0 +1,107 @@ +"use strict"; +// Copyright 2013 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +const arrify = require("arrify"); +const gcpMetadata = require("gcp-metadata"); +const oauth2client_1 = require("./oauth2client"); +class Compute extends oauth2client_1.OAuth2Client { + /** + * Google Compute Engine service account credentials. + * + * Retrieve access token from the metadata server. + * See: https://developers.google.com/compute/docs/authentication + */ + constructor(options = {}) { + super(options); + // Start with an expired refresh token, which will automatically be + // refreshed before the first API call is made. + this.credentials = { expiry_date: 1, refresh_token: 'compute-placeholder' }; + this.serviceAccountEmail = options.serviceAccountEmail || 'default'; + this.scopes = arrify(options.scopes); + } + /** + * Refreshes the access token. + * @param refreshToken Unused parameter + */ + async refreshTokenNoCache(refreshToken) { + const tokenPath = `service-accounts/${this.serviceAccountEmail}/token`; + let data; + try { + const instanceOptions = { + property: tokenPath, + }; + if (this.scopes.length > 0) { + instanceOptions.params = { + scopes: this.scopes.join(','), + }; + } + data = await gcpMetadata.instance(instanceOptions); + } + catch (e) { + e.message = `Could not refresh access token: ${e.message}`; + this.wrapError(e); + throw e; + } + const tokens = data; + if (data && data.expires_in) { + tokens.expiry_date = new Date().getTime() + data.expires_in * 1000; + delete tokens.expires_in; + } + this.emit('tokens', tokens); + return { tokens, res: null }; + } + /** + * Fetches an ID token. + * @param targetAudience the audience for the fetched ID token. + */ + async fetchIdToken(targetAudience) { + const idTokenPath = `service-accounts/${this.serviceAccountEmail}/identity` + + `?format=full&audience=${targetAudience}`; + let idToken; + try { + const instanceOptions = { + property: idTokenPath, + }; + idToken = await gcpMetadata.instance(instanceOptions); + } + catch (e) { + e.message = `Could not fetch ID token: ${e.message}`; + throw e; + } + return idToken; + } + wrapError(e) { + const res = e.response; + if (res && res.status) { + e.code = res.status.toString(); + if (res.status === 403) { + e.message = + 'A Forbidden error was returned while attempting to retrieve an access ' + + 'token for the Compute Engine built-in service account. This may be because the Compute ' + + 'Engine instance does not have the correct permission scopes specified: ' + + e.message; + } + else if (res.status === 404) { + e.message = + 'A Not Found error was returned while attempting to retrieve an access' + + 'token for the Compute Engine built-in service account. This may be because the Compute ' + + 'Engine instance does not have any permission scopes specified: ' + + e.message; + } + } + } +} +exports.Compute = Compute; +//# sourceMappingURL=computeclient.js.map \ No newline at end of file diff --git a/node_modules/google-auth-library/build/src/auth/credentials.d.ts b/node_modules/google-auth-library/build/src/auth/credentials.d.ts new file mode 100644 index 0000000..2c65046 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/credentials.d.ts @@ -0,0 +1,29 @@ +export interface Credentials { + refresh_token?: string | null; + expiry_date?: number | null; + access_token?: string | null; + token_type?: string | null; + id_token?: string | null; +} +export interface CredentialRequest { + refresh_token?: string; + access_token?: string; + token_type?: string; + expires_in?: number; + id_token?: string; +} +export interface JWTInput { + type?: string; + client_email?: string; + private_key?: string; + private_key_id?: string; + project_id?: string; + client_id?: string; + client_secret?: string; + refresh_token?: string; + quota_project_id?: string; +} +export interface CredentialBody { + client_email?: string; + private_key?: string; +} diff --git a/node_modules/google-auth-library/build/src/auth/credentials.js b/node_modules/google-auth-library/build/src/auth/credentials.js new file mode 100644 index 0000000..5ea0d58 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/credentials.js @@ -0,0 +1,16 @@ +"use strict"; +// Copyright 2014 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=credentials.js.map \ No newline at end of file diff --git a/node_modules/google-auth-library/build/src/auth/envDetect.d.ts b/node_modules/google-auth-library/build/src/auth/envDetect.d.ts new file mode 100644 index 0000000..8b462cd --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/envDetect.d.ts @@ -0,0 +1,9 @@ +export declare enum GCPEnv { + APP_ENGINE = "APP_ENGINE", + KUBERNETES_ENGINE = "KUBERNETES_ENGINE", + CLOUD_FUNCTIONS = "CLOUD_FUNCTIONS", + COMPUTE_ENGINE = "COMPUTE_ENGINE", + NONE = "NONE" +} +export declare function clear(): void; +export declare function getEnv(): Promise; diff --git a/node_modules/google-auth-library/build/src/auth/envDetect.js b/node_modules/google-auth-library/build/src/auth/envDetect.js new file mode 100644 index 0000000..87ce791 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/envDetect.js @@ -0,0 +1,77 @@ +"use strict"; +// Copyright 2018 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +const gcpMetadata = require("gcp-metadata"); +var GCPEnv; +(function (GCPEnv) { + GCPEnv["APP_ENGINE"] = "APP_ENGINE"; + GCPEnv["KUBERNETES_ENGINE"] = "KUBERNETES_ENGINE"; + GCPEnv["CLOUD_FUNCTIONS"] = "CLOUD_FUNCTIONS"; + GCPEnv["COMPUTE_ENGINE"] = "COMPUTE_ENGINE"; + GCPEnv["NONE"] = "NONE"; +})(GCPEnv = exports.GCPEnv || (exports.GCPEnv = {})); +let envPromise; +function clear() { + envPromise = undefined; +} +exports.clear = clear; +async function getEnv() { + if (envPromise) { + return envPromise; + } + envPromise = getEnvMemoized(); + return envPromise; +} +exports.getEnv = getEnv; +async function getEnvMemoized() { + let env = GCPEnv.NONE; + if (isAppEngine()) { + env = GCPEnv.APP_ENGINE; + } + else if (isCloudFunction()) { + env = GCPEnv.CLOUD_FUNCTIONS; + } + else if (await isComputeEngine()) { + if (await isKubernetesEngine()) { + env = GCPEnv.KUBERNETES_ENGINE; + } + else { + env = GCPEnv.COMPUTE_ENGINE; + } + } + else { + env = GCPEnv.NONE; + } + return env; +} +function isAppEngine() { + return !!(process.env.GAE_SERVICE || process.env.GAE_MODULE_NAME); +} +function isCloudFunction() { + return !!(process.env.FUNCTION_NAME || process.env.FUNCTION_TARGET); +} +async function isKubernetesEngine() { + try { + await gcpMetadata.instance('attributes/cluster-name'); + return true; + } + catch (e) { + return false; + } +} +async function isComputeEngine() { + return gcpMetadata.isAvailable(); +} +//# sourceMappingURL=envDetect.js.map \ No newline at end of file diff --git a/node_modules/google-auth-library/build/src/auth/googleauth.d.ts b/node_modules/google-auth-library/build/src/auth/googleauth.d.ts new file mode 100644 index 0000000..0ce3408 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/googleauth.d.ts @@ -0,0 +1,243 @@ +/// +import { GaxiosOptions, GaxiosResponse } from 'gaxios'; +import * as stream from 'stream'; +import { DefaultTransporter, Transporter } from '../transporters'; +import { Compute } from './computeclient'; +import { CredentialBody, JWTInput } from './credentials'; +import { IdTokenClient } from './idtokenclient'; +import { GCPEnv } from './envDetect'; +import { JWT, JWTOptions } from './jwtclient'; +import { Headers, OAuth2Client, OAuth2ClientOptions, RefreshOptions } from './oauth2client'; +import { UserRefreshClient, UserRefreshClientOptions } from './refreshclient'; +export interface ProjectIdCallback { + (err?: Error | null, projectId?: string | null): void; +} +export interface CredentialCallback { + (err: Error | null, result?: UserRefreshClient | JWT): void; +} +interface DeprecatedGetClientOptions { +} +export interface ADCCallback { + (err: Error | null, credential?: OAuth2Client, projectId?: string | null): void; +} +export interface ADCResponse { + credential: OAuth2Client; + projectId: string | null; +} +export interface GoogleAuthOptions { + /** + * Path to a .json, .pem, or .p12 key file + */ + keyFilename?: string; + /** + * Path to a .json, .pem, or .p12 key file + */ + keyFile?: string; + /** + * Object containing client_email and private_key properties + */ + credentials?: CredentialBody; + /** + * Options object passed to the constructor of the client + */ + clientOptions?: JWTOptions | OAuth2ClientOptions | UserRefreshClientOptions; + /** + * Required scopes for the desired API request + */ + scopes?: string | string[]; + /** + * Your project ID. + */ + projectId?: string; +} +export declare const CLOUD_SDK_CLIENT_ID = "764086051850-6qr4p6gpi6hn506pt8ejuq83di341hur.apps.googleusercontent.com"; +export declare class GoogleAuth { + transporter?: Transporter; + /** + * Caches a value indicating whether the auth layer is running on Google + * Compute Engine. + * @private + */ + private checkIsGCE?; + get isGCE(): boolean | undefined; + private _getDefaultProjectIdPromise?; + private _cachedProjectId?; + jsonContent: JWTInput | null; + cachedCredential: JWT | UserRefreshClient | Compute | null; + private keyFilename?; + private scopes?; + private clientOptions?; + /** + * Export DefaultTransporter as a static property of the class. + */ + static DefaultTransporter: typeof DefaultTransporter; + constructor(opts?: GoogleAuthOptions); + /** + * Obtains the default project ID for the application. + * @param callback Optional callback + * @returns Promise that resolves with project Id (if used without callback) + */ + getProjectId(): Promise; + getProjectId(callback: ProjectIdCallback): void; + private getProjectIdAsync; + /** + * Obtains the default service-level credentials for the application. + * @param callback Optional callback. + * @returns Promise that resolves with the ADCResponse (if no callback was + * passed). + */ + getApplicationDefault(): Promise; + getApplicationDefault(callback: ADCCallback): void; + getApplicationDefault(options: RefreshOptions): Promise; + getApplicationDefault(options: RefreshOptions, callback: ADCCallback): void; + private getApplicationDefaultAsync; + /** + * Determines whether the auth layer is running on Google Compute Engine. + * @returns A promise that resolves with the boolean. + * @api private + */ + _checkIsGCE(): Promise; + /** + * Attempts to load default credentials from the environment variable path.. + * @returns Promise that resolves with the OAuth2Client or null. + * @api private + */ + _tryGetApplicationCredentialsFromEnvironmentVariable(options?: RefreshOptions): Promise; + /** + * Attempts to load default credentials from a well-known file location + * @return Promise that resolves with the OAuth2Client or null. + * @api private + */ + _tryGetApplicationCredentialsFromWellKnownFile(options?: RefreshOptions): Promise; + /** + * Attempts to load default credentials from a file at the given path.. + * @param filePath The path to the file to read. + * @returns Promise that resolves with the OAuth2Client + * @api private + */ + _getApplicationCredentialsFromFilePath(filePath: string, options?: RefreshOptions): Promise; + /** + * Create a credentials instance using the given input options. + * @param json The input object. + * @param options The JWT or UserRefresh options for the client + * @returns JWT or UserRefresh Client with data + */ + fromJSON(json: JWTInput, options?: RefreshOptions): JWT | UserRefreshClient; + /** + * Return a JWT or UserRefreshClient from JavaScript object, caching both the + * object used to instantiate and the client. + * @param json The input object. + * @param options The JWT or UserRefresh options for the client + * @returns JWT or UserRefresh Client with data + */ + private _cacheClientFromJSON; + /** + * Create a credentials instance using the given input stream. + * @param inputStream The input stream. + * @param callback Optional callback. + */ + fromStream(inputStream: stream.Readable): Promise; + fromStream(inputStream: stream.Readable, callback: CredentialCallback): void; + fromStream(inputStream: stream.Readable, options: RefreshOptions): Promise; + fromStream(inputStream: stream.Readable, options: RefreshOptions, callback: CredentialCallback): void; + private fromStreamAsync; + /** + * Create a credentials instance using the given API key string. + * @param apiKey The API key string + * @param options An optional options object. + * @returns A JWT loaded from the key + */ + fromAPIKey(apiKey: string, options?: RefreshOptions): JWT; + /** + * Determines whether the current operating system is Windows. + * @api private + */ + private _isWindows; + /** + * Run the Google Cloud SDK command that prints the default project ID + */ + private getDefaultServiceProjectId; + /** + * Loads the project id from environment variables. + * @api private + */ + private getProductionProjectId; + /** + * Loads the project id from the GOOGLE_APPLICATION_CREDENTIALS json file. + * @api private + */ + private getFileProjectId; + /** + * Gets the Compute Engine project ID if it can be inferred. + */ + private getGCEProjectId; + /** + * The callback function handles a credential object that contains the + * client_email and private_key (if exists). + * getCredentials checks for these values from the user JSON at first. + * If it doesn't exist, and the environment is on GCE, it gets the + * client_email from the cloud metadata server. + * @param callback Callback that handles the credential object that contains + * a client_email and optional private key, or the error. + * returned + */ + getCredentials(): Promise; + getCredentials(callback: (err: Error | null, credentials?: CredentialBody) => void): void; + private getCredentialsAsync; + /** + * Automatically obtain a client based on the provided configuration. If no + * options were passed, use Application Default Credentials. + */ + getClient(options?: DeprecatedGetClientOptions): Promise; + /** + * Creates a client which will fetch an ID token for authorization. + * @param targetAudience the audience for the fetched ID token. + * @returns IdTokenClient for making HTTP calls authenticated with ID tokens. + */ + getIdTokenClient(targetAudience: string): Promise; + /** + * Automatically obtain application default credentials, and return + * an access token for making requests. + */ + getAccessToken(): Promise; + /** + * Obtain the HTTP headers that will provide authorization for a given + * request. + */ + getRequestHeaders(url?: string): Promise; + /** + * Obtain credentials for a request, then attach the appropriate headers to + * the request options. + * @param opts Axios or Request options on which to attach the headers + */ + authorizeRequest(opts: { + url?: string; + uri?: string; + headers?: Headers; + }): Promise<{ + url?: string | undefined; + uri?: string | undefined; + headers?: Headers | undefined; + }>; + /** + * Automatically obtain application default credentials, and make an + * HTTP request using the given options. + * @param opts Axios request options for the HTTP request. + */ + request(opts: GaxiosOptions): Promise>; + /** + * Determine the compute environment in which the code is running. + */ + getEnv(): Promise; + /** + * Sign the given data with the current private key, or go out + * to the IAM API to sign it. + * @param data The data to be signed. + */ + sign(data: string): Promise; +} +export interface SignBlobResponse { + keyId: string; + signedBlob: string; +} +export {}; diff --git a/node_modules/google-auth-library/build/src/auth/googleauth.js b/node_modules/google-auth-library/build/src/auth/googleauth.js new file mode 100644 index 0000000..d4709aa --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/googleauth.js @@ -0,0 +1,583 @@ +"use strict"; +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +const child_process_1 = require("child_process"); +const fs = require("fs"); +const gcpMetadata = require("gcp-metadata"); +const os = require("os"); +const path = require("path"); +const crypto_1 = require("../crypto/crypto"); +const transporters_1 = require("../transporters"); +const computeclient_1 = require("./computeclient"); +const idtokenclient_1 = require("./idtokenclient"); +const envDetect_1 = require("./envDetect"); +const jwtclient_1 = require("./jwtclient"); +const refreshclient_1 = require("./refreshclient"); +exports.CLOUD_SDK_CLIENT_ID = '764086051850-6qr4p6gpi6hn506pt8ejuq83di341hur.apps.googleusercontent.com'; +class GoogleAuth { + constructor(opts) { + /** + * Caches a value indicating whether the auth layer is running on Google + * Compute Engine. + * @private + */ + this.checkIsGCE = undefined; + // To save the contents of the JSON credential file + this.jsonContent = null; + this.cachedCredential = null; + opts = opts || {}; + this._cachedProjectId = opts.projectId || null; + this.keyFilename = opts.keyFilename || opts.keyFile; + this.scopes = opts.scopes; + this.jsonContent = opts.credentials || null; + this.clientOptions = opts.clientOptions; + } + // Note: this properly is only public to satisify unit tests. + // https://github.com/Microsoft/TypeScript/issues/5228 + get isGCE() { + return this.checkIsGCE; + } + getProjectId(callback) { + if (callback) { + this.getProjectIdAsync().then(r => callback(null, r), callback); + } + else { + return this.getProjectIdAsync(); + } + } + getProjectIdAsync() { + if (this._cachedProjectId) { + return Promise.resolve(this._cachedProjectId); + } + // In implicit case, supports three environments. In order of precedence, + // the implicit environments are: + // - GCLOUD_PROJECT or GOOGLE_CLOUD_PROJECT environment variable + // - GOOGLE_APPLICATION_CREDENTIALS JSON file + // - Cloud SDK: `gcloud config config-helper --format json` + // - GCE project ID from metadata server) + if (!this._getDefaultProjectIdPromise) { + // TODO: refactor the below code so that it doesn't mix and match + // promises and async/await. + this._getDefaultProjectIdPromise = new Promise( + // eslint-disable-next-line no-async-promise-executor + async (resolve, reject) => { + try { + const projectId = this.getProductionProjectId() || + (await this.getFileProjectId()) || + (await this.getDefaultServiceProjectId()) || + (await this.getGCEProjectId()); + this._cachedProjectId = projectId; + if (!projectId) { + throw new Error('Unable to detect a Project Id in the current environment. \n' + + 'To learn more about authentication and Google APIs, visit: \n' + + 'https://cloud.google.com/docs/authentication/getting-started'); + } + resolve(projectId); + } + catch (e) { + reject(e); + } + }); + } + return this._getDefaultProjectIdPromise; + } + getApplicationDefault(optionsOrCallback = {}, callback) { + let options; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } + else { + options = optionsOrCallback; + } + if (callback) { + this.getApplicationDefaultAsync(options).then(r => callback(null, r.credential, r.projectId), callback); + } + else { + return this.getApplicationDefaultAsync(options); + } + } + async getApplicationDefaultAsync(options = {}) { + // If we've already got a cached credential, just return it. + if (this.cachedCredential) { + return { + credential: this.cachedCredential, + projectId: await this.getProjectIdAsync(), + }; + } + let credential; + let projectId; + // Check for the existence of a local environment variable pointing to the + // location of the credential file. This is typically used in local + // developer scenarios. + credential = await this._tryGetApplicationCredentialsFromEnvironmentVariable(options); + if (credential) { + if (credential instanceof jwtclient_1.JWT) { + credential.scopes = this.scopes; + } + this.cachedCredential = credential; + projectId = await this.getProjectId(); + return { credential, projectId }; + } + // Look in the well-known credential file location. + credential = await this._tryGetApplicationCredentialsFromWellKnownFile(options); + if (credential) { + if (credential instanceof jwtclient_1.JWT) { + credential.scopes = this.scopes; + } + this.cachedCredential = credential; + projectId = await this.getProjectId(); + return { credential, projectId }; + } + // Determine if we're running on GCE. + let isGCE; + try { + isGCE = await this._checkIsGCE(); + } + catch (e) { + e.message = `Unexpected error determining execution environment: ${e.message}`; + throw e; + } + if (!isGCE) { + // We failed to find the default credentials. Bail out with an error. + throw new Error('Could not load the default credentials. Browse to https://cloud.google.com/docs/authentication/getting-started for more information.'); + } + // For GCE, just return a default ComputeClient. It will take care of + // the rest. + options.scopes = this.scopes; + this.cachedCredential = new computeclient_1.Compute(options); + projectId = await this.getProjectId(); + return { projectId, credential: this.cachedCredential }; + } + /** + * Determines whether the auth layer is running on Google Compute Engine. + * @returns A promise that resolves with the boolean. + * @api private + */ + async _checkIsGCE() { + if (this.checkIsGCE === undefined) { + this.checkIsGCE = await gcpMetadata.isAvailable(); + } + return this.checkIsGCE; + } + /** + * Attempts to load default credentials from the environment variable path.. + * @returns Promise that resolves with the OAuth2Client or null. + * @api private + */ + async _tryGetApplicationCredentialsFromEnvironmentVariable(options) { + const credentialsPath = process.env['GOOGLE_APPLICATION_CREDENTIALS'] || + process.env['google_application_credentials']; + if (!credentialsPath || credentialsPath.length === 0) { + return null; + } + try { + return this._getApplicationCredentialsFromFilePath(credentialsPath, options); + } + catch (e) { + e.message = `Unable to read the credential file specified by the GOOGLE_APPLICATION_CREDENTIALS environment variable: ${e.message}`; + throw e; + } + } + /** + * Attempts to load default credentials from a well-known file location + * @return Promise that resolves with the OAuth2Client or null. + * @api private + */ + async _tryGetApplicationCredentialsFromWellKnownFile(options) { + // First, figure out the location of the file, depending upon the OS type. + let location = null; + if (this._isWindows()) { + // Windows + location = process.env['APPDATA']; + } + else { + // Linux or Mac + const home = process.env['HOME']; + if (home) { + location = path.join(home, '.config'); + } + } + // If we found the root path, expand it. + if (location) { + location = path.join(location, 'gcloud', 'application_default_credentials.json'); + if (!fs.existsSync(location)) { + location = null; + } + } + // The file does not exist. + if (!location) { + return null; + } + // The file seems to exist. Try to use it. + const client = await this._getApplicationCredentialsFromFilePath(location, options); + return client; + } + /** + * Attempts to load default credentials from a file at the given path.. + * @param filePath The path to the file to read. + * @returns Promise that resolves with the OAuth2Client + * @api private + */ + async _getApplicationCredentialsFromFilePath(filePath, options = {}) { + // Make sure the path looks like a string. + if (!filePath || filePath.length === 0) { + throw new Error('The file path is invalid.'); + } + // Make sure there is a file at the path. lstatSync will throw if there is + // nothing there. + try { + // Resolve path to actual file in case of symlink. Expect a thrown error + // if not resolvable. + filePath = fs.realpathSync(filePath); + if (!fs.lstatSync(filePath).isFile()) { + throw new Error(); + } + } + catch (err) { + err.message = `The file at ${filePath} does not exist, or it is not a file. ${err.message}`; + throw err; + } + // Now open a read stream on the file, and parse it. + const readStream = fs.createReadStream(filePath); + return this.fromStream(readStream, options); + } + /** + * Create a credentials instance using the given input options. + * @param json The input object. + * @param options The JWT or UserRefresh options for the client + * @returns JWT or UserRefresh Client with data + */ + fromJSON(json, options) { + let client; + if (!json) { + throw new Error('Must pass in a JSON object containing the Google auth settings.'); + } + options = options || {}; + if (json.type === 'authorized_user') { + client = new refreshclient_1.UserRefreshClient(options); + } + else { + options.scopes = this.scopes; + client = new jwtclient_1.JWT(options); + } + client.fromJSON(json); + return client; + } + /** + * Return a JWT or UserRefreshClient from JavaScript object, caching both the + * object used to instantiate and the client. + * @param json The input object. + * @param options The JWT or UserRefresh options for the client + * @returns JWT or UserRefresh Client with data + */ + _cacheClientFromJSON(json, options) { + let client; + // create either a UserRefreshClient or JWT client. + options = options || {}; + if (json.type === 'authorized_user') { + client = new refreshclient_1.UserRefreshClient(options); + } + else { + options.scopes = this.scopes; + client = new jwtclient_1.JWT(options); + } + client.fromJSON(json); + // cache both raw data used to instantiate client and client itself. + this.jsonContent = json; + this.cachedCredential = client; + return this.cachedCredential; + } + fromStream(inputStream, optionsOrCallback = {}, callback) { + let options = {}; + if (typeof optionsOrCallback === 'function') { + callback = optionsOrCallback; + } + else { + options = optionsOrCallback; + } + if (callback) { + this.fromStreamAsync(inputStream, options).then(r => callback(null, r), callback); + } + else { + return this.fromStreamAsync(inputStream, options); + } + } + fromStreamAsync(inputStream, options) { + return new Promise((resolve, reject) => { + if (!inputStream) { + throw new Error('Must pass in a stream containing the Google auth settings.'); + } + let s = ''; + inputStream + .setEncoding('utf8') + .on('error', reject) + .on('data', chunk => (s += chunk)) + .on('end', () => { + try { + const data = JSON.parse(s); + const r = this._cacheClientFromJSON(data, options); + return resolve(r); + } + catch (err) { + return reject(err); + } + }); + }); + } + /** + * Create a credentials instance using the given API key string. + * @param apiKey The API key string + * @param options An optional options object. + * @returns A JWT loaded from the key + */ + fromAPIKey(apiKey, options) { + options = options || {}; + const client = new jwtclient_1.JWT(options); + client.fromAPIKey(apiKey); + return client; + } + /** + * Determines whether the current operating system is Windows. + * @api private + */ + _isWindows() { + const sys = os.platform(); + if (sys && sys.length >= 3) { + if (sys.substring(0, 3).toLowerCase() === 'win') { + return true; + } + } + return false; + } + /** + * Run the Google Cloud SDK command that prints the default project ID + */ + async getDefaultServiceProjectId() { + return new Promise(resolve => { + child_process_1.exec('gcloud config config-helper --format json', (err, stdout, stderr) => { + if (!err && stdout) { + try { + const projectId = JSON.parse(stdout).configuration.properties.core + .project; + resolve(projectId); + return; + } + catch (e) { + // ignore errors + } + } + resolve(null); + }); + }); + } + /** + * Loads the project id from environment variables. + * @api private + */ + getProductionProjectId() { + return (process.env['GCLOUD_PROJECT'] || + process.env['GOOGLE_CLOUD_PROJECT'] || + process.env['gcloud_project'] || + process.env['google_cloud_project']); + } + /** + * Loads the project id from the GOOGLE_APPLICATION_CREDENTIALS json file. + * @api private + */ + async getFileProjectId() { + if (this.cachedCredential) { + // Try to read the project ID from the cached credentials file + return this.cachedCredential.projectId; + } + // Ensure the projectId is loaded from the keyFile if available. + if (this.keyFilename) { + const creds = await this.getClient(); + if (creds && creds.projectId) { + return creds.projectId; + } + } + // Try to load a credentials file and read its project ID + const r = await this._tryGetApplicationCredentialsFromEnvironmentVariable(); + if (r) { + return r.projectId; + } + else { + return null; + } + } + /** + * Gets the Compute Engine project ID if it can be inferred. + */ + async getGCEProjectId() { + try { + const r = await gcpMetadata.project('project-id'); + return r; + } + catch (e) { + // Ignore any errors + return null; + } + } + getCredentials(callback) { + if (callback) { + this.getCredentialsAsync().then(r => callback(null, r), callback); + } + else { + return this.getCredentialsAsync(); + } + } + async getCredentialsAsync() { + await this.getClient(); + if (this.jsonContent) { + const credential = { + client_email: this.jsonContent.client_email, + private_key: this.jsonContent.private_key, + }; + return credential; + } + const isGCE = await this._checkIsGCE(); + if (!isGCE) { + throw new Error('Unknown error.'); + } + // For GCE, return the service account details from the metadata server + // NOTE: The trailing '/' at the end of service-accounts/ is very important! + // The GCF metadata server doesn't respect querystring params if this / is + // not included. + const data = await gcpMetadata.instance({ + property: 'service-accounts/', + params: { recursive: 'true' }, + }); + if (!data || !data.default || !data.default.email) { + throw new Error('Failure from metadata server.'); + } + return { client_email: data.default.email }; + } + /** + * Automatically obtain a client based on the provided configuration. If no + * options were passed, use Application Default Credentials. + */ + async getClient(options) { + if (options) { + throw new Error('Passing options to getClient is forbidden in v5.0.0. Use new GoogleAuth(opts) instead.'); + } + if (!this.cachedCredential) { + if (this.jsonContent) { + this._cacheClientFromJSON(this.jsonContent, this.clientOptions); + } + else if (this.keyFilename) { + const filePath = path.resolve(this.keyFilename); + const stream = fs.createReadStream(filePath); + await this.fromStreamAsync(stream, this.clientOptions); + } + else { + await this.getApplicationDefaultAsync(this.clientOptions); + } + } + return this.cachedCredential; + } + /** + * Creates a client which will fetch an ID token for authorization. + * @param targetAudience the audience for the fetched ID token. + * @returns IdTokenClient for making HTTP calls authenticated with ID tokens. + */ + async getIdTokenClient(targetAudience) { + const client = await this.getClient(); + if (!('fetchIdToken' in client)) { + throw new Error('Cannot fetch ID token in this environment, use GCE or set the GOOGLE_APPLICATION_CREDENTIALS environment variable to a service account credentials JSON file.'); + } + return new idtokenclient_1.IdTokenClient({ targetAudience, idTokenProvider: client }); + } + /** + * Automatically obtain application default credentials, and return + * an access token for making requests. + */ + async getAccessToken() { + const client = await this.getClient(); + return (await client.getAccessToken()).token; + } + /** + * Obtain the HTTP headers that will provide authorization for a given + * request. + */ + async getRequestHeaders(url) { + const client = await this.getClient(); + return client.getRequestHeaders(url); + } + /** + * Obtain credentials for a request, then attach the appropriate headers to + * the request options. + * @param opts Axios or Request options on which to attach the headers + */ + async authorizeRequest(opts) { + opts = opts || {}; + const url = opts.url || opts.uri; + const client = await this.getClient(); + const headers = await client.getRequestHeaders(url); + opts.headers = Object.assign(opts.headers || {}, headers); + return opts; + } + /** + * Automatically obtain application default credentials, and make an + * HTTP request using the given options. + * @param opts Axios request options for the HTTP request. + */ + // tslint:disable-next-line no-any + async request(opts) { + const client = await this.getClient(); + return client.request(opts); + } + /** + * Determine the compute environment in which the code is running. + */ + getEnv() { + return envDetect_1.getEnv(); + } + /** + * Sign the given data with the current private key, or go out + * to the IAM API to sign it. + * @param data The data to be signed. + */ + async sign(data) { + const client = await this.getClient(); + const crypto = crypto_1.createCrypto(); + if (client instanceof jwtclient_1.JWT && client.key) { + const sign = await crypto.sign(client.key, data); + return sign; + } + const projectId = await this.getProjectId(); + if (!projectId) { + throw new Error('Cannot sign data without a project ID.'); + } + const creds = await this.getCredentials(); + if (!creds.client_email) { + throw new Error('Cannot sign data without `client_email`.'); + } + const url = `https://iamcredentials.googleapis.com/v1/projects/-/serviceAccounts/${creds.client_email}:signBlob`; + const res = await this.request({ + method: 'POST', + url, + data: { + payload: crypto.encodeBase64StringUtf8(data), + }, + }); + return res.data.signedBlob; + } +} +exports.GoogleAuth = GoogleAuth; +/** + * Export DefaultTransporter as a static property of the class. + */ +GoogleAuth.DefaultTransporter = transporters_1.DefaultTransporter; +//# sourceMappingURL=googleauth.js.map \ No newline at end of file diff --git a/node_modules/google-auth-library/build/src/auth/iam.d.ts b/node_modules/google-auth-library/build/src/auth/iam.d.ts new file mode 100644 index 0000000..93470a4 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/iam.d.ts @@ -0,0 +1,23 @@ +export interface RequestMetadata { + 'x-goog-iam-authority-selector': string; + 'x-goog-iam-authorization-token': string; +} +export declare class IAMAuth { + selector: string; + token: string; + /** + * IAM credentials. + * + * @param selector the iam authority selector + * @param token the token + * @constructor + */ + constructor(selector: string, token: string); + /** + * Acquire the HTTP headers required to make an authenticated request. + */ + getRequestHeaders(): { + 'x-goog-iam-authority-selector': string; + 'x-goog-iam-authorization-token': string; + }; +} diff --git a/node_modules/google-auth-library/build/src/auth/iam.js b/node_modules/google-auth-library/build/src/auth/iam.js new file mode 100644 index 0000000..fb4b55d --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/iam.js @@ -0,0 +1,41 @@ +"use strict"; +// Copyright 2014 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +class IAMAuth { + /** + * IAM credentials. + * + * @param selector the iam authority selector + * @param token the token + * @constructor + */ + constructor(selector, token) { + this.selector = selector; + this.token = token; + this.selector = selector; + this.token = token; + } + /** + * Acquire the HTTP headers required to make an authenticated request. + */ + getRequestHeaders() { + return { + 'x-goog-iam-authority-selector': this.selector, + 'x-goog-iam-authorization-token': this.token, + }; + } +} +exports.IAMAuth = IAMAuth; +//# sourceMappingURL=iam.js.map \ No newline at end of file diff --git a/node_modules/google-auth-library/build/src/auth/idtokenclient.d.ts b/node_modules/google-auth-library/build/src/auth/idtokenclient.d.ts new file mode 100644 index 0000000..bad975c --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/idtokenclient.d.ts @@ -0,0 +1,27 @@ +import { OAuth2Client, RequestMetadataResponse } from './oauth2client'; +export interface IdTokenOptions { + /** + * The client to make the request to fetch an ID token. + */ + idTokenProvider: IdTokenProvider; + /** + * The audience to use when requesting an ID token. + */ + targetAudience: string; +} +export interface IdTokenProvider { + fetchIdToken: (targetAudience: string) => Promise; +} +export declare class IdTokenClient extends OAuth2Client { + targetAudience: string; + idTokenProvider: IdTokenProvider; + /** + * Google ID Token client + * + * Retrieve access token from the metadata server. + * See: https://developers.google.com/compute/docs/authentication + */ + constructor(options: IdTokenOptions); + protected getRequestMetadataAsync(url?: string | null): Promise; + private getIdTokenExpiryDate; +} diff --git a/node_modules/google-auth-library/build/src/auth/idtokenclient.js b/node_modules/google-auth-library/build/src/auth/idtokenclient.js new file mode 100644 index 0000000..c3b3c6c --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/idtokenclient.js @@ -0,0 +1,52 @@ +"use strict"; +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +const oauth2client_1 = require("./oauth2client"); +class IdTokenClient extends oauth2client_1.OAuth2Client { + /** + * Google ID Token client + * + * Retrieve access token from the metadata server. + * See: https://developers.google.com/compute/docs/authentication + */ + constructor(options) { + super(); + this.targetAudience = options.targetAudience; + this.idTokenProvider = options.idTokenProvider; + } + async getRequestMetadataAsync(url) { + if (!this.credentials.id_token || + (this.credentials.expiry_date || 0) < Date.now()) { + const idToken = await this.idTokenProvider.fetchIdToken(this.targetAudience); + this.credentials = { + id_token: idToken, + expiry_date: this.getIdTokenExpiryDate(idToken), + }; + } + const headers = { + Authorization: 'Bearer ' + this.credentials.id_token, + }; + return { headers }; + } + getIdTokenExpiryDate(idToken) { + const payloadB64 = idToken.split('.')[1]; + if (payloadB64) { + const payload = JSON.parse(Buffer.from(payloadB64, 'base64').toString('ascii')); + return payload.exp * 1000; + } + } +} +exports.IdTokenClient = IdTokenClient; +//# sourceMappingURL=idtokenclient.js.map \ No newline at end of file diff --git a/node_modules/google-auth-library/build/src/auth/jwtaccess.d.ts b/node_modules/google-auth-library/build/src/auth/jwtaccess.d.ts new file mode 100644 index 0000000..1d2d69b --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/jwtaccess.d.ts @@ -0,0 +1,47 @@ +/// +import * as stream from 'stream'; +import { JWTInput } from './credentials'; +import { Headers } from './oauth2client'; +export interface Claims { + [index: string]: string; +} +export declare class JWTAccess { + email?: string | null; + key?: string | null; + keyId?: string | null; + projectId?: string; + private cache; + /** + * JWTAccess service account credentials. + * + * Create a new access token by using the credential to create a new JWT token + * that's recognized as the access token. + * + * @param email the service account email address. + * @param key the private key that will be used to sign the token. + * @param keyId the ID of the private key used to sign the token. + */ + constructor(email?: string | null, key?: string | null, keyId?: string | null); + /** + * Get a non-expired access token, after refreshing if necessary. + * + * @param url The URI being authorized. + * @param additionalClaims An object with a set of additional claims to + * include in the payload. + * @returns An object that includes the authorization header. + */ + getRequestHeaders(url: string, additionalClaims?: Claims): Headers; + /** + * Create a JWTAccess credentials instance using the given input options. + * @param json The input object. + */ + fromJSON(json: JWTInput): void; + /** + * Create a JWTAccess credentials instance using the given input stream. + * @param inputStream The input stream. + * @param callback Optional callback. + */ + fromStream(inputStream: stream.Readable): Promise; + fromStream(inputStream: stream.Readable, callback: (err?: Error) => void): void; + private fromStreamAsync; +} diff --git a/node_modules/google-auth-library/build/src/auth/jwtaccess.js b/node_modules/google-auth-library/build/src/auth/jwtaccess.js new file mode 100644 index 0000000..039dbb4 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/jwtaccess.js @@ -0,0 +1,135 @@ +"use strict"; +// Copyright 2015 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +const jws = require("jws"); +const LRU = require("lru-cache"); +const DEFAULT_HEADER = { + alg: 'RS256', + typ: 'JWT', +}; +class JWTAccess { + /** + * JWTAccess service account credentials. + * + * Create a new access token by using the credential to create a new JWT token + * that's recognized as the access token. + * + * @param email the service account email address. + * @param key the private key that will be used to sign the token. + * @param keyId the ID of the private key used to sign the token. + */ + constructor(email, key, keyId) { + this.cache = new LRU({ max: 500, maxAge: 60 * 60 * 1000 }); + this.email = email; + this.key = key; + this.keyId = keyId; + } + /** + * Get a non-expired access token, after refreshing if necessary. + * + * @param url The URI being authorized. + * @param additionalClaims An object with a set of additional claims to + * include in the payload. + * @returns An object that includes the authorization header. + */ + getRequestHeaders(url, additionalClaims) { + const cachedToken = this.cache.get(url); + if (cachedToken) { + return cachedToken; + } + const iat = Math.floor(new Date().getTime() / 1000); + const exp = iat + 3600; // 3600 seconds = 1 hour + // The payload used for signed JWT headers has: + // iss == sub == + // aud == + const defaultClaims = { + iss: this.email, + sub: this.email, + aud: url, + exp, + iat, + }; + // if additionalClaims are provided, ensure they do not collide with + // other required claims. + if (additionalClaims) { + for (const claim in defaultClaims) { + if (additionalClaims[claim]) { + throw new Error(`The '${claim}' property is not allowed when passing additionalClaims. This claim is included in the JWT by default.`); + } + } + } + const header = this.keyId + ? { ...DEFAULT_HEADER, kid: this.keyId } + : DEFAULT_HEADER; + const payload = Object.assign(defaultClaims, additionalClaims); + // Sign the jwt and add it to the cache + const signedJWT = jws.sign({ header, payload, secret: this.key }); + const headers = { Authorization: `Bearer ${signedJWT}` }; + this.cache.set(url, headers); + return headers; + } + /** + * Create a JWTAccess credentials instance using the given input options. + * @param json The input object. + */ + fromJSON(json) { + if (!json) { + throw new Error('Must pass in a JSON object containing the service account auth settings.'); + } + if (!json.client_email) { + throw new Error('The incoming JSON object does not contain a client_email field'); + } + if (!json.private_key) { + throw new Error('The incoming JSON object does not contain a private_key field'); + } + // Extract the relevant information from the json key file. + this.email = json.client_email; + this.key = json.private_key; + this.keyId = json.private_key_id; + this.projectId = json.project_id; + } + fromStream(inputStream, callback) { + if (callback) { + this.fromStreamAsync(inputStream).then(r => callback(), callback); + } + else { + return this.fromStreamAsync(inputStream); + } + } + fromStreamAsync(inputStream) { + return new Promise((resolve, reject) => { + if (!inputStream) { + reject(new Error('Must pass in a stream containing the service account auth settings.')); + } + let s = ''; + inputStream + .setEncoding('utf8') + .on('data', chunk => (s += chunk)) + .on('error', reject) + .on('end', () => { + try { + const data = JSON.parse(s); + this.fromJSON(data); + resolve(); + } + catch (err) { + reject(err); + } + }); + }); + } +} +exports.JWTAccess = JWTAccess; +//# sourceMappingURL=jwtaccess.js.map \ No newline at end of file diff --git a/node_modules/google-auth-library/build/src/auth/jwtclient.d.ts b/node_modules/google-auth-library/build/src/auth/jwtclient.d.ts new file mode 100644 index 0000000..d8f35c7 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/jwtclient.d.ts @@ -0,0 +1,103 @@ +/// +import { GoogleToken } from 'gtoken'; +import * as stream from 'stream'; +import { CredentialBody, Credentials, JWTInput } from './credentials'; +import { IdTokenProvider } from './idtokenclient'; +import { GetTokenResponse, OAuth2Client, RefreshOptions, RequestMetadataResponse } from './oauth2client'; +export interface JWTOptions extends RefreshOptions { + email?: string; + keyFile?: string; + key?: string; + keyId?: string; + scopes?: string | string[]; + subject?: string; + additionalClaims?: {}; +} +export declare class JWT extends OAuth2Client implements IdTokenProvider { + email?: string; + keyFile?: string; + key?: string; + keyId?: string; + scopes?: string | string[]; + scope?: string; + subject?: string; + gtoken?: GoogleToken; + additionalClaims?: {}; + private access?; + /** + * JWT service account credentials. + * + * Retrieve access token using gtoken. + * + * @param email service account email address. + * @param keyFile path to private key file. + * @param key value of key + * @param scopes list of requested scopes or a single scope. + * @param subject impersonated account's email address. + * @param key_id the ID of the key + */ + constructor(options: JWTOptions); + constructor(email?: string, keyFile?: string, key?: string, scopes?: string | string[], subject?: string, keyId?: string); + /** + * Creates a copy of the credential with the specified scopes. + * @param scopes List of requested scopes or a single scope. + * @return The cloned instance. + */ + createScoped(scopes?: string | string[]): JWT; + /** + * Obtains the metadata to be sent with the request. + * + * @param url the URI being authorized. + */ + protected getRequestMetadataAsync(url?: string | null): Promise; + /** + * Fetches an ID token. + * @param targetAudience the audience for the fetched ID token. + */ + fetchIdToken(targetAudience: string): Promise; + /** + * Determine if there are currently scopes available. + */ + private hasScopes; + /** + * Get the initial access token using gToken. + * @param callback Optional callback. + * @returns Promise that resolves with credentials + */ + authorize(): Promise; + authorize(callback: (err: Error | null, result?: Credentials) => void): void; + private authorizeAsync; + /** + * Refreshes the access token. + * @param refreshToken ignored + * @private + */ + protected refreshTokenNoCache(refreshToken?: string | null): Promise; + /** + * Create a gToken if it doesn't already exist. + */ + private createGToken; + /** + * Create a JWT credentials instance using the given input options. + * @param json The input object. + */ + fromJSON(json: JWTInput): void; + /** + * Create a JWT credentials instance using the given input stream. + * @param inputStream The input stream. + * @param callback Optional callback. + */ + fromStream(inputStream: stream.Readable): Promise; + fromStream(inputStream: stream.Readable, callback: (err?: Error | null) => void): void; + private fromStreamAsync; + /** + * Creates a JWT credentials instance using an API Key for authentication. + * @param apiKey The API Key in string form. + */ + fromAPIKey(apiKey: string): void; + /** + * Using the key or keyFile on the JWT client, obtain an object that contains + * the key and the client email. + */ + getCredentials(): Promise; +} diff --git a/node_modules/google-auth-library/build/src/auth/jwtclient.js b/node_modules/google-auth-library/build/src/auth/jwtclient.js new file mode 100644 index 0000000..e174317 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/jwtclient.js @@ -0,0 +1,251 @@ +"use strict"; +// Copyright 2013 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +const gtoken_1 = require("gtoken"); +const jwtaccess_1 = require("./jwtaccess"); +const oauth2client_1 = require("./oauth2client"); +class JWT extends oauth2client_1.OAuth2Client { + constructor(optionsOrEmail, keyFile, key, scopes, subject, keyId) { + const opts = optionsOrEmail && typeof optionsOrEmail === 'object' + ? optionsOrEmail + : { email: optionsOrEmail, keyFile, key, keyId, scopes, subject }; + super({ + eagerRefreshThresholdMillis: opts.eagerRefreshThresholdMillis, + forceRefreshOnFailure: opts.forceRefreshOnFailure, + }); + this.email = opts.email; + this.keyFile = opts.keyFile; + this.key = opts.key; + this.keyId = opts.keyId; + this.scopes = opts.scopes; + this.subject = opts.subject; + this.additionalClaims = opts.additionalClaims; + this.credentials = { refresh_token: 'jwt-placeholder', expiry_date: 1 }; + } + /** + * Creates a copy of the credential with the specified scopes. + * @param scopes List of requested scopes or a single scope. + * @return The cloned instance. + */ + createScoped(scopes) { + return new JWT({ + email: this.email, + keyFile: this.keyFile, + key: this.key, + keyId: this.keyId, + scopes, + subject: this.subject, + additionalClaims: this.additionalClaims, + }); + } + /** + * Obtains the metadata to be sent with the request. + * + * @param url the URI being authorized. + */ + async getRequestMetadataAsync(url) { + if (!this.apiKey && !this.hasScopes() && url) { + if (this.additionalClaims && + this.additionalClaims.target_audience) { + const { tokens } = await this.refreshToken(); + return { + headers: this.addSharedMetadataHeaders({ + Authorization: `Bearer ${tokens.id_token}`, + }), + }; + } + else { + // no scopes have been set, but a uri has been provided. Use JWTAccess + // credentials. + if (!this.access) { + this.access = new jwtaccess_1.JWTAccess(this.email, this.key, this.keyId); + } + const headers = await this.access.getRequestHeaders(url, this.additionalClaims); + return { headers: this.addSharedMetadataHeaders(headers) }; + } + } + else { + return super.getRequestMetadataAsync(url); + } + } + /** + * Fetches an ID token. + * @param targetAudience the audience for the fetched ID token. + */ + async fetchIdToken(targetAudience) { + // Create a new gToken for fetching an ID token + const gtoken = new gtoken_1.GoogleToken({ + iss: this.email, + sub: this.subject, + scope: this.scopes, + keyFile: this.keyFile, + key: this.key, + additionalClaims: { target_audience: targetAudience }, + }); + await gtoken.getToken({ + forceRefresh: true, + }); + if (!gtoken.idToken) { + throw new Error('Unknown error: Failed to fetch ID token'); + } + return gtoken.idToken; + } + /** + * Determine if there are currently scopes available. + */ + hasScopes() { + if (!this.scopes) { + return false; + } + // For arrays, check the array length. + if (this.scopes instanceof Array) { + return this.scopes.length > 0; + } + // For others, convert to a string and check the length. + return String(this.scopes).length > 0; + } + authorize(callback) { + if (callback) { + this.authorizeAsync().then(r => callback(null, r), callback); + } + else { + return this.authorizeAsync(); + } + } + async authorizeAsync() { + const result = await this.refreshToken(); + if (!result) { + throw new Error('No result returned'); + } + this.credentials = result.tokens; + this.credentials.refresh_token = 'jwt-placeholder'; + this.key = this.gtoken.key; + this.email = this.gtoken.iss; + return result.tokens; + } + /** + * Refreshes the access token. + * @param refreshToken ignored + * @private + */ + async refreshTokenNoCache(refreshToken) { + const gtoken = this.createGToken(); + const token = await gtoken.getToken({ + forceRefresh: this.isTokenExpiring(), + }); + const tokens = { + access_token: token.access_token, + token_type: 'Bearer', + expiry_date: gtoken.expiresAt, + id_token: gtoken.idToken, + }; + this.emit('tokens', tokens); + return { res: null, tokens }; + } + /** + * Create a gToken if it doesn't already exist. + */ + createGToken() { + if (!this.gtoken) { + this.gtoken = new gtoken_1.GoogleToken({ + iss: this.email, + sub: this.subject, + scope: this.scopes, + keyFile: this.keyFile, + key: this.key, + additionalClaims: this.additionalClaims, + }); + } + return this.gtoken; + } + /** + * Create a JWT credentials instance using the given input options. + * @param json The input object. + */ + fromJSON(json) { + if (!json) { + throw new Error('Must pass in a JSON object containing the service account auth settings.'); + } + if (!json.client_email) { + throw new Error('The incoming JSON object does not contain a client_email field'); + } + if (!json.private_key) { + throw new Error('The incoming JSON object does not contain a private_key field'); + } + // Extract the relevant information from the json key file. + this.email = json.client_email; + this.key = json.private_key; + this.keyId = json.private_key_id; + this.projectId = json.project_id; + this.quotaProjectId = json.quota_project_id; + } + fromStream(inputStream, callback) { + if (callback) { + this.fromStreamAsync(inputStream).then(r => callback(), callback); + } + else { + return this.fromStreamAsync(inputStream); + } + } + fromStreamAsync(inputStream) { + return new Promise((resolve, reject) => { + if (!inputStream) { + throw new Error('Must pass in a stream containing the service account auth settings.'); + } + let s = ''; + inputStream + .setEncoding('utf8') + .on('error', reject) + .on('data', chunk => (s += chunk)) + .on('end', () => { + try { + const data = JSON.parse(s); + this.fromJSON(data); + resolve(); + } + catch (e) { + reject(e); + } + }); + }); + } + /** + * Creates a JWT credentials instance using an API Key for authentication. + * @param apiKey The API Key in string form. + */ + fromAPIKey(apiKey) { + if (typeof apiKey !== 'string') { + throw new Error('Must provide an API Key string.'); + } + this.apiKey = apiKey; + } + /** + * Using the key or keyFile on the JWT client, obtain an object that contains + * the key and the client email. + */ + async getCredentials() { + if (this.key) { + return { private_key: this.key, client_email: this.email }; + } + else if (this.keyFile) { + const gtoken = this.createGToken(); + const creds = await gtoken.getCredentials(this.keyFile); + return { private_key: creds.privateKey, client_email: creds.clientEmail }; + } + throw new Error('A key or a keyFile must be provided to getCredentials.'); + } +} +exports.JWT = JWT; +//# sourceMappingURL=jwtclient.js.map \ No newline at end of file diff --git a/node_modules/google-auth-library/build/src/auth/loginticket.d.ts b/node_modules/google-auth-library/build/src/auth/loginticket.d.ts new file mode 100644 index 0000000..f727c56 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/loginticket.d.ts @@ -0,0 +1,135 @@ +export declare class LoginTicket { + private envelope?; + private payload?; + /** + * Create a simple class to extract user ID from an ID Token + * + * @param {string} env Envelope of the jwt + * @param {TokenPayload} pay Payload of the jwt + * @constructor + */ + constructor(env?: string, pay?: TokenPayload); + getEnvelope(): string | undefined; + getPayload(): TokenPayload | undefined; + /** + * Create a simple class to extract user ID from an ID Token + * + * @return The user ID + */ + getUserId(): string | null; + /** + * Returns attributes from the login ticket. This can contain + * various information about the user session. + * + * @return The envelope and payload + */ + getAttributes(): { + envelope: string | undefined; + payload: TokenPayload | undefined; + }; +} +export interface TokenPayload { + /** + * The Issuer Identifier for the Issuer of the response. Always + * https://accounts.google.com or accounts.google.com for Google ID tokens. + */ + iss: string; + /** + * Access token hash. Provides validation that the access token is tied to the + * identity token. If the ID token is issued with an access token in the + * server flow, this is always included. This can be used as an alternate + * mechanism to protect against cross-site request forgery attacks, but if you + * follow Step 1 and Step 3 it is not necessary to verify the access token. + */ + at_hash?: string; + /** + * True if the user's e-mail address has been verified; otherwise false. + */ + email_verified?: boolean; + /** + * An identifier for the user, unique among all Google accounts and never + * reused. A Google account can have multiple emails at different points in + * time, but the sub value is never changed. Use sub within your application + * as the unique-identifier key for the user. + */ + sub: string; + /** + * The client_id of the authorized presenter. This claim is only needed when + * the party requesting the ID token is not the same as the audience of the ID + * token. This may be the case at Google for hybrid apps where a web + * application and Android app have a different client_id but share the same + * project. + */ + azp?: string; + /** + * The user's email address. This may not be unique and is not suitable for + * use as a primary key. Provided only if your scope included the string + * "email". + */ + email?: string; + /** + * The URL of the user's profile page. Might be provided when: + * - The request scope included the string "profile" + * - The ID token is returned from a token refresh + * - When profile claims are present, you can use them to update your app's + * user records. Note that this claim is never guaranteed to be present. + */ + profile?: string; + /** + * The URL of the user's profile picture. Might be provided when: + * - The request scope included the string "profile" + * - The ID token is returned from a token refresh + * - When picture claims are present, you can use them to update your app's + * user records. Note that this claim is never guaranteed to be present. + */ + picture?: string; + /** + * The user's full name, in a displayable form. Might be provided when: + * - The request scope included the string "profile" + * - The ID token is returned from a token refresh + * - When name claims are present, you can use them to update your app's user + * records. Note that this claim is never guaranteed to be present. + */ + name?: string; + /** + * The user's given name, in a displayable form. Might be provided when: + * - The request scope included the string "profile" + * - The ID token is returned from a token refresh + * - When name claims are present, you can use them to update your app's user + * records. Note that this claim is never guaranteed to be present. + */ + given_name?: string; + /** + * The user's family name, in a displayable form. Might be provided when: + * - The request scope included the string "profile" + * - The ID token is returned from a token refresh + * - When name claims are present, you can use them to update your app's user + * records. Note that this claim is never guaranteed to be present. + */ + family_name?: string; + /** + * Identifies the audience that this ID token is intended for. It must be one + * of the OAuth 2.0 client IDs of your application. + */ + aud: string; + /** + * The time the ID token was issued, represented in Unix time (integer + * seconds). + */ + iat: number; + /** + * The time the ID token expires, represented in Unix time (integer seconds). + */ + exp: number; + /** + * The value of the nonce supplied by your app in the authentication request. + * You should enforce protection against replay attacks by ensuring it is + * presented only once. + */ + nonce?: string; + /** + * The hosted G Suite domain of the user. Provided only if the user belongs to + * a hosted domain. + */ + hd?: string; +} diff --git a/node_modules/google-auth-library/build/src/auth/loginticket.js b/node_modules/google-auth-library/build/src/auth/loginticket.js new file mode 100644 index 0000000..637d95b --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/loginticket.js @@ -0,0 +1,57 @@ +"use strict"; +// Copyright 2014 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +class LoginTicket { + /** + * Create a simple class to extract user ID from an ID Token + * + * @param {string} env Envelope of the jwt + * @param {TokenPayload} pay Payload of the jwt + * @constructor + */ + constructor(env, pay) { + this.envelope = env; + this.payload = pay; + } + getEnvelope() { + return this.envelope; + } + getPayload() { + return this.payload; + } + /** + * Create a simple class to extract user ID from an ID Token + * + * @return The user ID + */ + getUserId() { + const payload = this.getPayload(); + if (payload && payload.sub) { + return payload.sub; + } + return null; + } + /** + * Returns attributes from the login ticket. This can contain + * various information about the user session. + * + * @return The envelope and payload + */ + getAttributes() { + return { envelope: this.getEnvelope(), payload: this.getPayload() }; + } +} +exports.LoginTicket = LoginTicket; +//# sourceMappingURL=loginticket.js.map \ No newline at end of file diff --git a/node_modules/google-auth-library/build/src/auth/oauth2client.d.ts b/node_modules/google-auth-library/build/src/auth/oauth2client.d.ts new file mode 100644 index 0000000..b9f90b3 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/oauth2client.d.ts @@ -0,0 +1,502 @@ +import { GaxiosError, GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios'; +import { JwkCertificate } from '../crypto/crypto'; +import { BodyResponseCallback } from '../transporters'; +import { AuthClient } from './authclient'; +import { Credentials } from './credentials'; +import { LoginTicket } from './loginticket'; +/** + * The results from the `generateCodeVerifierAsync` method. To learn more, + * See the sample: + * https://github.com/googleapis/google-auth-library-nodejs/blob/master/samples/oauth2-codeVerifier.js + */ +export interface CodeVerifierResults { + /** + * The code verifier that will be used when calling `getToken` to obtain a new + * access token. + */ + codeVerifier: string; + /** + * The code_challenge that should be sent with the `generateAuthUrl` call + * to obtain a verifiable authentication url. + */ + codeChallenge?: string; +} +export interface Certificates { + [index: string]: string | JwkCertificate; +} +export interface PublicKeys { + [index: string]: string; +} +export interface Headers { + [index: string]: string; +} +export declare enum CodeChallengeMethod { + Plain = "plain", + S256 = "S256" +} +export declare enum CertificateFormat { + PEM = "PEM", + JWK = "JWK" +} +export interface GetTokenOptions { + code: string; + codeVerifier?: string; + /** + * The client ID for your application. The value passed into the constructor + * will be used if not provided. Must match any client_id option passed to + * a corresponding call to generateAuthUrl. + */ + client_id?: string; + /** + * Determines where the API server redirects the user after the user + * completes the authorization flow. The value passed into the constructor + * will be used if not provided. Must match any redirect_uri option passed to + * a corresponding call to generateAuthUrl. + */ + redirect_uri?: string; +} +export interface TokenInfo { + /** + * The application that is the intended user of the access token. + */ + aud: string; + /** + * This value lets you correlate profile information from multiple Google + * APIs. It is only present in the response if you included the profile scope + * in your request in step 1. The field value is an immutable identifier for + * the logged-in user that can be used to create and manage user sessions in + * your application. The identifier is the same regardless of which client ID + * is used to retrieve it. This enables multiple applications in the same + * organization to correlate profile information. + */ + user_id?: string; + /** + * An array of scopes that the user granted access to. + */ + scopes: string[]; + /** + * The datetime when the token becomes invalid. + */ + expiry_date: number; + /** + * An identifier for the user, unique among all Google accounts and never + * reused. A Google account can have multiple emails at different points in + * time, but the sub value is never changed. Use sub within your application + * as the unique-identifier key for the user. + */ + sub?: string; + /** + * The client_id of the authorized presenter. This claim is only needed when + * the party requesting the ID token is not the same as the audience of the ID + * token. This may be the case at Google for hybrid apps where a web + * application and Android app have a different client_id but share the same + * project. + */ + azp?: string; + /** + * Indicates whether your application can refresh access tokens + * when the user is not present at the browser. Valid parameter values are + * 'online', which is the default value, and 'offline'. Set the value to + * 'offline' if your application needs to refresh access tokens when the user + * is not present at the browser. This value instructs the Google + * authorization server to return a refresh token and an access token the + * first time that your application exchanges an authorization code for + * tokens. + */ + access_type?: string; + /** + * The user's email address. This value may not be unique to this user and + * is not suitable for use as a primary key. Provided only if your scope + * included the email scope value. + */ + email?: string; + /** + * True if the user's e-mail address has been verified; otherwise false. + */ + email_verified?: boolean; +} +export interface GenerateAuthUrlOpts { + /** + * Recommended. Indicates whether your application can refresh access tokens + * when the user is not present at the browser. Valid parameter values are + * 'online', which is the default value, and 'offline'. Set the value to + * 'offline' if your application needs to refresh access tokens when the user + * is not present at the browser. This value instructs the Google + * authorization server to return a refresh token and an access token the + * first time that your application exchanges an authorization code for + * tokens. + */ + access_type?: string; + /** + * The hd (hosted domain) parameter streamlines the login process for G Suite + * hosted accounts. By including the domain of the G Suite user (for example, + * mycollege.edu), you can indicate that the account selection UI should be + * optimized for accounts at that domain. To optimize for G Suite accounts + * generally instead of just one domain, use an asterisk: hd=*. + * Don't rely on this UI optimization to control who can access your app, + * as client-side requests can be modified. Be sure to validate that the + * returned ID token has an hd claim value that matches what you expect + * (e.g. mycolledge.edu). Unlike the request parameter, the ID token claim is + * contained within a security token from Google, so the value can be trusted. + */ + hd?: string; + /** + * The 'response_type' will always be set to 'CODE'. + */ + response_type?: string; + /** + * The client ID for your application. The value passed into the constructor + * will be used if not provided. You can find this value in the API Console. + */ + client_id?: string; + /** + * Determines where the API server redirects the user after the user + * completes the authorization flow. The value must exactly match one of the + * 'redirect_uri' values listed for your project in the API Console. Note that + * the http or https scheme, case, and trailing slash ('/') must all match. + * The value passed into the constructor will be used if not provided. + */ + redirect_uri?: string; + /** + * Required. A space-delimited list of scopes that identify the resources that + * your application could access on the user's behalf. These values inform the + * consent screen that Google displays to the user. Scopes enable your + * application to only request access to the resources that it needs while + * also enabling users to control the amount of access that they grant to your + * application. Thus, there is an inverse relationship between the number of + * scopes requested and the likelihood of obtaining user consent. The + * OAuth 2.0 API Scopes document provides a full list of scopes that you might + * use to access Google APIs. We recommend that your application request + * access to authorization scopes in context whenever possible. By requesting + * access to user data in context, via incremental authorization, you help + * users to more easily understand why your application needs the access it is + * requesting. + */ + scope?: string[] | string; + /** + * Recommended. Specifies any string value that your application uses to + * maintain state between your authorization request and the authorization + * server's response. The server returns the exact value that you send as a + * name=value pair in the hash (#) fragment of the 'redirect_uri' after the + * user consents to or denies your application's access request. You can use + * this parameter for several purposes, such as directing the user to the + * correct resource in your application, sending nonces, and mitigating + * cross-site request forgery. Since your redirect_uri can be guessed, using a + * state value can increase your assurance that an incoming connection is the + * result of an authentication request. If you generate a random string or + * encode the hash of a cookie or another value that captures the client's + * state, you can validate the response to additionally ensure that the + * request and response originated in the same browser, providing protection + * against attacks such as cross-site request forgery. See the OpenID Connect + * documentation for an example of how to create and confirm a state token. + */ + state?: string; + /** + * Optional. Enables applications to use incremental authorization to request + * access to additional scopes in context. If you set this parameter's value + * to true and the authorization request is granted, then the new access token + * will also cover any scopes to which the user previously granted the + * application access. See the incremental authorization section for examples. + */ + include_granted_scopes?: boolean; + /** + * Optional. If your application knows which user is trying to authenticate, + * it can use this parameter to provide a hint to the Google Authentication + * Server. The server uses the hint to simplify the login flow either by + * prefilling the email field in the sign-in form or by selecting the + * appropriate multi-login session. Set the parameter value to an email + * address or sub identifier, which is equivalent to the user's Google ID. + */ + login_hint?: string; + /** + * Optional. A space-delimited, case-sensitive list of prompts to present the + * user. If you don't specify this parameter, the user will be prompted only + * the first time your app requests access. Possible values are: + * + * 'none' - Donot display any authentication or consent screens. Must not be + * specified with other values. + * 'consent' - Prompt the user for consent. + * 'select_account' - Prompt the user to select an account. + */ + prompt?: string; + /** + * Recommended. Specifies what method was used to encode a 'code_verifier' + * that will be used during authorization code exchange. This parameter must + * be used with the 'code_challenge' parameter. The value of the + * 'code_challenge_method' defaults to "plain" if not present in the request + * that includes a 'code_challenge'. The only supported values for this + * parameter are "S256" or "plain". + */ + code_challenge_method?: CodeChallengeMethod; + /** + * Recommended. Specifies an encoded 'code_verifier' that will be used as a + * server-side challenge during authorization code exchange. This parameter + * must be used with the 'code_challenge' parameter described above. + */ + code_challenge?: string; +} +export interface GetTokenCallback { + (err: GaxiosError | null, token?: Credentials | null, res?: GaxiosResponse | null): void; +} +export interface GetTokenResponse { + tokens: Credentials; + res: GaxiosResponse | null; +} +export interface GetAccessTokenCallback { + (err: GaxiosError | null, token?: string | null, res?: GaxiosResponse | null): void; +} +export interface GetAccessTokenResponse { + token?: string | null; + res?: GaxiosResponse | null; +} +export interface RefreshAccessTokenCallback { + (err: GaxiosError | null, credentials?: Credentials | null, res?: GaxiosResponse | null): void; +} +export interface RefreshAccessTokenResponse { + credentials: Credentials; + res: GaxiosResponse | null; +} +export interface RequestMetadataResponse { + headers: Headers; + res?: GaxiosResponse | null; +} +export interface RequestMetadataCallback { + (err: GaxiosError | null, headers?: Headers, res?: GaxiosResponse | null): void; +} +export interface GetFederatedSignonCertsCallback { + (err: GaxiosError | null, certs?: Certificates, response?: GaxiosResponse | null): void; +} +export interface FederatedSignonCertsResponse { + certs: Certificates; + format: CertificateFormat; + res?: GaxiosResponse | null; +} +export interface GetIapPublicKeysCallback { + (err: GaxiosError | null, pubkeys?: PublicKeys, response?: GaxiosResponse | null): void; +} +export interface IapPublicKeysResponse { + pubkeys: PublicKeys; + res?: GaxiosResponse | null; +} +export interface RevokeCredentialsResult { + success: boolean; +} +export interface VerifyIdTokenOptions { + idToken: string; + audience: string | string[]; + maxExpiry?: number; +} +export interface OAuth2ClientOptions extends RefreshOptions { + clientId?: string; + clientSecret?: string; + redirectUri?: string; +} +export interface RefreshOptions { + eagerRefreshThresholdMillis?: number; + forceRefreshOnFailure?: boolean; +} +export declare class OAuth2Client extends AuthClient { + private redirectUri?; + private certificateCache; + private certificateExpiry; + private certificateCacheFormat; + protected refreshTokenPromises: Map>; + _clientId?: string; + _clientSecret?: string; + apiKey?: string; + projectId?: string; + eagerRefreshThresholdMillis: number; + forceRefreshOnFailure: boolean; + /** + * Handles OAuth2 flow for Google APIs. + * + * @param clientId The authentication client ID. + * @param clientSecret The authentication client secret. + * @param redirectUri The URI to redirect to after completing the auth + * request. + * @param opts optional options for overriding the given parameters. + * @constructor + */ + constructor(options?: OAuth2ClientOptions); + constructor(clientId?: string, clientSecret?: string, redirectUri?: string); + protected static readonly GOOGLE_TOKEN_INFO_URL = "https://oauth2.googleapis.com/tokeninfo"; + /** + * The base URL for auth endpoints. + */ + private static readonly GOOGLE_OAUTH2_AUTH_BASE_URL_; + /** + * The base endpoint for token retrieval. + */ + private static readonly GOOGLE_OAUTH2_TOKEN_URL_; + /** + * The base endpoint to revoke tokens. + */ + private static readonly GOOGLE_OAUTH2_REVOKE_URL_; + /** + * Google Sign on certificates in PEM format. + */ + private static readonly GOOGLE_OAUTH2_FEDERATED_SIGNON_PEM_CERTS_URL_; + /** + * Google Sign on certificates in JWK format. + */ + private static readonly GOOGLE_OAUTH2_FEDERATED_SIGNON_JWK_CERTS_URL_; + /** + * Google Sign on certificates in JWK format. + */ + private static readonly GOOGLE_OAUTH2_IAP_PUBLIC_KEY_URL_; + /** + * Clock skew - five minutes in seconds + */ + private static readonly CLOCK_SKEW_SECS_; + /** + * Max Token Lifetime is one day in seconds + */ + private static readonly MAX_TOKEN_LIFETIME_SECS_; + /** + * The allowed oauth token issuers. + */ + private static readonly ISSUERS_; + /** + * Generates URL for consent page landing. + * @param opts Options. + * @return URL to consent page. + */ + generateAuthUrl(opts?: GenerateAuthUrlOpts): string; + generateCodeVerifier(): void; + /** + * Convenience method to automatically generate a code_verifier, and it's + * resulting SHA256. If used, this must be paired with a S256 + * code_challenge_method. + * + * For a full example see: + * https://github.com/googleapis/google-auth-library-nodejs/blob/master/samples/oauth2-codeVerifier.js + */ + generateCodeVerifierAsync(): Promise; + /** + * Gets the access token for the given code. + * @param code The authorization code. + * @param callback Optional callback fn. + */ + getToken(code: string): Promise; + getToken(options: GetTokenOptions): Promise; + getToken(code: string, callback: GetTokenCallback): void; + getToken(options: GetTokenOptions, callback: GetTokenCallback): void; + private getTokenAsync; + /** + * Refreshes the access token. + * @param refresh_token Existing refresh token. + * @private + */ + protected refreshToken(refreshToken?: string | null): Promise; + protected refreshTokenNoCache(refreshToken?: string | null): Promise; + /** + * Retrieves the access token using refresh token + * + * @deprecated use getRequestHeaders instead. + * @param callback callback + */ + refreshAccessToken(): Promise; + refreshAccessToken(callback: RefreshAccessTokenCallback): void; + private refreshAccessTokenAsync; + /** + * Get a non-expired access token, after refreshing if necessary + * + * @param callback Callback to call with the access token + */ + getAccessToken(): Promise; + getAccessToken(callback: GetAccessTokenCallback): void; + private getAccessTokenAsync; + /** + * The main authentication interface. It takes an optional url which when + * present is the endpoint being accessed, and returns a Promise which + * resolves with authorization header fields. + * + * In OAuth2Client, the result has the form: + * { Authorization: 'Bearer ' } + * @param url The optional url being authorized + */ + getRequestHeaders(url?: string): Promise; + protected getRequestMetadataAsync(url?: string | null): Promise; + /** + * Generates an URL to revoke the given token. + * @param token The existing token to be revoked. + */ + static getRevokeTokenUrl(token: string): string; + /** + * Revokes the access given to token. + * @param token The existing token to be revoked. + * @param callback Optional callback fn. + */ + revokeToken(token: string): GaxiosPromise; + revokeToken(token: string, callback: BodyResponseCallback): void; + /** + * Revokes access token and clears the credentials object + * @param callback callback + */ + revokeCredentials(): GaxiosPromise; + revokeCredentials(callback: BodyResponseCallback): void; + private revokeCredentialsAsync; + /** + * Provides a request implementation with OAuth 2.0 flow. If credentials have + * a refresh_token, in cases of HTTP 401 and 403 responses, it automatically + * asks for a new access token and replays the unsuccessful request. + * @param opts Request options. + * @param callback callback. + * @return Request object + */ + request(opts: GaxiosOptions): GaxiosPromise; + request(opts: GaxiosOptions, callback: BodyResponseCallback): void; + protected requestAsync(opts: GaxiosOptions, retry?: boolean): Promise>; + /** + * Verify id token is token by checking the certs and audience + * @param options that contains all options. + * @param callback Callback supplying GoogleLogin if successful + */ + verifyIdToken(options: VerifyIdTokenOptions): Promise; + verifyIdToken(options: VerifyIdTokenOptions, callback: (err: Error | null, login?: LoginTicket) => void): void; + private verifyIdTokenAsync; + /** + * Obtains information about the provisioned access token. Especially useful + * if you want to check the scopes that were provisioned to a given token. + * + * @param accessToken Required. The Access Token for which you want to get + * user info. + */ + getTokenInfo(accessToken: string): Promise; + /** + * Gets federated sign-on certificates to use for verifying identity tokens. + * Returns certs as array structure, where keys are key ids, and values + * are certificates in either PEM or JWK format. + * @param callback Callback supplying the certificates + */ + getFederatedSignonCerts(): Promise; + getFederatedSignonCerts(callback: GetFederatedSignonCertsCallback): void; + getFederatedSignonCertsAsync(): Promise; + /** + * Gets federated sign-on certificates to use for verifying identity tokens. + * Returns certs as array structure, where keys are key ids, and values + * are certificates in either PEM or JWK format. + * @param callback Callback supplying the certificates + */ + getIapPublicKeys(): Promise; + getIapPublicKeys(callback: GetIapPublicKeysCallback): void; + getIapPublicKeysAsync(): Promise; + verifySignedJwtWithCerts(): void; + /** + * Verify the id token is signed with the correct certificate + * and is from the correct audience. + * @param jwt The jwt to verify (The ID Token in this case). + * @param certs The array of certs to test the jwt against. + * @param requiredAudience The audience to test the jwt against. + * @param issuers The allowed issuers of the jwt (Optional). + * @param maxExpiry The max expiry the certificate can be (Optional). + * @return Returns a promise resolving to LoginTicket on verification. + */ + verifySignedJwtWithCertsAsync(jwt: string, certs: Certificates | PublicKeys, requiredAudience: string | string[], issuers?: string[], maxExpiry?: number): Promise; + /** + * Returns true if a token is expired or will expire within + * eagerRefreshThresholdMillismilliseconds. + * If there is no expiry time, assumes the token is not expired or expiring. + */ + protected isTokenExpiring(): boolean; +} diff --git a/node_modules/google-auth-library/build/src/auth/oauth2client.js b/node_modules/google-auth-library/build/src/auth/oauth2client.js new file mode 100644 index 0000000..bf0d062 --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/oauth2client.js @@ -0,0 +1,674 @@ +"use strict"; +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +const querystring = require("querystring"); +const stream = require("stream"); +const formatEcdsa = require("ecdsa-sig-formatter"); +const crypto_1 = require("../crypto/crypto"); +const authclient_1 = require("./authclient"); +const loginticket_1 = require("./loginticket"); +var CodeChallengeMethod; +(function (CodeChallengeMethod) { + CodeChallengeMethod["Plain"] = "plain"; + CodeChallengeMethod["S256"] = "S256"; +})(CodeChallengeMethod = exports.CodeChallengeMethod || (exports.CodeChallengeMethod = {})); +var CertificateFormat; +(function (CertificateFormat) { + CertificateFormat["PEM"] = "PEM"; + CertificateFormat["JWK"] = "JWK"; +})(CertificateFormat = exports.CertificateFormat || (exports.CertificateFormat = {})); +class OAuth2Client extends authclient_1.AuthClient { + constructor(optionsOrClientId, clientSecret, redirectUri) { + super(); + this.certificateCache = {}; + this.certificateExpiry = null; + this.certificateCacheFormat = CertificateFormat.PEM; + this.refreshTokenPromises = new Map(); + const opts = optionsOrClientId && typeof optionsOrClientId === 'object' + ? optionsOrClientId + : { clientId: optionsOrClientId, clientSecret, redirectUri }; + this._clientId = opts.clientId; + this._clientSecret = opts.clientSecret; + this.redirectUri = opts.redirectUri; + this.eagerRefreshThresholdMillis = + opts.eagerRefreshThresholdMillis || 5 * 60 * 1000; + this.forceRefreshOnFailure = !!opts.forceRefreshOnFailure; + } + /** + * Generates URL for consent page landing. + * @param opts Options. + * @return URL to consent page. + */ + generateAuthUrl(opts = {}) { + if (opts.code_challenge_method && !opts.code_challenge) { + throw new Error('If a code_challenge_method is provided, code_challenge must be included.'); + } + opts.response_type = opts.response_type || 'code'; + opts.client_id = opts.client_id || this._clientId; + opts.redirect_uri = opts.redirect_uri || this.redirectUri; + // Allow scopes to be passed either as array or a string + if (opts.scope instanceof Array) { + opts.scope = opts.scope.join(' '); + } + const rootUrl = OAuth2Client.GOOGLE_OAUTH2_AUTH_BASE_URL_; + return rootUrl + '?' + querystring.stringify(opts); + } + generateCodeVerifier() { + // To make the code compatible with browser SubtleCrypto we need to make + // this method async. + throw new Error('generateCodeVerifier is removed, please use generateCodeVerifierAsync instead.'); + } + /** + * Convenience method to automatically generate a code_verifier, and it's + * resulting SHA256. If used, this must be paired with a S256 + * code_challenge_method. + * + * For a full example see: + * https://github.com/googleapis/google-auth-library-nodejs/blob/master/samples/oauth2-codeVerifier.js + */ + async generateCodeVerifierAsync() { + // base64 encoding uses 6 bits per character, and we want to generate128 + // characters. 6*128/8 = 96. + const crypto = crypto_1.createCrypto(); + const randomString = crypto.randomBytesBase64(96); + // The valid characters in the code_verifier are [A-Z]/[a-z]/[0-9]/ + // "-"/"."/"_"/"~". Base64 encoded strings are pretty close, so we're just + // swapping out a few chars. + const codeVerifier = randomString + .replace(/\+/g, '~') + .replace(/=/g, '_') + .replace(/\//g, '-'); + // Generate the base64 encoded SHA256 + const unencodedCodeChallenge = await crypto.sha256DigestBase64(codeVerifier); + // We need to use base64UrlEncoding instead of standard base64 + const codeChallenge = unencodedCodeChallenge + .split('=')[0] + .replace(/\+/g, '-') + .replace(/\//g, '_'); + return { codeVerifier, codeChallenge }; + } + getToken(codeOrOptions, callback) { + const options = typeof codeOrOptions === 'string' ? { code: codeOrOptions } : codeOrOptions; + if (callback) { + this.getTokenAsync(options).then(r => callback(null, r.tokens, r.res), e => callback(e, null, e.response)); + } + else { + return this.getTokenAsync(options); + } + } + async getTokenAsync(options) { + const url = OAuth2Client.GOOGLE_OAUTH2_TOKEN_URL_; + const values = { + code: options.code, + client_id: options.client_id || this._clientId, + client_secret: this._clientSecret, + redirect_uri: options.redirect_uri || this.redirectUri, + grant_type: 'authorization_code', + code_verifier: options.codeVerifier, + }; + const res = await this.transporter.request({ + method: 'POST', + url, + data: querystring.stringify(values), + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + }); + const tokens = res.data; + if (res.data && res.data.expires_in) { + tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000; + delete tokens.expires_in; + } + this.emit('tokens', tokens); + return { tokens, res }; + } + /** + * Refreshes the access token. + * @param refresh_token Existing refresh token. + * @private + */ + async refreshToken(refreshToken) { + if (!refreshToken) { + return this.refreshTokenNoCache(refreshToken); + } + // If a request to refresh using the same token has started, + // return the same promise. + if (this.refreshTokenPromises.has(refreshToken)) { + return this.refreshTokenPromises.get(refreshToken); + } + const p = this.refreshTokenNoCache(refreshToken).then(r => { + this.refreshTokenPromises.delete(refreshToken); + return r; + }, e => { + this.refreshTokenPromises.delete(refreshToken); + throw e; + }); + this.refreshTokenPromises.set(refreshToken, p); + return p; + } + async refreshTokenNoCache(refreshToken) { + if (!refreshToken) { + throw new Error('No refresh token is set.'); + } + const url = OAuth2Client.GOOGLE_OAUTH2_TOKEN_URL_; + const data = { + refresh_token: refreshToken, + client_id: this._clientId, + client_secret: this._clientSecret, + grant_type: 'refresh_token', + }; + // request for new token + const res = await this.transporter.request({ + method: 'POST', + url, + data: querystring.stringify(data), + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + }); + const tokens = res.data; + // TODO: de-duplicate this code from a few spots + if (res.data && res.data.expires_in) { + tokens.expiry_date = new Date().getTime() + res.data.expires_in * 1000; + delete tokens.expires_in; + } + this.emit('tokens', tokens); + return { tokens, res }; + } + refreshAccessToken(callback) { + if (callback) { + this.refreshAccessTokenAsync().then(r => callback(null, r.credentials, r.res), callback); + } + else { + return this.refreshAccessTokenAsync(); + } + } + async refreshAccessTokenAsync() { + const r = await this.refreshToken(this.credentials.refresh_token); + const tokens = r.tokens; + tokens.refresh_token = this.credentials.refresh_token; + this.credentials = tokens; + return { credentials: this.credentials, res: r.res }; + } + getAccessToken(callback) { + if (callback) { + this.getAccessTokenAsync().then(r => callback(null, r.token, r.res), callback); + } + else { + return this.getAccessTokenAsync(); + } + } + async getAccessTokenAsync() { + const shouldRefresh = !this.credentials.access_token || this.isTokenExpiring(); + if (shouldRefresh) { + if (!this.credentials.refresh_token) { + throw new Error('No refresh token is set.'); + } + const r = await this.refreshAccessTokenAsync(); + if (!r.credentials || (r.credentials && !r.credentials.access_token)) { + throw new Error('Could not refresh access token.'); + } + return { token: r.credentials.access_token, res: r.res }; + } + else { + return { token: this.credentials.access_token }; + } + } + /** + * The main authentication interface. It takes an optional url which when + * present is the endpoint being accessed, and returns a Promise which + * resolves with authorization header fields. + * + * In OAuth2Client, the result has the form: + * { Authorization: 'Bearer ' } + * @param url The optional url being authorized + */ + async getRequestHeaders(url) { + const headers = (await this.getRequestMetadataAsync(url)).headers; + return headers; + } + async getRequestMetadataAsync(url) { + const thisCreds = this.credentials; + if (!thisCreds.access_token && !thisCreds.refresh_token && !this.apiKey) { + throw new Error('No access, refresh token or API key is set.'); + } + if (thisCreds.access_token && !this.isTokenExpiring()) { + thisCreds.token_type = thisCreds.token_type || 'Bearer'; + const headers = { + Authorization: thisCreds.token_type + ' ' + thisCreds.access_token, + }; + return { headers }; + } + if (this.apiKey) { + return { headers: { 'X-Goog-Api-Key': this.apiKey } }; + } + let r = null; + let tokens = null; + try { + r = await this.refreshToken(thisCreds.refresh_token); + tokens = r.tokens; + } + catch (err) { + const e = err; + if (e.response && + (e.response.status === 403 || e.response.status === 404)) { + e.message = `Could not refresh access token: ${e.message}`; + } + throw e; + } + const credentials = this.credentials; + credentials.token_type = credentials.token_type || 'Bearer'; + tokens.refresh_token = credentials.refresh_token; + this.credentials = tokens; + const headers = { + Authorization: credentials.token_type + ' ' + tokens.access_token, + }; + return { headers: this.addSharedMetadataHeaders(headers), res: r.res }; + } + /** + * Generates an URL to revoke the given token. + * @param token The existing token to be revoked. + */ + static getRevokeTokenUrl(token) { + const parameters = querystring.stringify({ token }); + return `${OAuth2Client.GOOGLE_OAUTH2_REVOKE_URL_}?${parameters}`; + } + revokeToken(token, callback) { + const opts = { + url: OAuth2Client.getRevokeTokenUrl(token), + method: 'POST', + }; + if (callback) { + this.transporter + .request(opts) + .then(r => callback(null, r), callback); + } + else { + return this.transporter.request(opts); + } + } + revokeCredentials(callback) { + if (callback) { + this.revokeCredentialsAsync().then(res => callback(null, res), callback); + } + else { + return this.revokeCredentialsAsync(); + } + } + async revokeCredentialsAsync() { + const token = this.credentials.access_token; + this.credentials = {}; + if (token) { + return this.revokeToken(token); + } + else { + throw new Error('No access token to revoke.'); + } + } + request(opts, callback) { + if (callback) { + this.requestAsync(opts).then(r => callback(null, r), e => { + return callback(e, e.response); + }); + } + else { + return this.requestAsync(opts); + } + } + async requestAsync(opts, retry = false) { + let r2; + try { + const r = await this.getRequestMetadataAsync(opts.url); + opts.headers = opts.headers || {}; + if (r.headers && r.headers['x-goog-user-project']) { + opts.headers['x-goog-user-project'] = r.headers['x-goog-user-project']; + } + if (r.headers && r.headers.Authorization) { + opts.headers.Authorization = r.headers.Authorization; + } + if (this.apiKey) { + opts.headers['X-Goog-Api-Key'] = this.apiKey; + } + r2 = await this.transporter.request(opts); + } + catch (e) { + const res = e.response; + if (res) { + const statusCode = res.status; + // Retry the request for metadata if the following criteria are true: + // - We haven't already retried. It only makes sense to retry once. + // - The response was a 401 or a 403 + // - The request didn't send a readableStream + // - An access_token and refresh_token were available, but either no + // expiry_date was available or the forceRefreshOnFailure flag is set. + // The absent expiry_date case can happen when developers stash the + // access_token and refresh_token for later use, but the access_token + // fails on the first try because it's expired. Some developers may + // choose to enable forceRefreshOnFailure to mitigate time-related + // errors. + const mayRequireRefresh = this.credentials && + this.credentials.access_token && + this.credentials.refresh_token && + (!this.credentials.expiry_date || this.forceRefreshOnFailure); + const isReadableStream = res.config.data instanceof stream.Readable; + const isAuthErr = statusCode === 401 || statusCode === 403; + if (!retry && isAuthErr && !isReadableStream && mayRequireRefresh) { + await this.refreshAccessTokenAsync(); + return this.requestAsync(opts, true); + } + } + throw e; + } + return r2; + } + verifyIdToken(options, callback) { + // This function used to accept two arguments instead of an options object. + // Check the types to help users upgrade with less pain. + // This check can be removed after a 2.0 release. + if (callback && typeof callback !== 'function') { + throw new Error('This method accepts an options object as the first parameter, which includes the idToken, audience, and maxExpiry.'); + } + if (callback) { + this.verifyIdTokenAsync(options).then(r => callback(null, r), callback); + } + else { + return this.verifyIdTokenAsync(options); + } + } + async verifyIdTokenAsync(options) { + if (!options.idToken) { + throw new Error('The verifyIdToken method requires an ID Token'); + } + const response = await this.getFederatedSignonCertsAsync(); + const login = await this.verifySignedJwtWithCertsAsync(options.idToken, response.certs, options.audience, OAuth2Client.ISSUERS_, options.maxExpiry); + return login; + } + /** + * Obtains information about the provisioned access token. Especially useful + * if you want to check the scopes that were provisioned to a given token. + * + * @param accessToken Required. The Access Token for which you want to get + * user info. + */ + async getTokenInfo(accessToken) { + const { data } = await this.transporter.request({ + method: 'GET', + url: OAuth2Client.GOOGLE_TOKEN_INFO_URL, + params: { access_token: accessToken }, + }); + const info = Object.assign({ + expiry_date: new Date().getTime() + data.expires_in * 1000, + scopes: data.scope.split(' '), + }, data); + delete info.expires_in; + delete info.scope; + return info; + } + getFederatedSignonCerts(callback) { + if (callback) { + this.getFederatedSignonCertsAsync().then(r => callback(null, r.certs, r.res), callback); + } + else { + return this.getFederatedSignonCertsAsync(); + } + } + async getFederatedSignonCertsAsync() { + const nowTime = new Date().getTime(); + const format = crypto_1.hasBrowserCrypto() + ? CertificateFormat.JWK + : CertificateFormat.PEM; + if (this.certificateExpiry && + nowTime < this.certificateExpiry.getTime() && + this.certificateCacheFormat === format) { + return { certs: this.certificateCache, format }; + } + let res; + let url; + switch (format) { + case CertificateFormat.PEM: + url = OAuth2Client.GOOGLE_OAUTH2_FEDERATED_SIGNON_PEM_CERTS_URL_; + break; + case CertificateFormat.JWK: + url = OAuth2Client.GOOGLE_OAUTH2_FEDERATED_SIGNON_JWK_CERTS_URL_; + break; + default: + throw new Error(`Unsupported certificate format ${format}`); + } + try { + res = await this.transporter.request({ url }); + } + catch (e) { + e.message = `Failed to retrieve verification certificates: ${e.message}`; + throw e; + } + const cacheControl = res ? res.headers['cache-control'] : undefined; + let cacheAge = -1; + if (cacheControl) { + const pattern = new RegExp('max-age=([0-9]*)'); + const regexResult = pattern.exec(cacheControl); + if (regexResult && regexResult.length === 2) { + // Cache results with max-age (in seconds) + cacheAge = Number(regexResult[1]) * 1000; // milliseconds + } + } + let certificates = {}; + switch (format) { + case CertificateFormat.PEM: + certificates = res.data; + break; + case CertificateFormat.JWK: + for (const key of res.data.keys) { + certificates[key.kid] = key; + } + break; + default: + throw new Error(`Unsupported certificate format ${format}`); + } + const now = new Date(); + this.certificateExpiry = + cacheAge === -1 ? null : new Date(now.getTime() + cacheAge); + this.certificateCache = certificates; + this.certificateCacheFormat = format; + return { certs: certificates, format, res }; + } + getIapPublicKeys(callback) { + if (callback) { + this.getIapPublicKeysAsync().then(r => callback(null, r.pubkeys, r.res), callback); + } + else { + return this.getIapPublicKeysAsync(); + } + } + async getIapPublicKeysAsync() { + const nowTime = new Date().getTime(); + let res; + const url = OAuth2Client.GOOGLE_OAUTH2_IAP_PUBLIC_KEY_URL_; + try { + res = await this.transporter.request({ url }); + } + catch (e) { + e.message = `Failed to retrieve verification certificates: ${e.message}`; + throw e; + } + return { pubkeys: res.data, res }; + } + verifySignedJwtWithCerts() { + // To make the code compatible with browser SubtleCrypto we need to make + // this method async. + throw new Error('verifySignedJwtWithCerts is removed, please use verifySignedJwtWithCertsAsync instead.'); + } + /** + * Verify the id token is signed with the correct certificate + * and is from the correct audience. + * @param jwt The jwt to verify (The ID Token in this case). + * @param certs The array of certs to test the jwt against. + * @param requiredAudience The audience to test the jwt against. + * @param issuers The allowed issuers of the jwt (Optional). + * @param maxExpiry The max expiry the certificate can be (Optional). + * @return Returns a promise resolving to LoginTicket on verification. + */ + async verifySignedJwtWithCertsAsync(jwt, certs, requiredAudience, issuers, maxExpiry) { + const crypto = crypto_1.createCrypto(); + if (!maxExpiry) { + maxExpiry = OAuth2Client.MAX_TOKEN_LIFETIME_SECS_; + } + const segments = jwt.split('.'); + if (segments.length !== 3) { + throw new Error('Wrong number of segments in token: ' + jwt); + } + const signed = segments[0] + '.' + segments[1]; + let signature = segments[2]; + let envelope; + let payload; + try { + envelope = JSON.parse(crypto.decodeBase64StringUtf8(segments[0])); + } + catch (err) { + err.message = `Can't parse token envelope: ${segments[0]}': ${err.message}`; + throw err; + } + if (!envelope) { + throw new Error("Can't parse token envelope: " + segments[0]); + } + try { + payload = JSON.parse(crypto.decodeBase64StringUtf8(segments[1])); + } + catch (err) { + err.message = `Can't parse token payload '${segments[0]}`; + throw err; + } + if (!payload) { + throw new Error("Can't parse token payload: " + segments[1]); + } + if (!Object.prototype.hasOwnProperty.call(certs, envelope.kid)) { + // If this is not present, then there's no reason to attempt verification + throw new Error('No pem found for envelope: ' + JSON.stringify(envelope)); + } + const cert = certs[envelope.kid]; + if (envelope.alg === 'ES256') { + signature = formatEcdsa.joseToDer(signature, 'ES256').toString('base64'); + } + const verified = await crypto.verify(cert, signed, signature); + if (!verified) { + throw new Error('Invalid token signature: ' + jwt); + } + if (!payload.iat) { + throw new Error('No issue time in token: ' + JSON.stringify(payload)); + } + if (!payload.exp) { + throw new Error('No expiration time in token: ' + JSON.stringify(payload)); + } + const iat = Number(payload.iat); + if (isNaN(iat)) + throw new Error('iat field using invalid format'); + const exp = Number(payload.exp); + if (isNaN(exp)) + throw new Error('exp field using invalid format'); + const now = new Date().getTime() / 1000; + if (exp >= now + maxExpiry) { + throw new Error('Expiration time too far in future: ' + JSON.stringify(payload)); + } + const earliest = iat - OAuth2Client.CLOCK_SKEW_SECS_; + const latest = exp + OAuth2Client.CLOCK_SKEW_SECS_; + if (now < earliest) { + throw new Error('Token used too early, ' + + now + + ' < ' + + earliest + + ': ' + + JSON.stringify(payload)); + } + if (now > latest) { + throw new Error('Token used too late, ' + + now + + ' > ' + + latest + + ': ' + + JSON.stringify(payload)); + } + if (issuers && issuers.indexOf(payload.iss) < 0) { + throw new Error('Invalid issuer, expected one of [' + + issuers + + '], but got ' + + payload.iss); + } + // Check the audience matches if we have one + if (typeof requiredAudience !== 'undefined' && requiredAudience !== null) { + const aud = payload.aud; + let audVerified = false; + // If the requiredAudience is an array, check if it contains token + // audience + if (requiredAudience.constructor === Array) { + audVerified = requiredAudience.indexOf(aud) > -1; + } + else { + audVerified = aud === requiredAudience; + } + if (!audVerified) { + throw new Error('Wrong recipient, payload audience != requiredAudience'); + } + } + return new loginticket_1.LoginTicket(envelope, payload); + } + /** + * Returns true if a token is expired or will expire within + * eagerRefreshThresholdMillismilliseconds. + * If there is no expiry time, assumes the token is not expired or expiring. + */ + isTokenExpiring() { + const expiryDate = this.credentials.expiry_date; + return expiryDate + ? expiryDate <= new Date().getTime() + this.eagerRefreshThresholdMillis + : false; + } +} +exports.OAuth2Client = OAuth2Client; +OAuth2Client.GOOGLE_TOKEN_INFO_URL = 'https://oauth2.googleapis.com/tokeninfo'; +/** + * The base URL for auth endpoints. + */ +OAuth2Client.GOOGLE_OAUTH2_AUTH_BASE_URL_ = 'https://accounts.google.com/o/oauth2/v2/auth'; +/** + * The base endpoint for token retrieval. + */ +OAuth2Client.GOOGLE_OAUTH2_TOKEN_URL_ = 'https://oauth2.googleapis.com/token'; +/** + * The base endpoint to revoke tokens. + */ +OAuth2Client.GOOGLE_OAUTH2_REVOKE_URL_ = 'https://oauth2.googleapis.com/revoke'; +/** + * Google Sign on certificates in PEM format. + */ +OAuth2Client.GOOGLE_OAUTH2_FEDERATED_SIGNON_PEM_CERTS_URL_ = 'https://www.googleapis.com/oauth2/v1/certs'; +/** + * Google Sign on certificates in JWK format. + */ +OAuth2Client.GOOGLE_OAUTH2_FEDERATED_SIGNON_JWK_CERTS_URL_ = 'https://www.googleapis.com/oauth2/v3/certs'; +/** + * Google Sign on certificates in JWK format. + */ +OAuth2Client.GOOGLE_OAUTH2_IAP_PUBLIC_KEY_URL_ = 'https://www.gstatic.com/iap/verify/public_key'; +/** + * Clock skew - five minutes in seconds + */ +OAuth2Client.CLOCK_SKEW_SECS_ = 300; +/** + * Max Token Lifetime is one day in seconds + */ +OAuth2Client.MAX_TOKEN_LIFETIME_SECS_ = 86400; +/** + * The allowed oauth token issuers. + */ +OAuth2Client.ISSUERS_ = [ + 'accounts.google.com', + 'https://accounts.google.com', +]; +//# sourceMappingURL=oauth2client.js.map \ No newline at end of file diff --git a/node_modules/google-auth-library/build/src/auth/refreshclient.d.ts b/node_modules/google-auth-library/build/src/auth/refreshclient.d.ts new file mode 100644 index 0000000..65a588d --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/refreshclient.d.ts @@ -0,0 +1,43 @@ +/// +import * as stream from 'stream'; +import { JWTInput } from './credentials'; +import { GetTokenResponse, OAuth2Client, RefreshOptions } from './oauth2client'; +export interface UserRefreshClientOptions extends RefreshOptions { + clientId?: string; + clientSecret?: string; + refreshToken?: string; +} +export declare class UserRefreshClient extends OAuth2Client { + _refreshToken?: string | null; + /** + * User Refresh Token credentials. + * + * @param clientId The authentication client ID. + * @param clientSecret The authentication client secret. + * @param refreshToken The authentication refresh token. + */ + constructor(clientId?: string, clientSecret?: string, refreshToken?: string); + constructor(options: UserRefreshClientOptions); + constructor(clientId?: string, clientSecret?: string, refreshToken?: string); + /** + * Refreshes the access token. + * @param refreshToken An ignored refreshToken.. + * @param callback Optional callback. + */ + protected refreshTokenNoCache(refreshToken?: string | null): Promise; + /** + * Create a UserRefreshClient credentials instance using the given input + * options. + * @param json The input object. + */ + fromJSON(json: JWTInput): void; + /** + * Create a UserRefreshClient credentials instance using the given input + * stream. + * @param inputStream The input stream. + * @param callback Optional callback. + */ + fromStream(inputStream: stream.Readable): Promise; + fromStream(inputStream: stream.Readable, callback: (err?: Error) => void): void; + private fromStreamAsync; +} diff --git a/node_modules/google-auth-library/build/src/auth/refreshclient.js b/node_modules/google-auth-library/build/src/auth/refreshclient.js new file mode 100644 index 0000000..aff6d0b --- /dev/null +++ b/node_modules/google-auth-library/build/src/auth/refreshclient.js @@ -0,0 +1,104 @@ +"use strict"; +// Copyright 2015 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +const oauth2client_1 = require("./oauth2client"); +class UserRefreshClient extends oauth2client_1.OAuth2Client { + constructor(optionsOrClientId, clientSecret, refreshToken, eagerRefreshThresholdMillis, forceRefreshOnFailure) { + const opts = optionsOrClientId && typeof optionsOrClientId === 'object' + ? optionsOrClientId + : { + clientId: optionsOrClientId, + clientSecret, + refreshToken, + eagerRefreshThresholdMillis, + forceRefreshOnFailure, + }; + super({ + clientId: opts.clientId, + clientSecret: opts.clientSecret, + eagerRefreshThresholdMillis: opts.eagerRefreshThresholdMillis, + forceRefreshOnFailure: opts.forceRefreshOnFailure, + }); + this._refreshToken = opts.refreshToken; + this.credentials.refresh_token = opts.refreshToken; + } + /** + * Refreshes the access token. + * @param refreshToken An ignored refreshToken.. + * @param callback Optional callback. + */ + async refreshTokenNoCache(refreshToken) { + return super.refreshTokenNoCache(this._refreshToken); + } + /** + * Create a UserRefreshClient credentials instance using the given input + * options. + * @param json The input object. + */ + fromJSON(json) { + if (!json) { + throw new Error('Must pass in a JSON object containing the user refresh token'); + } + if (json.type !== 'authorized_user') { + throw new Error('The incoming JSON object does not have the "authorized_user" type'); + } + if (!json.client_id) { + throw new Error('The incoming JSON object does not contain a client_id field'); + } + if (!json.client_secret) { + throw new Error('The incoming JSON object does not contain a client_secret field'); + } + if (!json.refresh_token) { + throw new Error('The incoming JSON object does not contain a refresh_token field'); + } + this._clientId = json.client_id; + this._clientSecret = json.client_secret; + this._refreshToken = json.refresh_token; + this.credentials.refresh_token = json.refresh_token; + this.quotaProjectId = json.quota_project_id; + } + fromStream(inputStream, callback) { + if (callback) { + this.fromStreamAsync(inputStream).then(r => callback(), callback); + } + else { + return this.fromStreamAsync(inputStream); + } + } + async fromStreamAsync(inputStream) { + return new Promise((resolve, reject) => { + if (!inputStream) { + return reject(new Error('Must pass in a stream containing the user refresh token.')); + } + let s = ''; + inputStream + .setEncoding('utf8') + .on('error', reject) + .on('data', chunk => (s += chunk)) + .on('end', () => { + try { + const data = JSON.parse(s); + this.fromJSON(data); + return resolve(); + } + catch (err) { + return reject(err); + } + }); + }); + } +} +exports.UserRefreshClient = UserRefreshClient; +//# sourceMappingURL=refreshclient.js.map \ No newline at end of file diff --git a/node_modules/google-auth-library/build/src/crypto/browser/crypto.d.ts b/node_modules/google-auth-library/build/src/crypto/browser/crypto.d.ts new file mode 100644 index 0000000..f7949a0 --- /dev/null +++ b/node_modules/google-auth-library/build/src/crypto/browser/crypto.d.ts @@ -0,0 +1,11 @@ +import { Crypto, JwkCertificate } from '../crypto'; +export declare class BrowserCrypto implements Crypto { + constructor(); + sha256DigestBase64(str: string): Promise; + randomBytesBase64(count: number): string; + private static padBase64; + verify(pubkey: JwkCertificate, data: string, signature: string): Promise; + sign(privateKey: JwkCertificate, data: string): Promise; + decodeBase64StringUtf8(base64: string): string; + encodeBase64StringUtf8(text: string): string; +} diff --git a/node_modules/google-auth-library/build/src/crypto/browser/crypto.js b/node_modules/google-auth-library/build/src/crypto/browser/crypto.js new file mode 100644 index 0000000..6002d7b --- /dev/null +++ b/node_modules/google-auth-library/build/src/crypto/browser/crypto.js @@ -0,0 +1,99 @@ +"use strict"; +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +/* global window */ +Object.defineProperty(exports, "__esModule", { value: true }); +// This file implements crypto functions we need using in-browser +// SubtleCrypto interface `window.crypto.subtle`. +const base64js = require("base64-js"); +// Not all browsers support `TextEncoder`. The following `require` will +// provide a fast UTF8-only replacement for those browsers that don't support +// text encoding natively. +// eslint-disable-next-line node/no-unsupported-features/node-builtins +if (typeof process === 'undefined' && typeof TextEncoder === 'undefined') { + require('fast-text-encoding'); +} +class BrowserCrypto { + constructor() { + if (typeof window === 'undefined' || + window.crypto === undefined || + window.crypto.subtle === undefined) { + throw new Error("SubtleCrypto not found. Make sure it's an https:// website."); + } + } + async sha256DigestBase64(str) { + // SubtleCrypto digest() method is async, so we must make + // this method async as well. + // To calculate SHA256 digest using SubtleCrypto, we first + // need to convert an input string to an ArrayBuffer: + // eslint-disable-next-line node/no-unsupported-features/node-builtins + const inputBuffer = new TextEncoder().encode(str); + // Result is ArrayBuffer as well. + const outputBuffer = await window.crypto.subtle.digest('SHA-256', inputBuffer); + return base64js.fromByteArray(new Uint8Array(outputBuffer)); + } + randomBytesBase64(count) { + const array = new Uint8Array(count); + window.crypto.getRandomValues(array); + return base64js.fromByteArray(array); + } + static padBase64(base64) { + // base64js requires padding, so let's add some '=' + while (base64.length % 4 !== 0) { + base64 += '='; + } + return base64; + } + async verify(pubkey, data, signature) { + const algo = { + name: 'RSASSA-PKCS1-v1_5', + hash: { name: 'SHA-256' }, + }; + // eslint-disable-next-line node/no-unsupported-features/node-builtins + const dataArray = new TextEncoder().encode(data); + const signatureArray = base64js.toByteArray(BrowserCrypto.padBase64(signature)); + const cryptoKey = await window.crypto.subtle.importKey('jwk', pubkey, algo, true, ['verify']); + // SubtleCrypto's verify method is async so we must make + // this method async as well. + const result = await window.crypto.subtle.verify(algo, cryptoKey, signatureArray, dataArray); + return result; + } + async sign(privateKey, data) { + const algo = { + name: 'RSASSA-PKCS1-v1_5', + hash: { name: 'SHA-256' }, + }; + // eslint-disable-next-line node/no-unsupported-features/node-builtins + const dataArray = new TextEncoder().encode(data); + const cryptoKey = await window.crypto.subtle.importKey('jwk', privateKey, algo, true, ['sign']); + // SubtleCrypto's sign method is async so we must make + // this method async as well. + const result = await window.crypto.subtle.sign(algo, cryptoKey, dataArray); + return base64js.fromByteArray(new Uint8Array(result)); + } + decodeBase64StringUtf8(base64) { + const uint8array = base64js.toByteArray(BrowserCrypto.padBase64(base64)); + // eslint-disable-next-line node/no-unsupported-features/node-builtins + const result = new TextDecoder().decode(uint8array); + return result; + } + encodeBase64StringUtf8(text) { + // eslint-disable-next-line node/no-unsupported-features/node-builtins + const uint8array = new TextEncoder().encode(text); + const result = base64js.fromByteArray(uint8array); + return result; + } +} +exports.BrowserCrypto = BrowserCrypto; +//# sourceMappingURL=crypto.js.map \ No newline at end of file diff --git a/node_modules/google-auth-library/build/src/crypto/crypto.d.ts b/node_modules/google-auth-library/build/src/crypto/crypto.d.ts new file mode 100644 index 0000000..84adc06 --- /dev/null +++ b/node_modules/google-auth-library/build/src/crypto/crypto.d.ts @@ -0,0 +1,23 @@ +/// +export interface JwkCertificate { + kty: string; + alg: string; + use?: string; + kid: string; + n: string; + e: string; +} +export interface CryptoSigner { + update(data: string): void; + sign(key: string, outputFormat: string): string; +} +export interface Crypto { + sha256DigestBase64(str: string): Promise; + randomBytesBase64(n: number): string; + verify(pubkey: string | JwkCertificate, data: string | Buffer, signature: string): Promise; + sign(privateKey: string | JwkCertificate, data: string | Buffer): Promise; + decodeBase64StringUtf8(base64: string): string; + encodeBase64StringUtf8(text: string): string; +} +export declare function createCrypto(): Crypto; +export declare function hasBrowserCrypto(): boolean; diff --git a/node_modules/google-auth-library/build/src/crypto/crypto.js b/node_modules/google-auth-library/build/src/crypto/crypto.js new file mode 100644 index 0000000..06b88b3 --- /dev/null +++ b/node_modules/google-auth-library/build/src/crypto/crypto.js @@ -0,0 +1,32 @@ +"use strict"; +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +/* global window */ +Object.defineProperty(exports, "__esModule", { value: true }); +const crypto_1 = require("./browser/crypto"); +const crypto_2 = require("./node/crypto"); +function createCrypto() { + if (hasBrowserCrypto()) { + return new crypto_1.BrowserCrypto(); + } + return new crypto_2.NodeCrypto(); +} +exports.createCrypto = createCrypto; +function hasBrowserCrypto() { + return (typeof window !== 'undefined' && + typeof window.crypto !== 'undefined' && + typeof window.crypto.subtle !== 'undefined'); +} +exports.hasBrowserCrypto = hasBrowserCrypto; +//# sourceMappingURL=crypto.js.map \ No newline at end of file diff --git a/node_modules/google-auth-library/build/src/crypto/node/crypto.d.ts b/node_modules/google-auth-library/build/src/crypto/node/crypto.d.ts new file mode 100644 index 0000000..e04cb20 --- /dev/null +++ b/node_modules/google-auth-library/build/src/crypto/node/crypto.d.ts @@ -0,0 +1,10 @@ +/// +import { Crypto } from '../crypto'; +export declare class NodeCrypto implements Crypto { + sha256DigestBase64(str: string): Promise; + randomBytesBase64(count: number): string; + verify(pubkey: string, data: string | Buffer, signature: string): Promise; + sign(privateKey: string, data: string | Buffer): Promise; + decodeBase64StringUtf8(base64: string): string; + encodeBase64StringUtf8(text: string): string; +} diff --git a/node_modules/google-auth-library/build/src/crypto/node/crypto.js b/node_modules/google-auth-library/build/src/crypto/node/crypto.js new file mode 100644 index 0000000..4a06165 --- /dev/null +++ b/node_modules/google-auth-library/build/src/crypto/node/crypto.js @@ -0,0 +1,44 @@ +"use strict"; +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +const crypto = require("crypto"); +class NodeCrypto { + async sha256DigestBase64(str) { + return crypto.createHash('sha256').update(str).digest('base64'); + } + randomBytesBase64(count) { + return crypto.randomBytes(count).toString('base64'); + } + async verify(pubkey, data, signature) { + const verifier = crypto.createVerify('sha256'); + verifier.update(data); + verifier.end(); + return verifier.verify(pubkey, signature, 'base64'); + } + async sign(privateKey, data) { + const signer = crypto.createSign('RSA-SHA256'); + signer.update(data); + signer.end(); + return signer.sign(privateKey, 'base64'); + } + decodeBase64StringUtf8(base64) { + return Buffer.from(base64, 'base64').toString('utf-8'); + } + encodeBase64StringUtf8(text) { + return Buffer.from(text, 'utf-8').toString('base64'); + } +} +exports.NodeCrypto = NodeCrypto; +//# sourceMappingURL=crypto.js.map \ No newline at end of file diff --git a/node_modules/google-auth-library/build/src/index.d.ts b/node_modules/google-auth-library/build/src/index.d.ts new file mode 100644 index 0000000..30ea45e --- /dev/null +++ b/node_modules/google-auth-library/build/src/index.d.ts @@ -0,0 +1,15 @@ +import { GoogleAuth } from './auth/googleauth'; +export { Compute, ComputeOptions } from './auth/computeclient'; +export { CredentialBody, CredentialRequest, Credentials, JWTInput, } from './auth/credentials'; +export { GCPEnv } from './auth/envDetect'; +export { GoogleAuthOptions, ProjectIdCallback } from './auth/googleauth'; +export { IAMAuth, RequestMetadata } from './auth/iam'; +export { IdTokenClient, IdTokenProvider } from './auth/idtokenclient'; +export { Claims, JWTAccess } from './auth/jwtaccess'; +export { JWT, JWTOptions } from './auth/jwtclient'; +export { Certificates, CodeChallengeMethod, CodeVerifierResults, GenerateAuthUrlOpts, GetTokenOptions, OAuth2Client, OAuth2ClientOptions, RefreshOptions, TokenInfo, VerifyIdTokenOptions, } from './auth/oauth2client'; +export { LoginTicket, TokenPayload } from './auth/loginticket'; +export { UserRefreshClient, UserRefreshClientOptions, } from './auth/refreshclient'; +export { DefaultTransporter } from './transporters'; +declare const auth: GoogleAuth; +export { auth, GoogleAuth }; diff --git a/node_modules/google-auth-library/build/src/index.js b/node_modules/google-auth-library/build/src/index.js new file mode 100644 index 0000000..328790e --- /dev/null +++ b/node_modules/google-auth-library/build/src/index.js @@ -0,0 +1,41 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +const googleauth_1 = require("./auth/googleauth"); +exports.GoogleAuth = googleauth_1.GoogleAuth; +var computeclient_1 = require("./auth/computeclient"); +exports.Compute = computeclient_1.Compute; +var envDetect_1 = require("./auth/envDetect"); +exports.GCPEnv = envDetect_1.GCPEnv; +var iam_1 = require("./auth/iam"); +exports.IAMAuth = iam_1.IAMAuth; +var idtokenclient_1 = require("./auth/idtokenclient"); +exports.IdTokenClient = idtokenclient_1.IdTokenClient; +var jwtaccess_1 = require("./auth/jwtaccess"); +exports.JWTAccess = jwtaccess_1.JWTAccess; +var jwtclient_1 = require("./auth/jwtclient"); +exports.JWT = jwtclient_1.JWT; +var oauth2client_1 = require("./auth/oauth2client"); +exports.CodeChallengeMethod = oauth2client_1.CodeChallengeMethod; +exports.OAuth2Client = oauth2client_1.OAuth2Client; +var loginticket_1 = require("./auth/loginticket"); +exports.LoginTicket = loginticket_1.LoginTicket; +var refreshclient_1 = require("./auth/refreshclient"); +exports.UserRefreshClient = refreshclient_1.UserRefreshClient; +var transporters_1 = require("./transporters"); +exports.DefaultTransporter = transporters_1.DefaultTransporter; +const auth = new googleauth_1.GoogleAuth(); +exports.auth = auth; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/google-auth-library/build/src/messages.d.ts b/node_modules/google-auth-library/build/src/messages.d.ts new file mode 100644 index 0000000..9de99bc --- /dev/null +++ b/node_modules/google-auth-library/build/src/messages.d.ts @@ -0,0 +1,11 @@ +export declare enum WarningTypes { + WARNING = "Warning", + DEPRECATION = "DeprecationWarning" +} +export declare function warn(warning: Warning): void; +export interface Warning { + code: string; + type: WarningTypes; + message: string; + warned?: boolean; +} diff --git a/node_modules/google-auth-library/build/src/messages.js b/node_modules/google-auth-library/build/src/messages.js new file mode 100644 index 0000000..abf215e --- /dev/null +++ b/node_modules/google-auth-library/build/src/messages.js @@ -0,0 +1,39 @@ +"use strict"; +// Copyright 2018 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +var WarningTypes; +(function (WarningTypes) { + WarningTypes["WARNING"] = "Warning"; + WarningTypes["DEPRECATION"] = "DeprecationWarning"; +})(WarningTypes = exports.WarningTypes || (exports.WarningTypes = {})); +function warn(warning) { + // Only show a given warning once + if (warning.warned) { + return; + } + warning.warned = true; + if (typeof process !== 'undefined' && process.emitWarning) { + // @types/node doesn't recognize the emitWarning syntax which + // accepts a config object, so `as any` it is + // https://nodejs.org/docs/latest-v8.x/api/process.html#process_process_emitwarning_warning_options + // tslint:disable-next-line no-any + process.emitWarning(warning.message, warning); + } + else { + console.warn(warning.message); + } +} +exports.warn = warn; +//# sourceMappingURL=messages.js.map \ No newline at end of file diff --git a/node_modules/google-auth-library/build/src/options.d.ts b/node_modules/google-auth-library/build/src/options.d.ts new file mode 100644 index 0000000..ede9689 --- /dev/null +++ b/node_modules/google-auth-library/build/src/options.d.ts @@ -0,0 +1 @@ +export declare function validate(options: any): void; diff --git a/node_modules/google-auth-library/build/src/options.js b/node_modules/google-auth-library/build/src/options.js new file mode 100644 index 0000000..b561d12 --- /dev/null +++ b/node_modules/google-auth-library/build/src/options.js @@ -0,0 +1,35 @@ +"use strict"; +// Copyright 2017 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +// Accepts an options object passed from the user to the API. In the +// previous version of the API, it referred to a `Request` options object. +// Now it refers to an Axiox Request Config object. This is here to help +// ensure users don't pass invalid options when they upgrade from 0.x to 1.x. +// tslint:disable-next-line no-any +function validate(options) { + const vpairs = [ + { invalid: 'uri', expected: 'url' }, + { invalid: 'json', expected: 'data' }, + { invalid: 'qs', expected: 'params' }, + ]; + for (const pair of vpairs) { + if (options[pair.invalid]) { + const e = `'${pair.invalid}' is not a valid configuration option. Please use '${pair.expected}' instead. This library is using Axios for requests. Please see https://github.com/axios/axios to learn more about the valid request options.`; + throw new Error(e); + } + } +} +exports.validate = validate; +//# sourceMappingURL=options.js.map \ No newline at end of file diff --git a/node_modules/google-auth-library/build/src/transporters.d.ts b/node_modules/google-auth-library/build/src/transporters.d.ts new file mode 100644 index 0000000..16b5c5e --- /dev/null +++ b/node_modules/google-auth-library/build/src/transporters.d.ts @@ -0,0 +1,36 @@ +import { GaxiosError, GaxiosOptions, GaxiosPromise, GaxiosResponse } from 'gaxios'; +export interface Transporter { + request(opts: GaxiosOptions): GaxiosPromise; + request(opts: GaxiosOptions, callback?: BodyResponseCallback): void; + request(opts: GaxiosOptions, callback?: BodyResponseCallback): GaxiosPromise | void; +} +export interface BodyResponseCallback { + (err: Error | null, res?: GaxiosResponse | null): void; +} +export interface RequestError extends GaxiosError { + errors: Error[]; +} +export declare class DefaultTransporter { + /** + * Default user agent. + */ + static readonly USER_AGENT: string; + /** + * Configures request options before making a request. + * @param opts GaxiosOptions options. + * @return Configured options. + */ + configure(opts?: GaxiosOptions): GaxiosOptions; + /** + * Makes a request using Gaxios with given options. + * @param opts GaxiosOptions options. + * @param callback optional callback that contains GaxiosResponse object. + * @return GaxiosPromise, assuming no callback is passed. + */ + request(opts: GaxiosOptions): GaxiosPromise; + request(opts: GaxiosOptions, callback?: BodyResponseCallback): void; + /** + * Changes the error to include details from the body. + */ + private processError; +} diff --git a/node_modules/google-auth-library/build/src/transporters.js b/node_modules/google-auth-library/build/src/transporters.js new file mode 100644 index 0000000..5bb2e13 --- /dev/null +++ b/node_modules/google-auth-library/build/src/transporters.js @@ -0,0 +1,115 @@ +"use strict"; +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +const gaxios_1 = require("gaxios"); +const options_1 = require("./options"); +// eslint-disable-next-line @typescript-eslint/no-var-requires +const pkg = require('../../package.json'); +const PRODUCT_NAME = 'google-api-nodejs-client'; +class DefaultTransporter { + /** + * Configures request options before making a request. + * @param opts GaxiosOptions options. + * @return Configured options. + */ + configure(opts = {}) { + opts.headers = opts.headers || {}; + if (typeof window === 'undefined') { + // set transporter user agent if not in browser + const uaValue = opts.headers['User-Agent']; + if (!uaValue) { + opts.headers['User-Agent'] = DefaultTransporter.USER_AGENT; + } + else if (!uaValue.includes(`${PRODUCT_NAME}/`)) { + opts.headers['User-Agent'] = `${uaValue} ${DefaultTransporter.USER_AGENT}`; + } + // track google-auth-library-nodejs version: + const authVersion = `auth/${pkg.version}`; + if (opts.headers['x-goog-api-client'] && + !opts.headers['x-goog-api-client'].includes(authVersion)) { + opts.headers['x-goog-api-client'] = `${opts.headers['x-goog-api-client']} ${authVersion}`; + } + else if (!opts.headers['x-goog-api-client']) { + const nodeVersion = process.version.replace(/^v/, ''); + opts.headers['x-goog-api-client'] = `gl-node/${nodeVersion} ${authVersion}`; + } + } + return opts; + } + request(opts, callback) { + // ensure the user isn't passing in request-style options + opts = this.configure(opts); + try { + options_1.validate(opts); + } + catch (e) { + if (callback) { + return callback(e); + } + else { + throw e; + } + } + if (callback) { + gaxios_1.request(opts).then(r => { + callback(null, r); + }, e => { + callback(this.processError(e)); + }); + } + else { + return gaxios_1.request(opts).catch(e => { + throw this.processError(e); + }); + } + } + /** + * Changes the error to include details from the body. + */ + processError(e) { + const res = e.response; + const err = e; + const body = res ? res.data : null; + if (res && body && body.error && res.status !== 200) { + if (typeof body.error === 'string') { + err.message = body.error; + err.code = res.status.toString(); + } + else if (Array.isArray(body.error.errors)) { + err.message = body.error.errors + .map((err2) => err2.message) + .join('\n'); + err.code = body.error.code; + err.errors = body.error.errors; + } + else { + err.message = body.error.message; + err.code = body.error.code || res.status; + } + } + else if (res && res.status >= 400) { + // Consider all 4xx and 5xx responses errors. + err.message = body; + err.code = res.status.toString(); + } + return err; + } +} +exports.DefaultTransporter = DefaultTransporter; +/** + * Default user agent. + */ +DefaultTransporter.USER_AGENT = `${PRODUCT_NAME}/${pkg.version}`; +//# sourceMappingURL=transporters.js.map \ No newline at end of file diff --git a/node_modules/google-auth-library/package.json b/node_modules/google-auth-library/package.json new file mode 100644 index 0000000..0ac61b4 --- /dev/null +++ b/node_modules/google-auth-library/package.json @@ -0,0 +1,146 @@ +{ + "_from": "google-auth-library", + "_id": "google-auth-library@6.0.0", + "_inBundle": false, + "_integrity": "sha512-uLydy1t6SHN/EvYUJrtN3GCHFrnJ0c8HJjOxXiGjoTuYHIoCUT3jVxnzmjHwVnSdkfE9Akasm2rM6qG1COTXfQ==", + "_location": "/google-auth-library", + "_phantomChildren": {}, + "_requested": { + "type": "tag", + "registry": true, + "raw": "google-auth-library", + "name": "google-auth-library", + "escapedName": "google-auth-library", + "rawSpec": "", + "saveSpec": null, + "fetchSpec": "latest" + }, + "_requiredBy": [ + "#USER", + "/" + ], + "_resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-6.0.0.tgz", + "_shasum": "f92576e9e920803634c258b25f091604c1379722", + "_spec": "google-auth-library", + "_where": "/Users/cday/Code/zendesk/fetch-build-from-gcb", + "author": { + "name": "Google Inc." + }, + "bugs": { + "url": "https://github.com/googleapis/google-auth-library-nodejs/issues" + }, + "bundleDependencies": false, + "dependencies": { + "arrify": "^2.0.0", + "base64-js": "^1.3.0", + "ecdsa-sig-formatter": "^1.0.11", + "fast-text-encoding": "^1.0.0", + "gaxios": "^3.0.0", + "gcp-metadata": "^4.0.0", + "gtoken": "^5.0.0", + "jws": "^4.0.0", + "lru-cache": "^5.0.0" + }, + "deprecated": false, + "description": "Google APIs Authentication Client Library for Node.js", + "devDependencies": { + "@compodoc/compodoc": "^1.1.7", + "@types/base64-js": "^1.2.5", + "@types/chai": "^4.1.7", + "@types/jws": "^3.1.0", + "@types/lru-cache": "^5.0.0", + "@types/mocha": "^7.0.0", + "@types/mv": "^2.1.0", + "@types/ncp": "^2.0.1", + "@types/node": "^10.5.1", + "@types/sinon": "^7.0.0", + "@types/tmp": "^0.1.0", + "assert-rejects": "^1.0.0", + "c8": "^7.0.0", + "chai": "^4.2.0", + "codecov": "^3.0.2", + "execa": "^4.0.0", + "gts": "^2.0.0-alpha.8", + "is-docker": "^2.0.0", + "karma": "^4.0.0", + "karma-chrome-launcher": "^3.0.0", + "karma-coverage": "^2.0.0", + "karma-firefox-launcher": "^1.1.0", + "karma-mocha": "^1.3.0", + "karma-remap-coverage": "^0.1.5", + "karma-sourcemap-loader": "^0.3.7", + "karma-webpack": "^4.0.0", + "keypair": "^1.0.1", + "linkinator": "^2.0.0", + "mocha": "^7.0.0", + "mv": "^2.1.1", + "ncp": "^2.0.0", + "nock": "^12.0.0", + "null-loader": "^3.0.0", + "puppeteer": "^2.0.0", + "sinon": "^9.0.0", + "tmp": "^0.1.0", + "ts-loader": "^6.0.0", + "typescript": "^3.8.3", + "webpack": "^4.20.2", + "webpack-cli": "^3.1.1" + }, + "engines": { + "node": ">=10" + }, + "files": [ + "build/src", + "!build/src/**/*.map" + ], + "homepage": "https://github.com/googleapis/google-auth-library-nodejs#readme", + "keywords": [ + "google", + "api", + "google apis", + "client", + "client library" + ], + "license": "Apache-2.0", + "main": "./build/src/index.js", + "name": "google-auth-library", + "repository": { + "type": "git", + "url": "git+https://github.com/googleapis/google-auth-library-nodejs.git" + }, + "scripts": { + "browser-test": "karma start", + "clean": "gts clean", + "compile": "tsc -p .", + "docs": "compodoc src/", + "docs-test": "linkinator docs", + "fix": "gts fix && eslint --fix '**/*.js'", + "lint": "gts check", + "predocs-test": "npm run docs", + "prelint": "cd samples; npm link ../; npm i", + "prepare": "npm run compile", + "presystem-test": "npm run compile", + "pretest": "npm run compile", + "samples-test": "cd samples/ && npm link ../ && npm test && cd ../", + "system-test": "mocha build/system-test --timeout 60000", + "test": "c8 mocha build/test", + "webpack": "webpack" + }, + "types": "./build/src/index.d.ts", + "version": "6.0.0", + "warnings": [ + { + "code": "ENOTSUP", + "required": { + "node": ">=10" + }, + "pkgid": "google-auth-library@6.0.0" + }, + { + "code": "ENOTSUP", + "required": { + "node": ">=10" + }, + "pkgid": "google-auth-library@6.0.0" + } + ] +} diff --git a/node_modules/google-p12-pem/CHANGELOG.md b/node_modules/google-p12-pem/CHANGELOG.md new file mode 100644 index 0000000..d0449b7 --- /dev/null +++ b/node_modules/google-p12-pem/CHANGELOG.md @@ -0,0 +1,149 @@ +# Changelog + +[npm history][1] + +[1]: https://www.npmjs.com/package/google-p12-pem?activeTab=versions + +### [2.0.4](https://www.github.com/googleapis/google-p12-pem/compare/v2.0.3...v2.0.4) (2020-01-06) + + +### Bug Fixes + +* **deps:** pin TypeScript below 3.7.0 ([81dd96d](https://www.github.com/googleapis/google-p12-pem/commit/81dd96d4b43100824561f45b51f9126195b41d1d)) + +### [2.0.3](https://www.github.com/googleapis/google-p12-pem/compare/v2.0.2...v2.0.3) (2019-11-13) + + +### Bug Fixes + +* **docs:** add jsdoc-region-tag plugin ([#206](https://www.github.com/googleapis/google-p12-pem/issues/206)) ([b34efde](https://www.github.com/googleapis/google-p12-pem/commit/b34efdebb853dd5129e15ec1ff11a75184fc32d7)) + +### [2.0.2](https://www.github.com/googleapis/google-p12-pem/compare/v2.0.1...v2.0.2) (2019-09-06) + + +### Bug Fixes + +* **deps:** update dependency node-forge to ^0.9.0 ([#193](https://www.github.com/googleapis/google-p12-pem/issues/193)) ([ecac0f4](https://www.github.com/googleapis/google-p12-pem/commit/ecac0f4)) +* **docs:** remove reference-docs anchor ([a6ad735](https://www.github.com/googleapis/google-p12-pem/commit/a6ad735)) + +### [2.0.1](https://www.github.com/googleapis/google-p12-pem/compare/v2.0.0...v2.0.1) (2019-06-26) + + +### Bug Fixes + +* **docs:** link to reference docs section on googleapis.dev ([#184](https://www.github.com/googleapis/google-p12-pem/issues/184)) ([a08353b](https://www.github.com/googleapis/google-p12-pem/commit/a08353b)) + +## [2.0.0](https://www.github.com/google/google-p12-pem/compare/v1.0.4...v2.0.0) (2019-05-02) + + +### Build System + +* upgrade engines field to >=8.10.0 ([#167](https://www.github.com/google/google-p12-pem/issues/167)) ([85da6e6](https://www.github.com/google/google-p12-pem/commit/85da6e6)) + + +### BREAKING CHANGES + +* upgrade engines field to >=8.10.0 (#167) + +## v1.0.4 + +03-12-2019 12:25 PDT + +This release includes a new shiny version of node-forge! + +### Dependencies +- fix(deps): update dependency node-forge to ^0.8.0 ([#137](https://github.com/google/google-p12-pem/pull/137)) + +### Documentation +- docs: update links in contrib guide ([#145](https://github.com/google/google-p12-pem/pull/145)) +- docs: move CONTRIBUTING.md to root ([#140](https://github.com/google/google-p12-pem/pull/140)) +- docs: add lint/fix example to contributing guide ([#138](https://github.com/google/google-p12-pem/pull/138)) + +### Internal / Testing Changes +- build: Add docuploader credentials to node publish jobs ([#149](https://github.com/google/google-p12-pem/pull/149)) +- build: update release config ([#147](https://github.com/google/google-p12-pem/pull/147)) +- build: use node10 to run samples-test, system-test etc ([#148](https://github.com/google/google-p12-pem/pull/148)) +- chore(deps): update dependency mocha to v6 +- build: use linkinator for docs test ([#144](https://github.com/google/google-p12-pem/pull/144)) +- build: create docs test npm scripts ([#143](https://github.com/google/google-p12-pem/pull/143)) +- build: test using @grpc/grpc-js in CI ([#142](https://github.com/google/google-p12-pem/pull/142)) +- chore(deps): update dependency eslint-config-prettier to v4 ([#135](https://github.com/google/google-p12-pem/pull/135)) +- build: ignore googleapis.com in doc link check ([#134](https://github.com/google/google-p12-pem/pull/134)) +- build: check dead links on Kokoro ([#132](https://github.com/google/google-p12-pem/pull/132)) +- test: add system test, samples, and sample test ([#131](https://github.com/google/google-p12-pem/pull/131)) +- chore(build): inject yoshi automation key ([#130](https://github.com/google/google-p12-pem/pull/130)) +- chore: update nyc and eslint configs ([#129](https://github.com/google/google-p12-pem/pull/129)) +- chore: fix publish.sh permission +x ([#127](https://github.com/google/google-p12-pem/pull/127)) +- fix(build): fix Kokoro release script ([#126](https://github.com/google/google-p12-pem/pull/126)) +- build: add Kokoro configs for autorelease ([#125](https://github.com/google/google-p12-pem/pull/125)) + +## v1.0.3 + +12-07-2018 09:50 PST + +This is a service release very few updates. The only interesting change is the removal of support for Node.js 4.x and 9.x, both of which are out of LTS support. + +### Dependencies +- fix(deps): update dependency pify to v4 ([#62](https://github.com/google/google-p12-pem/pull/62)) + +### Documentation +- docs: clean up the readme ([#121](https://github.com/google/google-p12-pem/pull/121)) + +### Internal / Testing Changes +- chore: basic cleanup ([#122](https://github.com/google/google-p12-pem/pull/122)) +- chore: always nyc report before calling codecov ([#120](https://github.com/google/google-p12-pem/pull/120)) +- chore: nyc ignore build/test by default ([#119](https://github.com/google/google-p12-pem/pull/119)) +- chore(build): update templates and synth ([#117](https://github.com/google/google-p12-pem/pull/117)) +- fix(build): fix system key decryption ([#112](https://github.com/google/google-p12-pem/pull/112)) +- chore(deps): update dependency typescript to ~3.2.0 ([#111](https://github.com/google/google-p12-pem/pull/111)) +- chore: add synth.metadata +- chore(deps): update dependency gts to ^0.9.0 ([#106](https://github.com/google/google-p12-pem/pull/106)) +- chore: update eslintignore config ([#105](https://github.com/google/google-p12-pem/pull/105)) +- chore: use latest npm on Windows ([#104](https://github.com/google/google-p12-pem/pull/104)) +- chore: update CircleCI config ([#103](https://github.com/google/google-p12-pem/pull/103)) +- chore: include build in eslintignore ([#100](https://github.com/google/google-p12-pem/pull/100)) +- chore: update issue templates ([#96](https://github.com/google/google-p12-pem/pull/96)) +- chore: remove old issue template ([#94](https://github.com/google/google-p12-pem/pull/94)) +- build: run tests on node11 ([#93](https://github.com/google/google-p12-pem/pull/93)) +- chores(build): run codecov on continuous builds ([#88](https://github.com/google/google-p12-pem/pull/88)) +- chores(build): do not collect sponge.xml from windows builds ([#90](https://github.com/google/google-p12-pem/pull/90)) +- chore(deps): update dependency typescript to ~3.1.0 ([#89](https://github.com/google/google-p12-pem/pull/89)) +- chore: update new issue template ([#87](https://github.com/google/google-p12-pem/pull/87)) +- build: fix codecov uploading on Kokoro ([#84](https://github.com/google/google-p12-pem/pull/84)) +- Update kokoro config ([#81](https://github.com/google/google-p12-pem/pull/81)) +- Run system tests on Kokoro ([#78](https://github.com/google/google-p12-pem/pull/78)) +- Don't publish sourcemaps ([#79](https://github.com/google/google-p12-pem/pull/79)) +- test: remove appveyor config ([#77](https://github.com/google/google-p12-pem/pull/77)) +- Update CI config ([#76](https://github.com/google/google-p12-pem/pull/76)) +- Enable prefer-const in the eslint config ([#75](https://github.com/google/google-p12-pem/pull/75)) +- Enable no-var in eslint ([#74](https://github.com/google/google-p12-pem/pull/74)) +- Update CI config ([#73](https://github.com/google/google-p12-pem/pull/73)) +- Retry npm install in CI ([#71](https://github.com/google/google-p12-pem/pull/71)) +- Update CI config ([#69](https://github.com/google/google-p12-pem/pull/69)) +- Update CI config ([#68](https://github.com/google/google-p12-pem/pull/68)) +- Update github templates and CircleCI config ([#67](https://github.com/google/google-p12-pem/pull/67)) +- chore(deps): update dependency nyc to v13 ([#65](https://github.com/google/google-p12-pem/pull/65)) +- add synth file and standardize config ([#64](https://github.com/google/google-p12-pem/pull/64)) +- chore: ignore package-log.json ([#61](https://github.com/google/google-p12-pem/pull/61)) +- chore: update renovate config ([#59](https://github.com/google/google-p12-pem/pull/59)) +- chore(deps): lock file maintenance ([#60](https://github.com/google/google-p12-pem/pull/60)) +- chore: remove greenkeeper badge ([#58](https://github.com/google/google-p12-pem/pull/58)) +- test: throw on deprecation +- chore: move mocha options to mocha.opts ([#54](https://github.com/google/google-p12-pem/pull/54)) +- chore(deps): update dependency typescript to v3 ([#56](https://github.com/google/google-p12-pem/pull/56)) +- chore(deps): lock file maintenance ([#55](https://github.com/google/google-p12-pem/pull/55)) +- chore(deps): lock file maintenance ([#53](https://github.com/google/google-p12-pem/pull/53)) +- chore(deps): update dependency gts to ^0.8.0 ([#49](https://github.com/google/google-p12-pem/pull/49)) +- test: use strictEqual in tests ([#51](https://github.com/google/google-p12-pem/pull/51)) +- chore(deps): update dependency typescript to ~2.9.0 ([#50](https://github.com/google/google-p12-pem/pull/50)) +- chore: Configure Renovate ([#48](https://github.com/google/google-p12-pem/pull/48)) +- fix: drop support for node.js 4.x and 9.x ([#46](https://github.com/google/google-p12-pem/pull/46)) +- Add Code of Conduct +- chore(package): update gts to the latest version ([#45](https://github.com/google/google-p12-pem/pull/45)) +- chore(package): update nyc to version 12.0.2 ([#42](https://github.com/google/google-p12-pem/pull/42)) +- chore: upgrade to the latest version of all dependencies ([#39](https://github.com/google/google-p12-pem/pull/39)) +- chore(build): run lint as a separate job ([#40](https://github.com/google/google-p12-pem/pull/40)) +- fix: pin gts version with ^ ([#38](https://github.com/google/google-p12-pem/pull/38)) +- chore(package): update @types/node to version 10.0.3 ([#34](https://github.com/google/google-p12-pem/pull/34)) +- chore: start testing on node 10 ([#36](https://github.com/google/google-p12-pem/pull/36)) +- chore(package): update @types/mocha to version 5.0.0 ([#33](https://github.com/google/google-p12-pem/pull/33)) diff --git a/node_modules/google-p12-pem/LICENSE b/node_modules/google-p12-pem/LICENSE new file mode 100644 index 0000000..8dafa3b --- /dev/null +++ b/node_modules/google-p12-pem/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Ryan Seys + +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. diff --git a/node_modules/google-p12-pem/README.md b/node_modules/google-p12-pem/README.md new file mode 100644 index 0000000..43bfc4e --- /dev/null +++ b/node_modules/google-p12-pem/README.md @@ -0,0 +1,121 @@ +[//]: # "This README.md file is auto-generated, all changes to this file will be lost." +[//]: # "To regenerate it, use `python -m synthtool`." +Google Cloud Platform logo + +# [google-p12-pem: Node.js Client](https://github.com/googleapis/google-p12-pem) + +[![release level](https://img.shields.io/badge/release%20level-general%20availability%20%28GA%29-brightgreen.svg?style=flat)](https://cloud.google.com/terms/launch-stages) +[![npm version](https://img.shields.io/npm/v/google-p12-pem.svg)](https://www.npmjs.org/package/google-p12-pem) +[![codecov](https://img.shields.io/codecov/c/github/googleapis/google-p12-pem/master.svg?style=flat)](https://codecov.io/gh/googleapis/google-p12-pem) + + + + +Convert Google .p12 keys to .pem keys. + + + + +* [github.com/googleapis/google-p12-pem](https://github.com/googleapis/google-p12-pem) + +Read more about the client libraries for Cloud APIs, including the older +Google APIs Client Libraries, in [Client Libraries Explained][explained]. + +[explained]: https://cloud.google.com/apis/docs/client-libraries-explained + +**Table of contents:** + + +* [Quickstart](#quickstart) + + * [Installing the client library](#installing-the-client-library) + * [Using the client library](#using-the-client-library) +* [Samples](#samples) +* [Versioning](#versioning) +* [Contributing](#contributing) +* [License](#license) + +## Quickstart + +### Installing the client library + +```bash +npm install google-p12-pem +``` + + +### Using the client library + +```javascript + const {getPem} = require('google-p12-pem'); + + /** + * Given a p12 file, convert it to the PEM format. + * @param {string} pathToCert The relative path to a p12 file. + */ + async function quickstart() { + // TODO(developer): provide the path to your cert + // const pathToCert = 'path/to/cert.p12'; + + const pem = await getPem(pathToCert); + console.log('The converted PEM:'); + console.log(pem); + } + + quickstart(); + +``` +#### CLI style + +``` sh +gp12-pem myfile.p12 > output.pem +``` + + +## Samples + +Samples are in the [`samples/`](https://github.com/googleapis/google-p12-pem/tree/master/samples) directory. The samples' `README.md` +has instructions for running the samples. + +| Sample | Source Code | Try it | +| --------------------------- | --------------------------------- | ------ | +| Quickstart | [source code](https://github.com/googleapis/google-p12-pem/blob/master/samples/quickstart.js) | [![Open in Cloud Shell][shell_img]](https://console.cloud.google.com/cloudshell/open?git_repo=https://github.com/googleapis/google-p12-pem&page=editor&open_in_editor=samples/quickstart.js,samples/README.md) | + + + +## Versioning + +This library follows [Semantic Versioning](http://semver.org/). + + +This library is considered to be **General Availability (GA)**. This means it +is stable; the code surface will not change in backwards-incompatible ways +unless absolutely necessary (e.g. because of critical security issues) or with +an extensive deprecation period. Issues and requests against **GA** libraries +are addressed with the highest priority. + + + + + +More Information: [Google Cloud Platform Launch Stages][launch_stages] + +[launch_stages]: https://cloud.google.com/terms/launch-stages + +## Contributing + +Contributions welcome! See the [Contributing Guide](https://github.com/googleapis/google-p12-pem/blob/master/CONTRIBUTING.md). + +## License + +Apache Version 2.0 + +See [LICENSE](https://github.com/googleapis/google-p12-pem/blob/master/LICENSE) + + + +[shell_img]: https://gstatic.com/cloudssh/images/open-btn.png +[projects]: https://console.cloud.google.com/project +[billing]: https://support.google.com/cloud/answer/6293499#enable-billing + +[auth]: https://cloud.google.com/docs/authentication/getting-started diff --git a/node_modules/google-p12-pem/build/src/bin/gp12-pem.d.ts b/node_modules/google-p12-pem/build/src/bin/gp12-pem.d.ts new file mode 100644 index 0000000..cd3d1cd --- /dev/null +++ b/node_modules/google-p12-pem/build/src/bin/gp12-pem.d.ts @@ -0,0 +1,8 @@ +#!/usr/bin/env node +/** + * Copyright 2018 Google LLC + * + * Distributed under MIT license. + * See file LICENSE for detail or copy at https://opensource.org/licenses/MIT + */ +export {}; diff --git a/node_modules/google-p12-pem/build/src/bin/gp12-pem.js b/node_modules/google-p12-pem/build/src/bin/gp12-pem.js new file mode 100755 index 0000000..e2939c4 --- /dev/null +++ b/node_modules/google-p12-pem/build/src/bin/gp12-pem.js @@ -0,0 +1,26 @@ +#!/usr/bin/env node +"use strict"; +/** + * Copyright 2018 Google LLC + * + * Distributed under MIT license. + * See file LICENSE for detail or copy at https://opensource.org/licenses/MIT + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const gp12 = require("../index"); +const argv = process.argv; +const p12Path = argv[2]; +if (!p12Path) { + console.error('Please specify a *.p12 file to convert.'); + process.exit(1); +} +gp12.getPem(p12Path, (err, pem) => { + if (err) { + console.log(err); + process.exit(1); + } + else { + console.log(pem); + } +}); +//# sourceMappingURL=gp12-pem.js.map \ No newline at end of file diff --git a/node_modules/google-p12-pem/build/src/index.d.ts b/node_modules/google-p12-pem/build/src/index.d.ts new file mode 100644 index 0000000..06e04d3 --- /dev/null +++ b/node_modules/google-p12-pem/build/src/index.d.ts @@ -0,0 +1,15 @@ +/** + * Copyright 2018 Google LLC + * + * Distributed under MIT license. + * See file LICENSE for detail or copy at https://opensource.org/licenses/MIT + */ +/** + * Convert a .p12 file to .pem string + * @param filename The .p12 key filename. + * @param callback The callback function. + * @return A promise that resolves with the .pem private key + * if no callback provided. + */ +export declare function getPem(filename: string): Promise; +export declare function getPem(filename: string, callback: (err: Error | null, pem: string | null) => void): void; diff --git a/node_modules/google-p12-pem/build/src/index.js b/node_modules/google-p12-pem/build/src/index.js new file mode 100644 index 0000000..f997c40 --- /dev/null +++ b/node_modules/google-p12-pem/build/src/index.js @@ -0,0 +1,48 @@ +"use strict"; +/** + * Copyright 2018 Google LLC + * + * Distributed under MIT license. + * See file LICENSE for detail or copy at https://opensource.org/licenses/MIT + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const fs = require("fs"); +const forge = require("node-forge"); +const util_1 = require("util"); +const readFile = util_1.promisify(fs.readFile); +function getPem(filename, callback) { + if (callback) { + getPemAsync(filename) + .then(pem => callback(null, pem)) + .catch(err => callback(err, null)); + } + else { + return getPemAsync(filename); + } +} +exports.getPem = getPem; +function getPemAsync(filename) { + return readFile(filename, { encoding: 'base64' }).then(keyp12 => { + return convertToPem(keyp12); + }); +} +/** + * Converts a P12 in base64 encoding to a pem. + * @param p12base64 String containing base64 encoded p12. + * @returns a string containing the pem. + */ +function convertToPem(p12base64) { + const p12Der = forge.util.decode64(p12base64); + const p12Asn1 = forge.asn1.fromDer(p12Der); + const p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1, 'notasecret'); + const bags = p12.getBags({ friendlyName: 'privatekey' }); + if (bags.friendlyName) { + const privateKey = bags.friendlyName[0].key; + const pem = forge.pki.privateKeyToPem(privateKey); + return pem.replace(/\r\n/g, '\n'); + } + else { + throw new Error('Unable to get friendly name.'); + } +} +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/google-p12-pem/package.json b/node_modules/google-p12-pem/package.json new file mode 100644 index 0000000..93d4efd --- /dev/null +++ b/node_modules/google-p12-pem/package.json @@ -0,0 +1,104 @@ +{ + "_from": "google-p12-pem@^2.0.0", + "_id": "google-p12-pem@2.0.4", + "_inBundle": false, + "_integrity": "sha512-S4blHBQWZRnEW44OcR7TL9WR+QCqByRvhNDZ/uuQfpxywfupikf/miba8js1jZi6ZOGv5slgSuoshCWh6EMDzg==", + "_location": "/google-p12-pem", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "google-p12-pem@^2.0.0", + "name": "google-p12-pem", + "escapedName": "google-p12-pem", + "rawSpec": "^2.0.0", + "saveSpec": null, + "fetchSpec": "^2.0.0" + }, + "_requiredBy": [ + "/gtoken" + ], + "_resolved": "https://registry.npmjs.org/google-p12-pem/-/google-p12-pem-2.0.4.tgz", + "_shasum": "036462394e266472632a78b685f0cc3df4ef337b", + "_spec": "google-p12-pem@^2.0.0", + "_where": "/Users/cday/Code/zendesk/fetch-build-from-gcb/node_modules/gtoken", + "author": { + "name": "Ryan Seys" + }, + "bin": { + "gp12-pem": "build/src/bin/gp12-pem.js" + }, + "bugs": { + "url": "https://github.com/google/google-p12-pem/issues" + }, + "bundleDependencies": false, + "dependencies": { + "node-forge": "^0.9.0" + }, + "deprecated": false, + "description": "Convert Google .p12 keys to .pem keys.", + "devDependencies": { + "@compodoc/compodoc": "^1.1.7", + "@types/mocha": "^5.2.0", + "@types/node": "^10.0.9", + "@types/node-forge": "^0.9.0", + "c8": "^7.0.0", + "codecov": "^3.0.2", + "eslint": "^6.0.0", + "eslint-config-prettier": "^6.0.0", + "eslint-plugin-node": "^11.0.0", + "eslint-plugin-prettier": "^3.0.0", + "gts": "^1.0.0", + "intelli-espower-loader": "^1.0.1", + "js-green-licenses": "^1.0.0", + "linkinator": "^1.5.0", + "mocha": "^7.0.0", + "prettier": "^1.15.3", + "source-map-support": "^0.5.6", + "typescript": "3.6.4" + }, + "engines": { + "node": ">=8.10.0" + }, + "files": [ + "build/src", + "!build/src/**/*.map" + ], + "homepage": "https://github.com/google/google-p12-pem#readme", + "license": "MIT", + "main": "./build/src/index.js", + "name": "google-p12-pem", + "repository": { + "type": "git", + "url": "git+https://github.com/google/google-p12-pem.git" + }, + "scripts": { + "check": "gts check && npm run license-check", + "clean": "gts clean", + "compile": "tsc -p .", + "docs": "compodoc src/", + "docs-test": "linkinator docs", + "fix": "gts fix && eslint --fix '**/*.js'", + "license-check": "jsgl --local .", + "lint": "gts check && eslint '**/*.js'", + "posttest": "npm run check", + "predocs-test": "npm run docs", + "prepare": "npm run compile", + "presystem-test": "npm run compile", + "pretest": "npm run compile", + "samples-test": "cd samples/ && npm link ../ && npm test && cd ../", + "system-test": "mocha build/system-test", + "test": "c8 mocha build/test" + }, + "types": "./build/src/index.d.ts", + "version": "2.0.4", + "warnings": [ + { + "code": "ENOTSUP", + "required": { + "node": ">=8.10.0" + }, + "pkgid": "google-p12-pem@2.0.4" + } + ] +} diff --git a/node_modules/gtoken/CHANGELOG.md b/node_modules/gtoken/CHANGELOG.md new file mode 100644 index 0000000..aa901ef --- /dev/null +++ b/node_modules/gtoken/CHANGELOG.md @@ -0,0 +1,223 @@ +# Changelog + +[npm history][1] + +[1]: https://www.npmjs.com/package/gtoken?activeTab=versions + +## [5.0.0](https://www.github.com/googleapis/node-gtoken/compare/v4.1.4...v5.0.0) (2020-03-24) + + +### ⚠ BREAKING CHANGES + +* drop Node 8 from engines (#284) +* typescript@3.7.x introduced breaking changes to compiled code + +### Features + +* drop Node 8 from engines ([#284](https://www.github.com/googleapis/node-gtoken/issues/284)) ([209e007](https://www.github.com/googleapis/node-gtoken/commit/209e00746116a82a3cf9acc158aff12a4971f3d0)) + + +### Build System + +* update gts and typescript ([#283](https://www.github.com/googleapis/node-gtoken/issues/283)) ([ff076dc](https://www.github.com/googleapis/node-gtoken/commit/ff076dcb3da229238e7bed28d739c48986652c78)) + +### [4.1.4](https://www.github.com/googleapis/node-gtoken/compare/v4.1.3...v4.1.4) (2020-01-06) + + +### Bug Fixes + +* **deps:** pin TypeScript below 3.7.0 ([f1ae7b6](https://www.github.com/googleapis/node-gtoken/commit/f1ae7b64ead1c918546ae5bbe8546dfb4ecc788a)) +* **deps:** update dependency jws to v4 ([#251](https://www.github.com/googleapis/node-gtoken/issues/251)) ([e13542f](https://www.github.com/googleapis/node-gtoken/commit/e13542f888a81ed3ced0023e9b78ed25264b1d1c)) + +### [4.1.3](https://www.github.com/googleapis/node-gtoken/compare/v4.1.2...v4.1.3) (2019-11-15) + + +### Bug Fixes + +* **deps:** use typescript ~3.6.0 ([#246](https://www.github.com/googleapis/node-gtoken/issues/246)) ([5f725b7](https://www.github.com/googleapis/node-gtoken/commit/5f725b71f080e83058b1a23340acadc0c8704123)) + +### [4.1.2](https://www.github.com/googleapis/node-gtoken/compare/v4.1.1...v4.1.2) (2019-11-13) + + +### Bug Fixes + +* **docs:** add jsdoc-region-tag plugin ([#242](https://www.github.com/googleapis/node-gtoken/issues/242)) ([994c5cc](https://www.github.com/googleapis/node-gtoken/commit/994c5ccf92731599aa63b84c29a9d5f6b1431cc5)) + +### [4.1.1](https://www.github.com/googleapis/node-gtoken/compare/v4.1.0...v4.1.1) (2019-10-31) + + +### Bug Fixes + +* **deps:** update gaxios to 2.1.0 ([#238](https://www.github.com/googleapis/node-gtoken/issues/238)) ([bb12064](https://www.github.com/googleapis/node-gtoken/commit/bb1206420388399ef8992efe54c70bdb3fdcd965)) + +## [4.1.0](https://www.github.com/googleapis/node-gtoken/compare/v4.0.0...v4.1.0) (2019-09-24) + + +### Features + +* allow upstream libraries to force token refresh ([#229](https://www.github.com/googleapis/node-gtoken/issues/229)) ([1fd4dd1](https://www.github.com/googleapis/node-gtoken/commit/1fd4dd1)) + +## [4.0.0](https://www.github.com/googleapis/node-gtoken/compare/v3.0.2...v4.0.0) (2019-07-09) + + +### ⚠ BREAKING CHANGES + +* This commit creates multiple breaking changes. The `getToken()` +method previously returned `Promise`, where the string was the +`access_token` returned from the response. However, the `oauth2` endpoint could +return a variety of other fields, such as an `id_token` in special cases. + +```js +const token = await getToken(); +// old response: 'some.access.token' +// new response: { access_token: 'some.access.token'} +``` + +To further support this change, the `GoogleToken` class no longer exposes +a `token` variable. It now exposes `rawToken`, `accessToken`, and `idToken` +fields which can be used to access the relevant values returned in the +response. + +### Bug Fixes + +* expose all fields from response ([#218](https://www.github.com/googleapis/node-gtoken/issues/218)) ([d463370](https://www.github.com/googleapis/node-gtoken/commit/d463370)) + +### [3.0.2](https://www.github.com/googleapis/node-gtoken/compare/v3.0.1...v3.0.2) (2019-06-26) + + +### Bug Fixes + +* **docs:** make anchors work in jsdoc ([#215](https://www.github.com/googleapis/node-gtoken/issues/215)) ([c5f6c89](https://www.github.com/googleapis/node-gtoken/commit/c5f6c89)) + +### [3.0.1](https://www.github.com/googleapis/node-gtoken/compare/v3.0.0...v3.0.1) (2019-06-13) + + +### Bug Fixes + +* **docs:** move to new client docs URL ([#212](https://www.github.com/googleapis/node-gtoken/issues/212)) ([b7a8c75](https://www.github.com/googleapis/node-gtoken/commit/b7a8c75)) + +## [3.0.0](https://www.github.com/googleapis/node-gtoken/compare/v2.3.3...v3.0.0) (2019-05-07) + + +### Bug Fixes + +* **deps:** update dependency gaxios to v2 ([#191](https://www.github.com/googleapis/node-gtoken/issues/191)) ([da65ea7](https://www.github.com/googleapis/node-gtoken/commit/da65ea7)) +* **deps:** update dependency google-p12-pem to v2 ([#196](https://www.github.com/googleapis/node-gtoken/issues/196)) ([b510f06](https://www.github.com/googleapis/node-gtoken/commit/b510f06)) +* fs.readFile does not exist in browser ([#186](https://www.github.com/googleapis/node-gtoken/issues/186)) ([a16d8e7](https://www.github.com/googleapis/node-gtoken/commit/a16d8e7)) + + +### Build System + +* upgrade engines field to >=8.10.0 ([#194](https://www.github.com/googleapis/node-gtoken/issues/194)) ([ee4d6c8](https://www.github.com/googleapis/node-gtoken/commit/ee4d6c8)) + + +### BREAKING CHANGES + +* upgrade engines field to >=8.10.0 (#194) + +## v2.3.3 + +03-13-2019 14:54 PDT + +### Bug Fixes +- fix: propagate error message ([#173](https://github.com/google/node-gtoken/pull/173)) + +### Documentation +- docs: update links in contrib guide ([#171](https://github.com/google/node-gtoken/pull/171)) +- docs: move CONTRIBUTING.md to root ([#166](https://github.com/google/node-gtoken/pull/166)) +- docs: add lint/fix example to contributing guide ([#164](https://github.com/google/node-gtoken/pull/164)) + +### Internal / Testing Changes +- build: Add docuploader credentials to node publish jobs ([#176](https://github.com/google/node-gtoken/pull/176)) +- build: use node10 to run samples-test, system-test etc ([#175](https://github.com/google/node-gtoken/pull/175)) +- build: update release configuration +- chore(deps): update dependency mocha to v6 +- build: use linkinator for docs test ([#170](https://github.com/google/node-gtoken/pull/170)) +- build: create docs test npm scripts ([#169](https://github.com/google/node-gtoken/pull/169)) +- build: test using @grpc/grpc-js in CI ([#168](https://github.com/google/node-gtoken/pull/168)) +- build: ignore googleapis.com in doc link check ([#162](https://github.com/google/node-gtoken/pull/162)) +- build: check for 404s on all docs + +## v2.3.2 + +01-09-2019 13:40 PST + +### Documentation +- docs: generate docs with compodoc ([#154](https://github.com/googleapis/node-gtoken/pull/154)) +- docs: fix up the readme ([#153](https://github.com/googleapis/node-gtoken/pull/153)) + +### Internal / Testing Changes +- build: Re-generated to pick up changes in the API or client library generator. ([#158](https://github.com/googleapis/node-gtoken/pull/158)) +- build: check broken links in generated docs ([#152](https://github.com/googleapis/node-gtoken/pull/152)) +- fix: add a system test and get it passing ([#150](https://github.com/googleapis/node-gtoken/pull/150)) +- chore(build): inject yoshi automation key ([#149](https://github.com/googleapis/node-gtoken/pull/149)) + +## v2.3.1 + +12-10-2018 15:28 PST + +### Dependencies +- fix(deps): update dependency pify to v4 ([#87](https://github.com/google/node-gtoken/pull/87)) +- fix(deps): use gaxios for http requests ([#125](https://github.com/google/node-gtoken/pull/125)) + +### Internal / Testing Changes +- build: add Kokoro configs for autorelease ([#143](https://github.com/google/node-gtoken/pull/143)) +- chore: always nyc report before calling codecov ([#141](https://github.com/google/node-gtoken/pull/141)) +- chore: nyc ignore build/test by default ([#140](https://github.com/google/node-gtoken/pull/140)) +- chore: update synth metadata and templates ([#138](https://github.com/google/node-gtoken/pull/138)) +- fix(build): fix system key decryption ([#133](https://github.com/google/node-gtoken/pull/133)) +- chore(deps): update dependency typescript to ~3.2.0 ([#132](https://github.com/google/node-gtoken/pull/132)) +- chore: add a synth.metadata +- chore(deps): update dependency gts to ^0.9.0 ([#127](https://github.com/google/node-gtoken/pull/127)) +- chore: update eslintignore config ([#126](https://github.com/google/node-gtoken/pull/126)) +- chore: use latest npm on Windows ([#124](https://github.com/google/node-gtoken/pull/124)) +- chore: update CircleCI config ([#123](https://github.com/google/node-gtoken/pull/123)) +- chore: include build in eslintignore ([#120](https://github.com/google/node-gtoken/pull/120)) +- chore: update issue templates ([#116](https://github.com/google/node-gtoken/pull/116)) +- chore: remove old issue template ([#114](https://github.com/google/node-gtoken/pull/114)) +- build: run tests on node11 ([#113](https://github.com/google/node-gtoken/pull/113)) +- chore(deps): update dependency nock to v10 ([#111](https://github.com/google/node-gtoken/pull/111)) +- chores(build): do not collect sponge.xml from windows builds ([#112](https://github.com/google/node-gtoken/pull/112)) +- chore(deps): update dependency typescript to ~3.1.0 ([#110](https://github.com/google/node-gtoken/pull/110)) +- chores(build): run codecov on continuous builds ([#109](https://github.com/google/node-gtoken/pull/109)) +- chore: update new issue template ([#108](https://github.com/google/node-gtoken/pull/108)) +- chore: update CI config ([#105](https://github.com/google/node-gtoken/pull/105)) +- Update kokoro config ([#103](https://github.com/google/node-gtoken/pull/103)) +- Update CI config ([#101](https://github.com/google/node-gtoken/pull/101)) +- Don't publish sourcemaps ([#99](https://github.com/google/node-gtoken/pull/99)) +- Update kokoro config ([#97](https://github.com/google/node-gtoken/pull/97)) +- test: remove appveyor config ([#96](https://github.com/google/node-gtoken/pull/96)) +- Update CI config ([#95](https://github.com/google/node-gtoken/pull/95)) +- Enable prefer-const in the eslint config ([#94](https://github.com/google/node-gtoken/pull/94)) +- Enable no-var in eslint ([#93](https://github.com/google/node-gtoken/pull/93)) +- Update CI config ([#92](https://github.com/google/node-gtoken/pull/92)) +- Add synth and update CI config ([#91](https://github.com/google/node-gtoken/pull/91)) +- Retry npm install in CI ([#90](https://github.com/google/node-gtoken/pull/90)) +- chore(deps): update dependency nyc to v13 ([#88](https://github.com/google/node-gtoken/pull/88)) +- chore: ignore package-log.json ([#86](https://github.com/google/node-gtoken/pull/86)) +- chore: update renovate config ([#83](https://github.com/google/node-gtoken/pull/83)) +- chore(deps): lock file maintenance ([#85](https://github.com/google/node-gtoken/pull/85)) +- chore: remove greenkeeper badge ([#82](https://github.com/google/node-gtoken/pull/82)) +- test: throw on deprecation ([#81](https://github.com/google/node-gtoken/pull/81)) +- chore(deps): update dependency typescript to v3 ([#80](https://github.com/google/node-gtoken/pull/80)) +- chore: move mocha options to mocha.opts ([#78](https://github.com/google/node-gtoken/pull/78)) +- chore(deps): lock file maintenance ([#79](https://github.com/google/node-gtoken/pull/79)) +- test: use strictEqual in tests ([#76](https://github.com/google/node-gtoken/pull/76)) +- chore(deps): lock file maintenance ([#77](https://github.com/google/node-gtoken/pull/77)) +- chore(deps): update dependency typescript to ~2.9.0 ([#75](https://github.com/google/node-gtoken/pull/75)) +- chore: Configure Renovate ([#74](https://github.com/google/node-gtoken/pull/74)) +- Update gts to the latest version 🚀 ([#73](https://github.com/google/node-gtoken/pull/73)) +- Add Code of Conduct +- build: start testing against Node 10 ([#69](https://github.com/google/node-gtoken/pull/69)) +- chore(package): update nyc to version 12.0.2 ([#67](https://github.com/google/node-gtoken/pull/67)) +- chore(package): update @types/node to version 10.0.3 ([#65](https://github.com/google/node-gtoken/pull/65)) + +### 2.0.0 +New features: +- API now supports callback and promise based workflows + +Breaking changes: +- `GoogleToken` is now a class type, and must be instantiated. +- `GoogleToken.expires_at` renamed to `GoogleToken.expiresAt` +- `GoogleToken.raw_token` renamed to `GoogleToken.rawToken` +- `GoogleToken.token_expires` renamed to `GoogleToken.tokenExpires` diff --git a/node_modules/gtoken/LICENSE b/node_modules/gtoken/LICENSE new file mode 100644 index 0000000..061e6a6 --- /dev/null +++ b/node_modules/gtoken/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014 Ryan Seys + +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. diff --git a/node_modules/gtoken/README.md b/node_modules/gtoken/README.md new file mode 100644 index 0000000..3e1831f --- /dev/null +++ b/node_modules/gtoken/README.md @@ -0,0 +1,182 @@ +Google Cloud Platform logo + +# [node-gtoken](https://github.com/googleapis/node-gtoken) + +[![npm version][npm-image]][npm-url] +[![Known Vulnerabilities][snyk-image]][snyk-url] +[![codecov][codecov-image]][codecov-url] +[![Code Style: Google][gts-image]][gts-url] + +> Node.js Google Authentication Service Account Tokens + +This is a low level utility library used to interact with Google Authentication services. **In most cases, you probably want to use the [google-auth-library](https://github.com/googleapis/google-auth-library-nodejs) instead.** + +* [gtoken API Reference][client-docs] +* [github.com/googleapis/node-gtoken](https://github.com/googleapis/node-gtoken) + +## Installation + +``` sh +npm install gtoken +``` + +## Usage + +### Use with a `.pem` or `.p12` key file: + +``` js +const { GoogleToken } = require('gtoken'); +const gtoken = new GoogleToken({ + keyFile: 'path/to/key.pem', // or path to .p12 key file + email: 'my_service_account_email@developer.gserviceaccount.com', + scope: ['https://scope1', 'https://scope2'] // or space-delimited string of scopes +}); + +gtoken.getToken((err, tokens) => { + if (err) { + console.log(err); + return; + } + console.log(tokens); + // { + // access_token: 'very-secret-token', + // expires_in: 3600, + // token_type: 'Bearer' + // } +}); +``` + +You can also use the async/await style API: + +``` js +const tokens = await gtoken.getToken() +console.log(tokens); +``` + +Or use promises: + +```js +gtoken.getToken() + .then(tokens => { + console.log(tokens) + }) + .catch(console.error); +``` + +### Use with a service account `.json` key file: + +``` js +const { GoogleToken } = require('gtoken'); +const gtoken = new GoogleToken({ + keyFile: 'path/to/key.json', + scope: ['https://scope1', 'https://scope2'] // or space-delimited string of scopes +}); + +gtoken.getToken((err, tokens) => { + if (err) { + console.log(err); + return; + } + console.log(tokens); +}); +``` + +### Pass the private key as a string directly: + +``` js +const key = '-----BEGIN RSA PRIVATE KEY-----\nXXXXXXXXXXX...'; +const { GoogleToken } = require('gtoken'); +const gtoken = new GoogleToken({ + email: 'my_service_account_email@developer.gserviceaccount.com', + scope: ['https://scope1', 'https://scope2'], // or space-delimited string of scopes + key: key +}); +``` + +## Options + +> Various options that can be set when creating initializing the `gtoken` object. + +- `options.email or options.iss`: The service account email address. +- `options.scope`: An array of scope strings or space-delimited string of scopes. +- `options.sub`: The email address of the user requesting delegated access. +- `options.keyFile`: The filename of `.json` key, `.pem` key or `.p12` key. +- `options.key`: The raw RSA private key value, in place of using `options.keyFile`. + +### .getToken(callback) + +> Returns the cached tokens or requests a new one and returns it. + +``` js +gtoken.getToken((err, token) => { + console.log(err || token); + // gtoken.rawToken value is also set +}); +``` + +### .getCredentials('path/to/key.json') + +> Given a keyfile, returns the key and (if available) the client email. + +```js +const creds = await gtoken.getCredentials('path/to/key.json'); +``` + +### Properties + +> Various properties set on the gtoken object after call to `.getToken()`. + +- `gtoken.idToken`: The OIDC token returned (if any). +- `gtoken.accessToken`: The access token. +- `gtoken.expiresAt`: The expiry date as milliseconds since 1970/01/01 +- `gtoken.key`: The raw key value. +- `gtoken.rawToken`: Most recent raw token data received from Google. + +### .hasExpired() + +> Returns true if the token has expired, or token does not exist. + +``` js +const tokens = await gtoken.getToken(); +gtoken.hasExpired(); // false +``` + +### .revokeToken() + +> Revoke the token if set. + +``` js +await gtoken.revokeToken(); +console.log('Token revoked!'); +``` + +## Downloading your private `.p12` key from Google + +1. Open the [Google Developer Console][gdevconsole]. +2. Open your project and under "APIs & auth", click Credentials. +3. Generate a new `.p12` key and download it into your project. + +## Converting your `.p12` key to a `.pem` key + +You can just specify your `.p12` file (with `.p12` extension) as the `keyFile` and it will automatically be converted to a `.pem` on the fly, however this results in a slight performance hit. If you'd like to convert to a `.pem` for use later, use OpenSSL if you have it installed. + +``` sh +$ openssl pkcs12 -in key.p12 -nodes -nocerts > key.pem +``` + +Don't forget, the passphrase when converting these files is the string `'notasecret'` + +## License + +[MIT](https://github.com/googleapis/node-gtoken/blob/master/LICENSE) + +[codecov-image]: https://codecov.io/gh/googleapis/node-gtoken/branch/master/graph/badge.svg +[codecov-url]: https://codecov.io/gh/googleapis/node-gtoken +[gdevconsole]: https://console.developers.google.com +[gts-image]: https://img.shields.io/badge/code%20style-google-blueviolet.svg +[gts-url]: https://www.npmjs.com/package/gts +[npm-image]: https://img.shields.io/npm/v/gtoken.svg +[npm-url]: https://npmjs.org/package/gtoken +[snyk-image]: https://snyk.io/test/github/googleapis/node-gtoken/badge.svg +[snyk-url]: https://snyk.io/test/github/googleapis/node-gtoken +[client-docs]: https://googleapis.dev/nodejs/gtoken/latest/ diff --git a/node_modules/gtoken/build/src/index.d.ts b/node_modules/gtoken/build/src/index.d.ts new file mode 100644 index 0000000..84f3a09 --- /dev/null +++ b/node_modules/gtoken/build/src/index.d.ts @@ -0,0 +1,90 @@ +/** + * Copyright 2018 Google LLC + * + * Distributed under MIT license. + * See file LICENSE for detail or copy at https://opensource.org/licenses/MIT + */ +export declare type GetTokenCallback = (err: Error | null, token?: TokenData) => void; +export interface Credentials { + privateKey: string; + clientEmail?: string; +} +export interface TokenData { + refresh_token?: string; + expires_in?: number; + access_token?: string; + token_type?: string; + id_token?: string; +} +export interface TokenOptions { + keyFile?: string; + key?: string; + email?: string; + iss?: string; + sub?: string; + scope?: string | string[]; + additionalClaims?: {}; +} +export interface GetTokenOptions { + forceRefresh?: boolean; +} +export declare class GoogleToken { + get accessToken(): string | undefined; + get idToken(): string | undefined; + get tokenType(): string | undefined; + get refreshToken(): string | undefined; + expiresAt?: number; + key?: string; + keyFile?: string; + iss?: string; + sub?: string; + scope?: string; + rawToken?: TokenData; + tokenExpires?: number; + email?: string; + additionalClaims?: {}; + /** + * Create a GoogleToken. + * + * @param options Configuration object. + */ + constructor(options?: TokenOptions); + /** + * Returns whether the token has expired. + * + * @return true if the token has expired, false otherwise. + */ + hasExpired(): boolean; + /** + * Returns a cached token or retrieves a new one from Google. + * + * @param callback The callback function. + */ + getToken(opts?: GetTokenOptions): Promise; + getToken(callback: GetTokenCallback, opts?: GetTokenOptions): void; + /** + * Given a keyFile, extract the key and client email if available + * @param keyFile Path to a json, pem, or p12 file that contains the key. + * @returns an object with privateKey and clientEmail properties + */ + getCredentials(keyFile: string): Promise; + private getTokenAsync; + private ensureEmail; + /** + * Revoke the token if one is set. + * + * @param callback The callback function. + */ + revokeToken(): Promise; + revokeToken(callback: (err?: Error) => void): void; + private revokeTokenAsync; + /** + * Configure the GoogleToken for re-use. + * @param {object} options Configuration object. + */ + private configure; + /** + * Request the token from Google. + */ + private requestToken; +} diff --git a/node_modules/gtoken/build/src/index.js b/node_modules/gtoken/build/src/index.js new file mode 100644 index 0000000..b766bcc --- /dev/null +++ b/node_modules/gtoken/build/src/index.js @@ -0,0 +1,234 @@ +"use strict"; +/** + * Copyright 2018 Google LLC + * + * Distributed under MIT license. + * See file LICENSE for detail or copy at https://opensource.org/licenses/MIT + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const fs = require("fs"); +const gaxios_1 = require("gaxios"); +const jws = require("jws"); +const mime = require("mime"); +const util_1 = require("util"); +const readFile = fs.readFile + ? util_1.promisify(fs.readFile) + : async () => { + // if running in the web-browser, fs.readFile may not have been shimmed. + throw new ErrorWithCode('use key rather than keyFile.', 'MISSING_CREDENTIALS'); + }; +const GOOGLE_TOKEN_URL = 'https://www.googleapis.com/oauth2/v4/token'; +const GOOGLE_REVOKE_TOKEN_URL = 'https://accounts.google.com/o/oauth2/revoke?token='; +class ErrorWithCode extends Error { + constructor(message, code) { + super(message); + this.code = code; + } +} +let getPem; +class GoogleToken { + /** + * Create a GoogleToken. + * + * @param options Configuration object. + */ + constructor(options) { + this.configure(options); + } + get accessToken() { + return this.rawToken ? this.rawToken.access_token : undefined; + } + get idToken() { + return this.rawToken ? this.rawToken.id_token : undefined; + } + get tokenType() { + return this.rawToken ? this.rawToken.token_type : undefined; + } + get refreshToken() { + return this.rawToken ? this.rawToken.refresh_token : undefined; + } + /** + * Returns whether the token has expired. + * + * @return true if the token has expired, false otherwise. + */ + hasExpired() { + const now = new Date().getTime(); + if (this.rawToken && this.expiresAt) { + return now >= this.expiresAt; + } + else { + return true; + } + } + getToken(callback, opts = {}) { + if (typeof callback === 'object') { + opts = callback; + callback = undefined; + } + opts = Object.assign({ + forceRefresh: false, + }, opts); + if (callback) { + const cb = callback; + this.getTokenAsync(opts).then(t => cb(null, t), callback); + return; + } + return this.getTokenAsync(opts); + } + /** + * Given a keyFile, extract the key and client email if available + * @param keyFile Path to a json, pem, or p12 file that contains the key. + * @returns an object with privateKey and clientEmail properties + */ + async getCredentials(keyFile) { + const mimeType = mime.getType(keyFile); + switch (mimeType) { + case 'application/json': { + // *.json file + const key = await readFile(keyFile, 'utf8'); + const body = JSON.parse(key); + const privateKey = body.private_key; + const clientEmail = body.client_email; + if (!privateKey || !clientEmail) { + throw new ErrorWithCode('private_key and client_email are required.', 'MISSING_CREDENTIALS'); + } + return { privateKey, clientEmail }; + } + case 'application/x-x509-ca-cert': { + // *.pem file + const privateKey = await readFile(keyFile, 'utf8'); + return { privateKey }; + } + case 'application/x-pkcs12': { + // *.p12 file + // NOTE: The loading of `google-p12-pem` is deferred for performance + // reasons. The `node-forge` npm module in `google-p12-pem` adds a fair + // bit time to overall module loading, and is likely not frequently + // used. In a future release, p12 support will be entirely removed. + if (!getPem) { + getPem = (await Promise.resolve().then(() => require('google-p12-pem'))).getPem; + } + const privateKey = await getPem(keyFile); + return { privateKey }; + } + default: + throw new ErrorWithCode('Unknown certificate type. Type is determined based on file extension. ' + + 'Current supported extensions are *.json, *.pem, and *.p12.', 'UNKNOWN_CERTIFICATE_TYPE'); + } + } + async getTokenAsync(opts) { + if (this.hasExpired() === false && opts.forceRefresh === false) { + return Promise.resolve(this.rawToken); + } + if (!this.key && !this.keyFile) { + throw new Error('No key or keyFile set.'); + } + if (!this.key && this.keyFile) { + const creds = await this.getCredentials(this.keyFile); + this.key = creds.privateKey; + this.iss = creds.clientEmail || this.iss; + if (!creds.clientEmail) { + this.ensureEmail(); + } + } + return this.requestToken(); + } + ensureEmail() { + if (!this.iss) { + throw new ErrorWithCode('email is required.', 'MISSING_CREDENTIALS'); + } + } + revokeToken(callback) { + if (callback) { + this.revokeTokenAsync().then(() => callback(), callback); + return; + } + return this.revokeTokenAsync(); + } + async revokeTokenAsync() { + if (!this.accessToken) { + throw new Error('No token to revoke.'); + } + const url = GOOGLE_REVOKE_TOKEN_URL + this.accessToken; + await gaxios_1.request({ url }); + this.configure({ + email: this.iss, + sub: this.sub, + key: this.key, + keyFile: this.keyFile, + scope: this.scope, + additionalClaims: this.additionalClaims, + }); + } + /** + * Configure the GoogleToken for re-use. + * @param {object} options Configuration object. + */ + configure(options = {}) { + this.keyFile = options.keyFile; + this.key = options.key; + this.rawToken = undefined; + this.iss = options.email || options.iss; + this.sub = options.sub; + this.additionalClaims = options.additionalClaims; + if (typeof options.scope === 'object') { + this.scope = options.scope.join(' '); + } + else { + this.scope = options.scope; + } + } + /** + * Request the token from Google. + */ + async requestToken() { + const iat = Math.floor(new Date().getTime() / 1000); + const additionalClaims = this.additionalClaims || {}; + const payload = Object.assign({ + iss: this.iss, + scope: this.scope, + aud: GOOGLE_TOKEN_URL, + exp: iat + 3600, + iat, + sub: this.sub, + }, additionalClaims); + const signedJWT = jws.sign({ + header: { alg: 'RS256' }, + payload, + secret: this.key, + }); + try { + const r = await gaxios_1.request({ + method: 'POST', + url: GOOGLE_TOKEN_URL, + data: { + grant_type: 'urn:ietf:params:oauth:grant-type:jwt-bearer', + assertion: signedJWT, + }, + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + responseType: 'json', + }); + this.rawToken = r.data; + this.expiresAt = + r.data.expires_in === null || r.data.expires_in === undefined + ? undefined + : (iat + r.data.expires_in) * 1000; + return this.rawToken; + } + catch (e) { + this.rawToken = undefined; + this.tokenExpires = undefined; + const body = e.response && e.response.data ? e.response.data : {}; + if (body.error) { + const desc = body.error_description + ? `: ${body.error_description}` + : ''; + e.message = `${body.error}${desc}`; + } + throw e; + } + } +} +exports.GoogleToken = GoogleToken; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/gtoken/node_modules/gaxios/CHANGELOG.md b/node_modules/gtoken/node_modules/gaxios/CHANGELOG.md new file mode 100644 index 0000000..9bd3242 --- /dev/null +++ b/node_modules/gtoken/node_modules/gaxios/CHANGELOG.md @@ -0,0 +1,87 @@ +# Changelog + +### [2.3.2](https://www.github.com/googleapis/gaxios/compare/v2.3.1...v2.3.2) (2020-02-28) + + +### Bug Fixes + +* update github repo in package ([#239](https://www.github.com/googleapis/gaxios/issues/239)) ([7e750cb](https://www.github.com/googleapis/gaxios/commit/7e750cbaaa59812817d725c74fb9d364c4b71096)) + +### [2.3.1](https://www.github.com/googleapis/gaxios/compare/v2.3.0...v2.3.1) (2020-02-13) + + +### Bug Fixes + +* **deps:** update dependency https-proxy-agent to v5 ([#233](https://www.github.com/googleapis/gaxios/issues/233)) ([56de0a8](https://www.github.com/googleapis/gaxios/commit/56de0a824a2f9622e3e4d4bdd41adccd812a30b4)) + +## [2.3.0](https://www.github.com/googleapis/gaxios/compare/v2.2.2...v2.3.0) (2020-01-31) + + +### Features + +* add promise support for onRetryAttempt and shouldRetry ([#223](https://www.github.com/googleapis/gaxios/issues/223)) ([061afa3](https://www.github.com/googleapis/gaxios/commit/061afa381a51d39823e63accf3dacd16e191f3b9)) + +### [2.2.2](https://www.github.com/googleapis/gaxios/compare/v2.2.1...v2.2.2) (2020-01-08) + + +### Bug Fixes + +* **build:** add publication configuration ([#218](https://www.github.com/googleapis/gaxios/issues/218)) ([43e581f](https://www.github.com/googleapis/gaxios/commit/43e581ff4ed5e79d72f6f29748a5eebb6bff1229)) + +### [2.2.1](https://www.github.com/googleapis/gaxios/compare/v2.2.0...v2.2.1) (2020-01-04) + + +### Bug Fixes + +* **deps:** update dependency https-proxy-agent to v4 ([#201](https://www.github.com/googleapis/gaxios/issues/201)) ([5cdeef2](https://www.github.com/googleapis/gaxios/commit/5cdeef288a0c5c544c0dc2659aafbb2215d06c4b)) +* remove retryDelay option ([#203](https://www.github.com/googleapis/gaxios/issues/203)) ([d21e08d](https://www.github.com/googleapis/gaxios/commit/d21e08d2aada980d39bc5ca7093d54452be2d646)) + +## [2.2.0](https://www.github.com/googleapis/gaxios/compare/v2.1.1...v2.2.0) (2019-12-05) + + +### Features + +* populate GaxiosResponse with raw response information (res.url) ([#189](https://www.github.com/googleapis/gaxios/issues/189)) ([53a7f54](https://www.github.com/googleapis/gaxios/commit/53a7f54cc0f20320d7a6a21a9a9f36050cec2eec)) + + +### Bug Fixes + +* don't retry a request that is aborted intentionally ([#190](https://www.github.com/googleapis/gaxios/issues/190)) ([ba9777b](https://www.github.com/googleapis/gaxios/commit/ba9777b15b5262f8288a8bb3cca49a1de8427d8e)) +* **deps:** pin TypeScript below 3.7.0 ([5373f07](https://www.github.com/googleapis/gaxios/commit/5373f0793a765965a8221ecad2f99257ed1b7444)) + +### [2.1.1](https://www.github.com/googleapis/gaxios/compare/v2.1.0...v2.1.1) (2019-11-15) + + +### Bug Fixes + +* **docs:** snippets are now replaced in jsdoc comments ([#183](https://www.github.com/googleapis/gaxios/issues/183)) ([8dd1324](https://www.github.com/googleapis/gaxios/commit/8dd1324256590bd2f2e9015c813950e1cd8cb330)) + +## [2.1.0](https://www.github.com/googleapis/gaxios/compare/v2.0.3...v2.1.0) (2019-10-09) + + +### Bug Fixes + +* **deps:** update dependency https-proxy-agent to v3 ([#172](https://www.github.com/googleapis/gaxios/issues/172)) ([4a38f35](https://www.github.com/googleapis/gaxios/commit/4a38f35)) + + +### Features + +* **TypeScript:** agent can now be passed as builder method, rather than agent instance ([c84ddd6](https://www.github.com/googleapis/gaxios/commit/c84ddd6)) + +### [2.0.3](https://www.github.com/googleapis/gaxios/compare/v2.0.2...v2.0.3) (2019-09-11) + + +### Bug Fixes + +* do not override content-type if its given ([#158](https://www.github.com/googleapis/gaxios/issues/158)) ([f49e0e6](https://www.github.com/googleapis/gaxios/commit/f49e0e6)) +* improve stream detection logic ([6c41537](https://www.github.com/googleapis/gaxios/commit/6c41537)) +* revert header change ([#161](https://www.github.com/googleapis/gaxios/issues/161)) ([b0f6a8b](https://www.github.com/googleapis/gaxios/commit/b0f6a8b)) + +### [2.0.2](https://www.github.com/googleapis/gaxios/compare/v2.0.1...v2.0.2) (2019-07-23) + + +### Bug Fixes + +* check for existence of fetch before using it ([#138](https://www.github.com/googleapis/gaxios/issues/138)) ([79eb58d](https://www.github.com/googleapis/gaxios/commit/79eb58d)) +* **docs:** make anchors work in jsdoc ([#139](https://www.github.com/googleapis/gaxios/issues/139)) ([85103bb](https://www.github.com/googleapis/gaxios/commit/85103bb)) +* prevent double option processing ([#142](https://www.github.com/googleapis/gaxios/issues/142)) ([19b4b3c](https://www.github.com/googleapis/gaxios/commit/19b4b3c)) diff --git a/node_modules/gtoken/node_modules/gaxios/LICENSE b/node_modules/gtoken/node_modules/gaxios/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/node_modules/gtoken/node_modules/gaxios/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. 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 and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/gtoken/node_modules/gaxios/README.md b/node_modules/gtoken/node_modules/gaxios/README.md new file mode 100644 index 0000000..a25f3bd --- /dev/null +++ b/node_modules/gtoken/node_modules/gaxios/README.md @@ -0,0 +1,138 @@ +# gaxios + +[![npm version](https://img.shields.io/npm/v/gaxios.svg)](https://www.npmjs.org/package/gaxios) +[![codecov](https://codecov.io/gh/googleapis/gaxios/branch/master/graph/badge.svg)](https://codecov.io/gh/googleapis/gaxios) +[![Code Style: Google](https://img.shields.io/badge/code%20style-google-blueviolet.svg)](https://github.com/google/gts) + +> An HTTP request client that provides an `axios` like interface over top of `node-fetch`. + +## Install +```sh +$ npm install gaxios +``` + +## Example + +```js +const {request} = require('gaxios'); +const res = await request({ + url: 'https://www.googleapis.com/discovery/v1/apis/' +}); +``` + +## Setting Defaults +Gaxios supports setting default properties both on the default instance, and on additional instances. This is often useful when making many requests to the same domain with the same base settings. For example: + +```js +const gaxios = require('gaxios'); +gaxios.instance.defaults = { + baseURL: 'https://example.com' + headers: { + Authorization: 'SOME_TOKEN' + } +} +gaxios.request({url: '/data'}).then(...); +``` + +## Request Options + +```js +{ + // The url to which the request should be sent. Required. + url: string, + + // The HTTP method to use for the request. Defaults to `GET`. + method: 'GET', + + // The base Url to use for the request. Prepended to the `url` property above. + baseURL: 'https://example.com'; + + // The HTTP methods to be sent with the request. + headers: { 'some': 'header' }, + + // The data to send in the body of the request. Data objects will be serialized as JSON. + data: { + some: 'data' + }, + + // The max size of the http response content in bytes allowed. + // Defaults to `0`, which is the same as unset. + maxContentLength: 2000, + + // The max number of HTTP redirects to follow. + // Defaults to 100. + maxRedirects: 100, + + // The querystring parameters that will be encoded using `qs` and + // appended to the url + params: { + querystring: 'parameters' + }, + + // By default, we use the `querystring` package in node core to serialize + // querystring parameters. You can override that and provide your + // own implementation. + paramsSerializer: (params) => { + return qs.stringify(params); + }, + + // The timeout for the HTTP request. Defaults to 0. + timeout: 1000, + + // Optional method to override making the actual HTTP request. Useful + // for writing tests. + adapter?: (options) => { + return { + data: 'your data' + } + }; + + // The expected return type of the request. Options are: + // json | stream | blob | arraybuffer | text + // Defaults to `json`. + responseType: 'json', + + // The node.js http agent to use for the request. + agent: someHttpsAgent, + + // Custom function to determine if the response is valid based on the + // status code. Defaults to (>= 200 && < 300) + validateStatus: (status: number) => true, + + // Configuration for retrying of requests. + retryConfig: { + // The number of times to retry the request. Defaults to 3. + retry?: number; + + // The number of retries already attempted. + currentRetryAttempt?: number; + + // The HTTP Methods that will be automatically retried. + // Defaults to ['GET','PUT','HEAD','OPTIONS','DELETE'] + httpMethodsToRetry?: string[]; + + // The HTTP response status codes that will automatically be retried. + // Defaults to: [[100, 199], [429, 429], [500, 599]] + statusCodesToRetry?: number[][]; + + // Function to invoke when a retry attempt is made. + onRetryAttempt?: (err: GaxiosError) => Promise | void; + + // Function to invoke which determines if you should retry + shouldRetry?: (err: GaxiosError) => Promise | boolean; + + // When there is no response, the number of retries to attempt. Defaults to 2. + noResponseRetries?: number; + }, + + // Enables default configuration for retries. + retry: boolean, + + // Cancelling a request requires the `abort-controller` library. + // See https://github.com/bitinn/node-fetch#request-cancellation-with-abortsignal + signal?: AbortSignal +} +``` + +## License +[Apache-2.0](https://github.com/googleapis/gaxios/blob/master/LICENSE) diff --git a/node_modules/gtoken/node_modules/gaxios/build/src/common.d.ts b/node_modules/gtoken/node_modules/gaxios/build/src/common.d.ts new file mode 100644 index 0000000..f6635b2 --- /dev/null +++ b/node_modules/gtoken/node_modules/gaxios/build/src/common.d.ts @@ -0,0 +1,104 @@ +/// +import { AbortSignal } from 'abort-controller'; +import { Agent } from 'http'; +import { URL } from 'url'; +export declare class GaxiosError extends Error { + code?: string; + response?: GaxiosResponse; + config: GaxiosOptions; + constructor(message: string, options: GaxiosOptions, response: GaxiosResponse); +} +export interface Headers { + [index: string]: any; +} +export declare type GaxiosPromise = Promise>; +export interface GaxiosXMLHttpRequest { + responseURL: string; +} +export interface GaxiosResponse { + config: GaxiosOptions; + data: T; + status: number; + statusText: string; + headers: Headers; + request: GaxiosXMLHttpRequest; +} +/** + * Request options that are used to form the request. + */ +export interface GaxiosOptions { + /** + * Optional method to override making the actual HTTP request. Useful + * for writing tests. + */ + adapter?: (options: GaxiosOptions) => GaxiosPromise; + url?: string; + baseUrl?: string; + baseURL?: string; + method?: 'GET' | 'HEAD' | 'POST' | 'DELETE' | 'PUT' | 'CONNECT' | 'OPTIONS' | 'TRACE' | 'PATCH'; + headers?: Headers; + data?: any; + body?: any; + /** + * The maximum size of the http response content in bytes allowed. + */ + maxContentLength?: number; + /** + * The maximum number of redirects to follow. Defaults to 20. + */ + maxRedirects?: number; + follow?: number; + params?: any; + paramsSerializer?: (params: { + [index: string]: string | number; + }) => string; + timeout?: number; + onUploadProgress?: (progressEvent: any) => void; + responseType?: 'arraybuffer' | 'blob' | 'json' | 'text' | 'stream'; + agent?: Agent | ((parsedUrl: URL) => Agent); + validateStatus?: (status: number) => boolean; + retryConfig?: RetryConfig; + retry?: boolean; + signal?: AbortSignal; + size?: number; +} +/** + * Configuration for the Gaxios `request` method. + */ +export interface RetryConfig { + /** + * The number of times to retry the request. Defaults to 3. + */ + retry?: number; + /** + * The number of retries already attempted. + */ + currentRetryAttempt?: number; + /** + * The amount of time to initially delay the retry. Defaults to 100. + * @deprecated + */ + retryDelay?: number; + /** + * The HTTP Methods that will be automatically retried. + * Defaults to ['GET','PUT','HEAD','OPTIONS','DELETE'] + */ + httpMethodsToRetry?: string[]; + /** + * The HTTP response status codes that will automatically be retried. + * Defaults to: [[100, 199], [429, 429], [500, 599]] + */ + statusCodesToRetry?: number[][]; + /** + * Function to invoke when a retry attempt is made. + */ + onRetryAttempt?: (err: GaxiosError) => Promise | void; + /** + * Function to invoke which determines if you should retry + */ + shouldRetry?: (err: GaxiosError) => Promise | boolean; + /** + * When there is no response, the number of retries to attempt. Defaults to 2. + */ + noResponseRetries?: number; +} diff --git a/node_modules/gtoken/node_modules/gaxios/build/src/common.js b/node_modules/gtoken/node_modules/gaxios/build/src/common.js new file mode 100644 index 0000000..b9c5a57 --- /dev/null +++ b/node_modules/gtoken/node_modules/gaxios/build/src/common.js @@ -0,0 +1,25 @@ +"use strict"; +// Copyright 2018 Google LLC +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +// tslint:disable no-any +class GaxiosError extends Error { + constructor(message, options, response) { + super(message); + this.response = response; + this.config = options; + this.code = response.status.toString(); + } +} +exports.GaxiosError = GaxiosError; +//# sourceMappingURL=common.js.map \ No newline at end of file diff --git a/node_modules/gtoken/node_modules/gaxios/build/src/common.js.map b/node_modules/gtoken/node_modules/gaxios/build/src/common.js.map new file mode 100644 index 0000000..711ef63 --- /dev/null +++ b/node_modules/gtoken/node_modules/gaxios/build/src/common.js.map @@ -0,0 +1 @@ +{"version":3,"file":"common.js","sourceRoot":"","sources":["../../src/common.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,gDAAgD;AAChD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;AAMjC,wBAAwB;AAExB,MAAa,WAAqB,SAAQ,KAAK;IAI7C,YACE,OAAe,EACf,OAAsB,EACtB,QAA2B;QAE3B,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,IAAI,CAAC,MAAM,GAAG,OAAO,CAAC;QACtB,IAAI,CAAC,IAAI,GAAG,QAAQ,CAAC,MAAM,CAAC,QAAQ,EAAE,CAAC;IACzC,CAAC;CACF;AAdD,kCAcC"} \ No newline at end of file diff --git a/node_modules/gtoken/node_modules/gaxios/build/src/gaxios.d.ts b/node_modules/gtoken/node_modules/gaxios/build/src/gaxios.d.ts new file mode 100644 index 0000000..46b112a --- /dev/null +++ b/node_modules/gtoken/node_modules/gaxios/build/src/gaxios.d.ts @@ -0,0 +1,40 @@ +import { GaxiosOptions, GaxiosPromise } from './common'; +export declare class Gaxios { + private agentCache; + /** + * Default HTTP options that will be used for every HTTP request. + */ + defaults: GaxiosOptions; + /** + * The Gaxios class is responsible for making HTTP requests. + * @param defaults The default set of options to be used for this instance. + */ + constructor(defaults?: GaxiosOptions); + /** + * Perform an HTTP request with the given options. + * @param opts Set of HTTP options that will be used for this HTTP request. + */ + request(opts?: GaxiosOptions): GaxiosPromise; + /** + * Internal, retryable version of the `request` method. + * @param opts Set of HTTP options that will be used for this HTTP request. + */ + private _request; + private getResponseData; + /** + * Validates the options, and merges them with defaults. + * @param opts The original options passed from the client. + */ + private validateOpts; + /** + * By default, throw for any non-2xx status code + * @param status status code from the HTTP response + */ + private validateStatus; + /** + * Encode a set of key/value pars into a querystring format (?foo=bar&baz=boo) + * @param params key value pars to encode + */ + private paramsSerializer; + private translateResponse; +} diff --git a/node_modules/gtoken/node_modules/gaxios/build/src/gaxios.js b/node_modules/gtoken/node_modules/gaxios/build/src/gaxios.js new file mode 100644 index 0000000..4029ebd --- /dev/null +++ b/node_modules/gtoken/node_modules/gaxios/build/src/gaxios.js @@ -0,0 +1,224 @@ +"use strict"; +// Copyright 2018 Google LLC +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const extend_1 = __importDefault(require("extend")); +const node_fetch_1 = __importDefault(require("node-fetch")); +const querystring_1 = __importDefault(require("querystring")); +const is_stream_1 = __importDefault(require("is-stream")); +const url_1 = __importDefault(require("url")); +const common_1 = require("./common"); +const retry_1 = require("./retry"); +// tslint:disable no-any +const URL = hasURL() ? window.URL : url_1.default.URL; +const fetch = hasFetch() ? window.fetch : node_fetch_1.default; +function hasWindow() { + return typeof window !== 'undefined' && !!window; +} +function hasURL() { + return hasWindow() && !!window.URL; +} +function hasFetch() { + return hasWindow() && !!window.fetch; +} +// tslint:disable-next-line variable-name +let HttpsProxyAgent; +// Figure out if we should be using a proxy. Only if it's required, load +// the https-proxy-agent module as it adds startup cost. +function loadProxy() { + const proxy = process.env.HTTPS_PROXY || + process.env.https_proxy || + process.env.HTTP_PROXY || + process.env.http_proxy; + if (proxy) { + HttpsProxyAgent = require('https-proxy-agent'); + } + return proxy; +} +loadProxy(); +class Gaxios { + /** + * The Gaxios class is responsible for making HTTP requests. + * @param defaults The default set of options to be used for this instance. + */ + constructor(defaults) { + this.agentCache = new Map(); + this.defaults = defaults || {}; + } + /** + * Perform an HTTP request with the given options. + * @param opts Set of HTTP options that will be used for this HTTP request. + */ + async request(opts = {}) { + opts = this.validateOpts(opts); + return this._request(opts); + } + /** + * Internal, retryable version of the `request` method. + * @param opts Set of HTTP options that will be used for this HTTP request. + */ + async _request(opts = {}) { + try { + let translatedResponse; + if (opts.adapter) { + translatedResponse = await opts.adapter(opts); + } + else { + const res = await fetch(opts.url, opts); + const data = await this.getResponseData(opts, res); + translatedResponse = this.translateResponse(opts, res, data); + } + if (!opts.validateStatus(translatedResponse.status)) { + throw new common_1.GaxiosError(`Request failed with status code ${translatedResponse.status}`, opts, translatedResponse); + } + return translatedResponse; + } + catch (e) { + const err = e; + err.config = opts; + const { shouldRetry, config } = await retry_1.getRetryConfig(e); + if (shouldRetry && config) { + err.config.retryConfig.currentRetryAttempt = config.retryConfig.currentRetryAttempt; + return this._request(err.config); + } + throw err; + } + } + async getResponseData(opts, res) { + switch (opts.responseType) { + case 'stream': + return res.body; + case 'json': + let data = await res.text(); + try { + data = JSON.parse(data); + } + catch (e) { } + return data; + case 'arraybuffer': + return res.arrayBuffer(); + case 'blob': + return res.blob(); + default: + return res.text(); + } + } + /** + * Validates the options, and merges them with defaults. + * @param opts The original options passed from the client. + */ + validateOpts(options) { + const opts = extend_1.default(true, {}, this.defaults, options); + if (!opts.url) { + throw new Error('URL is required.'); + } + // baseUrl has been deprecated, remove in 2.0 + const baseUrl = opts.baseUrl || opts.baseURL; + if (baseUrl) { + opts.url = baseUrl + opts.url; + } + const parsedUrl = new URL(opts.url); + opts.url = `${parsedUrl.origin}${parsedUrl.pathname}`; + opts.params = extend_1.default(querystring_1.default.parse(parsedUrl.search.substr(1)), // removes leading ? + opts.params); + opts.paramsSerializer = opts.paramsSerializer || this.paramsSerializer; + if (opts.params) { + parsedUrl.search = opts.paramsSerializer(opts.params); + } + opts.url = parsedUrl.href; + if (typeof options.maxContentLength === 'number') { + opts.size = options.maxContentLength; + } + if (typeof options.maxRedirects === 'number') { + opts.follow = options.maxRedirects; + } + opts.headers = opts.headers || {}; + if (opts.data) { + if (is_stream_1.default.readable(opts.data)) { + opts.body = opts.data; + } + else if (typeof opts.data === 'object') { + opts.body = JSON.stringify(opts.data); + // Allow the user to specifiy their own content type, + // such as application/json-patch+json; for historical reasons this + // content type must currently be a json type, as we are relying on + // application/x-www-form-urlencoded (which is incompatible with + // upstream GCP APIs) being rewritten to application/json. + // + // TODO: refactor upstream dependencies to stop relying on this + // side-effect. + if (!opts.headers['Content-Type'] || + !opts.headers['Content-Type'].includes('json')) { + opts.headers['Content-Type'] = 'application/json'; + } + } + else { + opts.body = opts.data; + } + } + opts.validateStatus = opts.validateStatus || this.validateStatus; + opts.responseType = opts.responseType || 'json'; + if (!opts.headers['Accept'] && opts.responseType === 'json') { + opts.headers['Accept'] = 'application/json'; + } + opts.method = opts.method || 'GET'; + const proxy = loadProxy(); + if (proxy) { + if (this.agentCache.has(proxy)) { + opts.agent = this.agentCache.get(proxy); + } + else { + opts.agent = new HttpsProxyAgent(proxy); + this.agentCache.set(proxy, opts.agent); + } + } + return opts; + } + /** + * By default, throw for any non-2xx status code + * @param status status code from the HTTP response + */ + validateStatus(status) { + return status >= 200 && status < 300; + } + /** + * Encode a set of key/value pars into a querystring format (?foo=bar&baz=boo) + * @param params key value pars to encode + */ + paramsSerializer(params) { + return querystring_1.default.stringify(params); + } + translateResponse(opts, res, data) { + // headers need to be converted from a map to an obj + const headers = {}; + res.headers.forEach((value, key) => { + headers[key] = value; + }); + return { + config: opts, + data: data, + headers, + status: res.status, + statusText: res.statusText, + // XMLHttpRequestLike + request: { + responseURL: res.url, + }, + }; + } +} +exports.Gaxios = Gaxios; +//# sourceMappingURL=gaxios.js.map \ No newline at end of file diff --git a/node_modules/gtoken/node_modules/gaxios/build/src/gaxios.js.map b/node_modules/gtoken/node_modules/gaxios/build/src/gaxios.js.map new file mode 100644 index 0000000..9bd574f --- /dev/null +++ b/node_modules/gtoken/node_modules/gaxios/build/src/gaxios.js.map @@ -0,0 +1 @@ +{"version":3,"file":"gaxios.js","sourceRoot":"","sources":["../../src/gaxios.ts"],"names":[],"mappings":"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"} \ No newline at end of file diff --git a/node_modules/gtoken/node_modules/gaxios/build/src/index.d.ts b/node_modules/gtoken/node_modules/gaxios/build/src/index.d.ts new file mode 100644 index 0000000..033aff5 --- /dev/null +++ b/node_modules/gtoken/node_modules/gaxios/build/src/index.d.ts @@ -0,0 +1,14 @@ +import { GaxiosOptions } from './common'; +import { Gaxios } from './gaxios'; +export { GaxiosError, GaxiosPromise, GaxiosResponse, Headers, RetryConfig, } from './common'; +export { Gaxios, GaxiosOptions }; +/** + * The default instance used when the `request` method is directly + * invoked. + */ +export declare const instance: Gaxios; +/** + * Make an HTTP request using the given options. + * @param opts Options for the request + */ +export declare function request(opts: GaxiosOptions): Promise>; diff --git a/node_modules/gtoken/node_modules/gaxios/build/src/index.js b/node_modules/gtoken/node_modules/gaxios/build/src/index.js new file mode 100644 index 0000000..71c3ece --- /dev/null +++ b/node_modules/gtoken/node_modules/gaxios/build/src/index.js @@ -0,0 +1,32 @@ +"use strict"; +// Copyright 2018 Google LLC +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +const gaxios_1 = require("./gaxios"); +exports.Gaxios = gaxios_1.Gaxios; +var common_1 = require("./common"); +exports.GaxiosError = common_1.GaxiosError; +/** + * The default instance used when the `request` method is directly + * invoked. + */ +exports.instance = new gaxios_1.Gaxios(); +/** + * Make an HTTP request using the given options. + * @param opts Options for the request + */ +async function request(opts) { + return exports.instance.request(opts); +} +exports.request = request; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/gtoken/node_modules/gaxios/build/src/index.js.map b/node_modules/gtoken/node_modules/gaxios/build/src/index.js.map new file mode 100644 index 0000000..af85752 --- /dev/null +++ b/node_modules/gtoken/node_modules/gaxios/build/src/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA,4BAA4B;AAC5B,kEAAkE;AAClE,mEAAmE;AACnE,0CAA0C;AAC1C,EAAE;AACF,gDAAgD;AAChD,EAAE;AACF,sEAAsE;AACtE,oEAAoE;AACpE,2EAA2E;AAC3E,sEAAsE;AACtE,iCAAiC;;AAGjC,qCAAgC;AASxB,iBATA,eAAM,CASA;AAPd,mCAMkB;AALhB,+BAAA,WAAW,CAAA;AAQb;;;GAGG;AACU,QAAA,QAAQ,GAAG,IAAI,eAAM,EAAE,CAAC;AAErC;;;GAGG;AACI,KAAK,UAAU,OAAO,CAAI,IAAmB;IAClD,OAAO,gBAAQ,CAAC,OAAO,CAAI,IAAI,CAAC,CAAC;AACnC,CAAC;AAFD,0BAEC"} \ No newline at end of file diff --git a/node_modules/gtoken/node_modules/gaxios/build/src/retry.d.ts b/node_modules/gtoken/node_modules/gaxios/build/src/retry.d.ts new file mode 100644 index 0000000..cfc5ee2 --- /dev/null +++ b/node_modules/gtoken/node_modules/gaxios/build/src/retry.d.ts @@ -0,0 +1,8 @@ +import { GaxiosError } from './common'; +export declare function getRetryConfig(err: GaxiosError): Promise<{ + shouldRetry: boolean; + config?: undefined; +} | { + shouldRetry: boolean; + config: import("./common").GaxiosOptions; +}>; diff --git a/node_modules/gtoken/node_modules/gaxios/build/src/retry.js b/node_modules/gtoken/node_modules/gaxios/build/src/retry.js new file mode 100644 index 0000000..b25b9ad --- /dev/null +++ b/node_modules/gtoken/node_modules/gaxios/build/src/retry.js @@ -0,0 +1,132 @@ +"use strict"; +// Copyright 2018 Google LLC +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +Object.defineProperty(exports, "__esModule", { value: true }); +async function getRetryConfig(err) { + let config = getConfig(err); + if (!err || !err.config || (!config && !err.config.retry)) { + return { shouldRetry: false }; + } + config = config || {}; + config.currentRetryAttempt = config.currentRetryAttempt || 0; + config.retry = + config.retry === undefined || config.retry === null ? 3 : config.retry; + config.httpMethodsToRetry = config.httpMethodsToRetry || [ + 'GET', + 'HEAD', + 'PUT', + 'OPTIONS', + 'DELETE', + ]; + config.noResponseRetries = + config.noResponseRetries === undefined || config.noResponseRetries === null + ? 2 + : config.noResponseRetries; + // If this wasn't in the list of status codes where we want + // to automatically retry, return. + const retryRanges = [ + // https://en.wikipedia.org/wiki/List_of_HTTP_status_codes + // 1xx - Retry (Informational, request still processing) + // 2xx - Do not retry (Success) + // 3xx - Do not retry (Redirect) + // 4xx - Do not retry (Client errors) + // 429 - Retry ("Too Many Requests") + // 5xx - Retry (Server errors) + [100, 199], + [429, 429], + [500, 599], + ]; + config.statusCodesToRetry = config.statusCodesToRetry || retryRanges; + // Put the config back into the err + err.config.retryConfig = config; + // Determine if we should retry the request + const shouldRetryFn = config.shouldRetry || shouldRetryRequest; + if (!(await shouldRetryFn(err))) { + return { shouldRetry: false, config: err.config }; + } + // Calculate time to wait with exponential backoff. + // Formula: (2^c - 1 / 2) * 1000 + const delay = ((Math.pow(2, config.currentRetryAttempt) - 1) / 2) * 1000; + // We're going to retry! Incremenent the counter. + err.config.retryConfig.currentRetryAttempt += 1; + // Create a promise that invokes the retry after the backOffDelay + const backoff = new Promise(resolve => { + setTimeout(resolve, delay); + }); + // Notify the user if they added an `onRetryAttempt` handler + if (config.onRetryAttempt) { + config.onRetryAttempt(err); + } + // Return the promise in which recalls Gaxios to retry the request + await backoff; + return { shouldRetry: true, config: err.config }; +} +exports.getRetryConfig = getRetryConfig; +/** + * Determine based on config if we should retry the request. + * @param err The GaxiosError passed to the interceptor. + */ +function shouldRetryRequest(err) { + const config = getConfig(err); + // node-fetch raises an AbortError if signaled: + // https://github.com/bitinn/node-fetch#request-cancellation-with-abortsignal + if (err.name === 'AbortError') { + return false; + } + // If there's no config, or retries are disabled, return. + if (!config || config.retry === 0) { + return false; + } + // Check if this error has no response (ETIMEDOUT, ENOTFOUND, etc) + if (!err.response && + (config.currentRetryAttempt || 0) >= config.noResponseRetries) { + return false; + } + // Only retry with configured HttpMethods. + if (!err.config.method || + config.httpMethodsToRetry.indexOf(err.config.method.toUpperCase()) < 0) { + return false; + } + // If this wasn't in the list of status codes where we want + // to automatically retry, return. + if (err.response && err.response.status) { + let isInRange = false; + for (const [min, max] of config.statusCodesToRetry) { + const status = err.response.status; + if (status >= min && status <= max) { + isInRange = true; + break; + } + } + if (!isInRange) { + return false; + } + } + // If we are out of retry attempts, return + config.currentRetryAttempt = config.currentRetryAttempt || 0; + if (config.currentRetryAttempt >= config.retry) { + return false; + } + return true; +} +/** + * Acquire the raxConfig object from an GaxiosError if available. + * @param err The Gaxios error with a config object. + */ +function getConfig(err) { + if (err && err.config && err.config.retryConfig) { + return err.config.retryConfig; + } + return; +} +//# sourceMappingURL=retry.js.map \ No newline at end of file diff --git a/node_modules/gtoken/node_modules/gaxios/build/src/retry.js.map b/node_modules/gtoken/node_modules/gaxios/build/src/retry.js.map new file mode 100644 index 0000000..e90a53f --- /dev/null +++ b/node_modules/gtoken/node_modules/gaxios/build/src/retry.js.map @@ -0,0 +1 @@ +{"version":3,"file":"retry.js","sourceRoot":"","sources":["../../src/retry.ts"],"names":[],"mappings":"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"} \ No newline at end of file diff --git a/node_modules/gtoken/node_modules/gaxios/build/src/web.d.ts b/node_modules/gtoken/node_modules/gaxios/build/src/web.d.ts new file mode 100644 index 0000000..e69de29 diff --git a/node_modules/gtoken/node_modules/gaxios/build/src/web.js b/node_modules/gtoken/node_modules/gaxios/build/src/web.js new file mode 100644 index 0000000..0517f5d --- /dev/null +++ b/node_modules/gtoken/node_modules/gaxios/build/src/web.js @@ -0,0 +1,2 @@ +"use strict"; +//# sourceMappingURL=web.js.map \ No newline at end of file diff --git a/node_modules/gtoken/node_modules/gaxios/build/src/web.js.map b/node_modules/gtoken/node_modules/gaxios/build/src/web.js.map new file mode 100644 index 0000000..3677aca --- /dev/null +++ b/node_modules/gtoken/node_modules/gaxios/build/src/web.js.map @@ -0,0 +1 @@ +{"version":3,"file":"web.js","sourceRoot":"","sources":["../../src/web.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/gtoken/node_modules/gaxios/package.json b/node_modules/gtoken/node_modules/gaxios/package.json new file mode 100644 index 0000000..63e5afe --- /dev/null +++ b/node_modules/gtoken/node_modules/gaxios/package.json @@ -0,0 +1,130 @@ +{ + "_from": "gaxios@^2.1.0", + "_id": "gaxios@2.3.4", + "_inBundle": false, + "_integrity": "sha512-US8UMj8C5pRnao3Zykc4AAVr+cffoNKRTg9Rsf2GiuZCW69vgJj38VK2PzlPuQU73FZ/nTk9/Av6/JGcE1N9vA==", + "_location": "/gtoken/gaxios", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "gaxios@^2.1.0", + "name": "gaxios", + "escapedName": "gaxios", + "rawSpec": "^2.1.0", + "saveSpec": null, + "fetchSpec": "^2.1.0" + }, + "_requiredBy": [ + "/gtoken" + ], + "_resolved": "https://registry.npmjs.org/gaxios/-/gaxios-2.3.4.tgz", + "_shasum": "eea99353f341c270c5f3c29fc46b8ead56f0a173", + "_spec": "gaxios@^2.1.0", + "_where": "/Users/cday/Code/zendesk/fetch-build-from-gcb/node_modules/gtoken", + "author": { + "name": "Google, LLC" + }, + "bugs": { + "url": "https://github.com/googleapis/gaxios/issues" + }, + "bundleDependencies": false, + "dependencies": { + "abort-controller": "^3.0.0", + "extend": "^3.0.2", + "https-proxy-agent": "^5.0.0", + "is-stream": "^2.0.0", + "node-fetch": "^2.3.0" + }, + "deprecated": false, + "description": "A simple common HTTP client specifically for Google APIs and services.", + "devDependencies": { + "@compodoc/compodoc": "^1.1.9", + "@types/execa": "^0.9.0", + "@types/express": "^4.16.1", + "@types/extend": "^3.0.1", + "@types/mocha": "^7.0.0", + "@types/mv": "^2.1.0", + "@types/ncp": "^2.0.1", + "@types/nock": "^10.0.0", + "@types/node": "^11.9.5", + "@types/node-fetch": "^2.1.6", + "@types/sinon": "^7.0.7", + "@types/tmp": "0.1.0", + "assert-rejects": "^1.0.0", + "c8": "^7.0.0", + "codecov": "^3.2.0", + "execa": "^4.0.0", + "express": "^4.16.4", + "gts": "^1.0.0", + "is-docker": "^2.0.0", + "karma": "^4.0.0", + "karma-chrome-launcher": "^3.0.0", + "karma-coverage": "^2.0.0", + "karma-firefox-launcher": "^1.1.0", + "karma-mocha": "^1.3.0", + "karma-remap-coverage": "^0.1.5", + "karma-sourcemap-loader": "^0.3.7", + "karma-webpack": "^4.0.0", + "linkinator": "^2.0.0", + "mocha": "^7.0.0", + "mv": "^2.1.1", + "ncp": "^2.0.0", + "nock": "^12.0.0", + "null-loader": "^3.0.0", + "puppeteer": "^2.0.0", + "sinon": "^9.0.0", + "tmp": "0.1.0", + "ts-loader": "^6.0.0", + "typescript": "3.6.4", + "webpack": "^4.29.5", + "webpack-cli": "^3.2.3" + }, + "engines": { + "node": ">=8.10.0" + }, + "files": [ + "build/src" + ], + "homepage": "https://github.com/googleapis/gaxios#readme", + "keywords": [ + "google" + ], + "license": "Apache-2.0", + "main": "build/src/index.js", + "name": "gaxios", + "repository": { + "type": "git", + "url": "git+https://github.com/googleapis/gaxios.git" + }, + "scripts": { + "browser-test": "node build/browser-test/browser-test-runner.js", + "clean": "gts clean", + "compile": "tsc -p .", + "docs": "compodoc src/", + "docs-test": "linkinator docs", + "fix": "gts fix", + "lint": "gts check", + "prebrowser-test": "npm run compile", + "predocs-test": "npm run docs", + "prelint": "cd samples; npm link ../; npm i", + "prepare": "npm run compile", + "presystem-test": "npm run compile", + "pretest": "npm run compile", + "samples-test": "cd samples/ && npm link ../ && npm test && cd ../", + "system-test": "mocha build/system-test --timeout 40000", + "test": "c8 mocha build/test", + "webpack": "webpack" + }, + "types": "build/src/index.d.ts", + "version": "2.3.4", + "warnings": [ + { + "code": "ENOTSUP", + "required": { + "node": ">=8.10.0" + }, + "pkgid": "gaxios@2.3.4" + } + ] +} diff --git a/node_modules/gtoken/package.json b/node_modules/gtoken/package.json new file mode 100644 index 0000000..b54ed22 --- /dev/null +++ b/node_modules/gtoken/package.json @@ -0,0 +1,113 @@ +{ + "_from": "gtoken@^5.0.0", + "_id": "gtoken@5.0.0", + "_inBundle": false, + "_integrity": "sha512-+TM/Mn9fm2LsAA3bZVSlCG20b0KfDdF6IC/mV/rRWuIUAwvXd2aMCGFNf1ont1qFzJh0tznnfEyY8YLQ1awqdw==", + "_location": "/gtoken", + "_phantomChildren": { + "abort-controller": "3.0.0", + "extend": "3.0.2", + "https-proxy-agent": "5.0.0", + "is-stream": "2.0.0", + "node-fetch": "2.6.0" + }, + "_requested": { + "type": "range", + "registry": true, + "raw": "gtoken@^5.0.0", + "name": "gtoken", + "escapedName": "gtoken", + "rawSpec": "^5.0.0", + "saveSpec": null, + "fetchSpec": "^5.0.0" + }, + "_requiredBy": [ + "/google-auth-library" + ], + "_resolved": "https://registry.npmjs.org/gtoken/-/gtoken-5.0.0.tgz", + "_shasum": "3be5dcf23706343d8dfe4850a896f52b2172aef0", + "_spec": "gtoken@^5.0.0", + "_where": "/Users/cday/Code/zendesk/fetch-build-from-gcb/node_modules/google-auth-library", + "author": { + "name": "Google, LLC" + }, + "bugs": { + "url": "https://github.com/google/node-gtoken/issues" + }, + "bundleDependencies": false, + "dependencies": { + "gaxios": "^2.1.0", + "google-p12-pem": "^2.0.0", + "jws": "^4.0.0", + "mime": "^2.2.0" + }, + "deprecated": false, + "description": "Node.js Google Authentication Service Account Tokens", + "devDependencies": { + "@compodoc/compodoc": "^1.1.7", + "@types/jws": "^3.1.0", + "@types/mime": "^2.0.0", + "@types/mocha": "^7.0.0", + "@types/nock": "^10.0.0", + "@types/node": "^10.0.3", + "c8": "^7.0.0", + "codecov": "^3.0.2", + "gts": "^2.0.0-alpha.5", + "js-green-licenses": "^1.0.0", + "linkinator": "^2.0.0", + "mocha": "^7.0.0", + "nock": "^12.0.0", + "typescript": "^3.8.3" + }, + "engines": { + "node": ">=10" + }, + "files": [ + "build/src", + "!build/src/**/*.map" + ], + "homepage": "https://github.com/google/node-gtoken#readme", + "keywords": [ + "google", + "service", + "account", + "api", + "token", + "api", + "auth" + ], + "license": "MIT", + "main": "./build/src/index.js", + "name": "gtoken", + "repository": { + "type": "git", + "url": "git+https://github.com/google/node-gtoken.git" + }, + "scripts": { + "clean": "gts clean", + "compile": "tsc -p .", + "docs": "compodoc src/", + "docs-test": "linkinator docs", + "fix": "gts fix", + "lint": "gts check", + "predocs-test": "npm run docs", + "prelint": "cd samples; npm link ../; npm i", + "prepare": "npm run compile", + "presystem-test": "npm run compile", + "pretest": "npm run compile", + "samples-test": "cd samples/ && npm link ../ && npm test && cd ../", + "system-test": "mocha build/system-test", + "test": "c8 mocha build/test" + }, + "types": "./build/src/index.d.ts", + "version": "5.0.0", + "warnings": [ + { + "code": "ENOTSUP", + "required": { + "node": ">=10" + }, + "pkgid": "gtoken@5.0.0" + } + ] +} diff --git a/node_modules/https-proxy-agent/README.md b/node_modules/https-proxy-agent/README.md new file mode 100644 index 0000000..328656a --- /dev/null +++ b/node_modules/https-proxy-agent/README.md @@ -0,0 +1,137 @@ +https-proxy-agent +================ +### An HTTP(s) proxy `http.Agent` implementation for HTTPS +[![Build Status](https://github.com/TooTallNate/node-https-proxy-agent/workflows/Node%20CI/badge.svg)](https://github.com/TooTallNate/node-https-proxy-agent/actions?workflow=Node+CI) + +This module provides an `http.Agent` implementation that connects to a specified +HTTP or HTTPS proxy server, and can be used with the built-in `https` module. + +Specifically, this `Agent` implementation connects to an intermediary "proxy" +server and issues the [CONNECT HTTP method][CONNECT], which tells the proxy to +open a direct TCP connection to the destination server. + +Since this agent implements the CONNECT HTTP method, it also works with other +protocols that use this method when connecting over proxies (i.e. WebSockets). +See the "Examples" section below for more. + + +Installation +------------ + +Install with `npm`: + +``` bash +$ npm install https-proxy-agent +``` + + +Examples +-------- + +#### `https` module example + +``` js +var url = require('url'); +var https = require('https'); +var HttpsProxyAgent = require('https-proxy-agent'); + +// HTTP/HTTPS proxy to connect to +var proxy = process.env.http_proxy || 'http://168.63.76.32:3128'; +console.log('using proxy server %j', proxy); + +// HTTPS endpoint for the proxy to connect to +var endpoint = process.argv[2] || 'https://graph.facebook.com/tootallnate'; +console.log('attempting to GET %j', endpoint); +var options = url.parse(endpoint); + +// create an instance of the `HttpsProxyAgent` class with the proxy server information +var agent = new HttpsProxyAgent(proxy); +options.agent = agent; + +https.get(options, function (res) { + console.log('"response" event!', res.headers); + res.pipe(process.stdout); +}); +``` + +#### `ws` WebSocket connection example + +``` js +var url = require('url'); +var WebSocket = require('ws'); +var HttpsProxyAgent = require('https-proxy-agent'); + +// HTTP/HTTPS proxy to connect to +var proxy = process.env.http_proxy || 'http://168.63.76.32:3128'; +console.log('using proxy server %j', proxy); + +// WebSocket endpoint for the proxy to connect to +var endpoint = process.argv[2] || 'ws://echo.websocket.org'; +var parsed = url.parse(endpoint); +console.log('attempting to connect to WebSocket %j', endpoint); + +// create an instance of the `HttpsProxyAgent` class with the proxy server information +var options = url.parse(proxy); + +var agent = new HttpsProxyAgent(options); + +// finally, initiate the WebSocket connection +var socket = new WebSocket(endpoint, { agent: agent }); + +socket.on('open', function () { + console.log('"open" event!'); + socket.send('hello world'); +}); + +socket.on('message', function (data, flags) { + console.log('"message" event! %j %j', data, flags); + socket.close(); +}); +``` + +API +--- + +### new HttpsProxyAgent(Object options) + +The `HttpsProxyAgent` class implements an `http.Agent` subclass that connects +to the specified "HTTP(s) proxy server" in order to proxy HTTPS and/or WebSocket +requests. This is achieved by using the [HTTP `CONNECT` method][CONNECT]. + +The `options` argument may either be a string URI of the proxy server to use, or an +"options" object with more specific properties: + + * `host` - String - Proxy host to connect to (may use `hostname` as well). Required. + * `port` - Number - Proxy port to connect to. Required. + * `protocol` - String - If `https:`, then use TLS to connect to the proxy. + * `headers` - Object - Additional HTTP headers to be sent on the HTTP CONNECT method. + * Any other options given are passed to the `net.connect()`/`tls.connect()` functions. + + +License +------- + +(The MIT License) + +Copyright (c) 2013 Nathan Rajlich <nathan@tootallnate.net> + +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. + +[CONNECT]: http://en.wikipedia.org/wiki/HTTP_tunnel#HTTP_CONNECT_Tunneling diff --git a/node_modules/https-proxy-agent/dist/agent.d.ts b/node_modules/https-proxy-agent/dist/agent.d.ts new file mode 100644 index 0000000..4f1c636 --- /dev/null +++ b/node_modules/https-proxy-agent/dist/agent.d.ts @@ -0,0 +1,30 @@ +/// +import net from 'net'; +import { Agent, ClientRequest, RequestOptions } from 'agent-base'; +import { HttpsProxyAgentOptions } from '.'; +/** + * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to + * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. + * + * Outgoing HTTP requests are first tunneled through the proxy server using the + * `CONNECT` HTTP request method to establish a connection to the proxy server, + * and then the proxy server connects to the destination target and issues the + * HTTP request from the proxy server. + * + * `https:` requests have their socket connection upgraded to TLS once + * the connection to the proxy server has been established. + * + * @api public + */ +export default class HttpsProxyAgent extends Agent { + private secureProxy; + private proxy; + constructor(_opts: string | HttpsProxyAgentOptions); + /** + * Called when the node-core HTTP client library is creating a + * new HTTP request. + * + * @api protected + */ + callback(req: ClientRequest, opts: RequestOptions): Promise; +} diff --git a/node_modules/https-proxy-agent/dist/agent.js b/node_modules/https-proxy-agent/dist/agent.js new file mode 100644 index 0000000..d666525 --- /dev/null +++ b/node_modules/https-proxy-agent/dist/agent.js @@ -0,0 +1,180 @@ +"use strict"; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const net_1 = __importDefault(require("net")); +const tls_1 = __importDefault(require("tls")); +const url_1 = __importDefault(require("url")); +const assert_1 = __importDefault(require("assert")); +const debug_1 = __importDefault(require("debug")); +const agent_base_1 = require("agent-base"); +const parse_proxy_response_1 = __importDefault(require("./parse-proxy-response")); +const debug = debug_1.default('https-proxy-agent:agent'); +/** + * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to + * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. + * + * Outgoing HTTP requests are first tunneled through the proxy server using the + * `CONNECT` HTTP request method to establish a connection to the proxy server, + * and then the proxy server connects to the destination target and issues the + * HTTP request from the proxy server. + * + * `https:` requests have their socket connection upgraded to TLS once + * the connection to the proxy server has been established. + * + * @api public + */ +class HttpsProxyAgent extends agent_base_1.Agent { + constructor(_opts) { + let opts; + if (typeof _opts === 'string') { + opts = url_1.default.parse(_opts); + } + else { + opts = _opts; + } + if (!opts) { + throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!'); + } + debug('creating new HttpsProxyAgent instance: %o', opts); + super(opts); + const proxy = Object.assign({}, opts); + // If `true`, then connect to the proxy server over TLS. + // Defaults to `false`. + this.secureProxy = opts.secureProxy || isHTTPS(proxy.protocol); + // Prefer `hostname` over `host`, and set the `port` if needed. + proxy.host = proxy.hostname || proxy.host; + if (typeof proxy.port === 'string') { + proxy.port = parseInt(proxy.port, 10); + } + if (!proxy.port && proxy.host) { + proxy.port = this.secureProxy ? 443 : 80; + } + // ALPN is supported by Node.js >= v5. + // attempt to negotiate http/1.1 for proxy servers that support http/2 + if (this.secureProxy && !('ALPNProtocols' in proxy)) { + proxy.ALPNProtocols = ['http 1.1']; + } + if (proxy.host && proxy.path) { + // If both a `host` and `path` are specified then it's most likely + // the result of a `url.parse()` call... we need to remove the + // `path` portion so that `net.connect()` doesn't attempt to open + // that as a Unix socket file. + delete proxy.path; + delete proxy.pathname; + } + this.proxy = proxy; + } + /** + * Called when the node-core HTTP client library is creating a + * new HTTP request. + * + * @api protected + */ + callback(req, opts) { + return __awaiter(this, void 0, void 0, function* () { + const { proxy, secureProxy } = this; + // Create a socket connection to the proxy server. + let socket; + if (secureProxy) { + debug('Creating `tls.Socket`: %o', proxy); + socket = tls_1.default.connect(proxy); + } + else { + debug('Creating `net.Socket`: %o', proxy); + socket = net_1.default.connect(proxy); + } + const headers = Object.assign({}, proxy.headers); + const hostname = `${opts.host}:${opts.port}`; + let payload = `CONNECT ${hostname} HTTP/1.1\r\n`; + // Inject the `Proxy-Authorization` header if necessary. + if (proxy.auth) { + headers['Proxy-Authorization'] = `Basic ${Buffer.from(proxy.auth).toString('base64')}`; + } + // The `Host` header should only include the port + // number when it is not the default port. + let { host, port, secureEndpoint } = opts; + if (!isDefaultPort(port, secureEndpoint)) { + host += `:${port}`; + } + headers.Host = host; + headers.Connection = 'close'; + for (const name of Object.keys(headers)) { + payload += `${name}: ${headers[name]}\r\n`; + } + const proxyResponsePromise = parse_proxy_response_1.default(socket); + socket.write(`${payload}\r\n`); + const { statusCode, buffered } = yield proxyResponsePromise; + if (statusCode === 200) { + req.once('socket', resume); + if (opts.secureEndpoint) { + const servername = opts.servername || opts.host; + if (!servername) { + throw new Error('Could not determine "servername"'); + } + // The proxy is connecting to a TLS server, so upgrade + // this socket connection to a TLS connection. + debug('Upgrading socket connection to TLS'); + return tls_1.default.connect(Object.assign(Object.assign({}, omit(opts, 'host', 'hostname', 'path', 'port')), { socket, + servername })); + } + return socket; + } + // Some other status code that's not 200... need to re-play the HTTP + // header "data" events onto the socket once the HTTP machinery is + // attached so that the node core `http` can parse and handle the + // error status code. + // Close the original socket, and a new "fake" socket is returned + // instead, so that the proxy doesn't get the HTTP request + // written to it (which may contain `Authorization` headers or other + // sensitive data). + // + // See: https://hackerone.com/reports/541502 + socket.destroy(); + const fakeSocket = new net_1.default.Socket(); + fakeSocket.readable = true; + // Need to wait for the "socket" event to re-play the "data" events. + req.once('socket', (s) => { + debug('replaying proxy buffer for failed request'); + assert_1.default(s.listenerCount('data') > 0); + // Replay the "buffered" Buffer onto the fake `socket`, since at + // this point the HTTP module machinery has been hooked up for + // the user. + s.push(buffered); + s.push(null); + }); + return fakeSocket; + }); + } +} +exports.default = HttpsProxyAgent; +function resume(socket) { + socket.resume(); +} +function isDefaultPort(port, secure) { + return Boolean((!secure && port === 80) || (secure && port === 443)); +} +function isHTTPS(protocol) { + return typeof protocol === 'string' ? /^https:?$/i.test(protocol) : false; +} +function omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; + } + } + return ret; +} +//# sourceMappingURL=agent.js.map \ No newline at end of file diff --git a/node_modules/https-proxy-agent/dist/agent.js.map b/node_modules/https-proxy-agent/dist/agent.js.map new file mode 100644 index 0000000..d1307cd --- /dev/null +++ b/node_modules/https-proxy-agent/dist/agent.js.map @@ -0,0 +1 @@ +{"version":3,"file":"agent.js","sourceRoot":"","sources":["../src/agent.ts"],"names":[],"mappings":"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"} \ No newline at end of file diff --git a/node_modules/https-proxy-agent/dist/index.d.ts b/node_modules/https-proxy-agent/dist/index.d.ts new file mode 100644 index 0000000..0d60062 --- /dev/null +++ b/node_modules/https-proxy-agent/dist/index.d.ts @@ -0,0 +1,23 @@ +/// +import net from 'net'; +import tls from 'tls'; +import { Url } from 'url'; +import { AgentOptions } from 'agent-base'; +import { OutgoingHttpHeaders } from 'http'; +import _HttpsProxyAgent from './agent'; +declare function createHttpsProxyAgent(opts: string | createHttpsProxyAgent.HttpsProxyAgentOptions): _HttpsProxyAgent; +declare namespace createHttpsProxyAgent { + interface BaseHttpsProxyAgentOptions { + headers?: OutgoingHttpHeaders; + secureProxy?: boolean; + host?: string | null; + path?: string | null; + port?: string | number | null; + } + export interface HttpsProxyAgentOptions extends AgentOptions, BaseHttpsProxyAgentOptions, Partial> { + } + export type HttpsProxyAgent = _HttpsProxyAgent; + export const HttpsProxyAgent: typeof _HttpsProxyAgent; + export {}; +} +export = createHttpsProxyAgent; diff --git a/node_modules/https-proxy-agent/dist/index.js b/node_modules/https-proxy-agent/dist/index.js new file mode 100644 index 0000000..b03e763 --- /dev/null +++ b/node_modules/https-proxy-agent/dist/index.js @@ -0,0 +1,14 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +const agent_1 = __importDefault(require("./agent")); +function createHttpsProxyAgent(opts) { + return new agent_1.default(opts); +} +(function (createHttpsProxyAgent) { + createHttpsProxyAgent.HttpsProxyAgent = agent_1.default; + createHttpsProxyAgent.prototype = agent_1.default.prototype; +})(createHttpsProxyAgent || (createHttpsProxyAgent = {})); +module.exports = createHttpsProxyAgent; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/https-proxy-agent/dist/index.js.map b/node_modules/https-proxy-agent/dist/index.js.map new file mode 100644 index 0000000..f3ce559 --- /dev/null +++ b/node_modules/https-proxy-agent/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":";;;;AAKA,oDAAuC;AAEvC,SAAS,qBAAqB,CAC7B,IAA2D;IAE3D,OAAO,IAAI,eAAgB,CAAC,IAAI,CAAC,CAAC;AACnC,CAAC;AAED,WAAU,qBAAqB;IAoBjB,qCAAe,GAAG,eAAgB,CAAC;IAEhD,qBAAqB,CAAC,SAAS,GAAG,eAAgB,CAAC,SAAS,CAAC;AAC9D,CAAC,EAvBS,qBAAqB,KAArB,qBAAqB,QAuB9B;AAED,iBAAS,qBAAqB,CAAC"} \ No newline at end of file diff --git a/node_modules/https-proxy-agent/dist/parse-proxy-response.d.ts b/node_modules/https-proxy-agent/dist/parse-proxy-response.d.ts new file mode 100644 index 0000000..7565674 --- /dev/null +++ b/node_modules/https-proxy-agent/dist/parse-proxy-response.d.ts @@ -0,0 +1,7 @@ +/// +import { Readable } from 'stream'; +export interface ProxyResponse { + statusCode: number; + buffered: Buffer; +} +export default function parseProxyResponse(socket: Readable): Promise; diff --git a/node_modules/https-proxy-agent/dist/parse-proxy-response.js b/node_modules/https-proxy-agent/dist/parse-proxy-response.js new file mode 100644 index 0000000..aa5ce3c --- /dev/null +++ b/node_modules/https-proxy-agent/dist/parse-proxy-response.js @@ -0,0 +1,66 @@ +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +const debug_1 = __importDefault(require("debug")); +const debug = debug_1.default('https-proxy-agent:parse-proxy-response'); +function parseProxyResponse(socket) { + return new Promise((resolve, reject) => { + // we need to buffer any HTTP traffic that happens with the proxy before we get + // the CONNECT response, so that if the response is anything other than an "200" + // response code, then we can re-play the "data" events on the socket once the + // HTTP parser is hooked up... + let buffersLength = 0; + const buffers = []; + function read() { + const b = socket.read(); + if (b) + ondata(b); + else + socket.once('readable', read); + } + function cleanup() { + socket.removeListener('end', onend); + socket.removeListener('error', onerror); + socket.removeListener('close', onclose); + socket.removeListener('readable', read); + } + function onclose(err) { + debug('onclose had error %o', err); + } + function onend() { + debug('onend'); + } + function onerror(err) { + cleanup(); + debug('onerror %o', err); + reject(err); + } + function ondata(b) { + buffers.push(b); + buffersLength += b.length; + const buffered = Buffer.concat(buffers, buffersLength); + const endOfHeaders = buffered.indexOf('\r\n\r\n'); + if (endOfHeaders === -1) { + // keep buffering + debug('have not received end of HTTP headers yet...'); + read(); + return; + } + const firstLine = buffered.toString('ascii', 0, buffered.indexOf('\r\n')); + const statusCode = +firstLine.split(' ')[1]; + debug('got proxy server response: %o', firstLine); + resolve({ + statusCode, + buffered + }); + } + socket.on('error', onerror); + socket.on('close', onclose); + socket.on('end', onend); + read(); + }); +} +exports.default = parseProxyResponse; +//# sourceMappingURL=parse-proxy-response.js.map \ No newline at end of file diff --git a/node_modules/https-proxy-agent/dist/parse-proxy-response.js.map b/node_modules/https-proxy-agent/dist/parse-proxy-response.js.map new file mode 100644 index 0000000..bacdb84 --- /dev/null +++ b/node_modules/https-proxy-agent/dist/parse-proxy-response.js.map @@ -0,0 +1 @@ +{"version":3,"file":"parse-proxy-response.js","sourceRoot":"","sources":["../src/parse-proxy-response.ts"],"names":[],"mappings":";;;;;AAAA,kDAAgC;AAGhC,MAAM,KAAK,GAAG,eAAW,CAAC,wCAAwC,CAAC,CAAC;AAOpE,SAAwB,kBAAkB,CACzC,MAAgB;IAEhB,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,EAAE;QACtC,+EAA+E;QAC/E,gFAAgF;QAChF,8EAA8E;QAC9E,8BAA8B;QAC9B,IAAI,aAAa,GAAG,CAAC,CAAC;QACtB,MAAM,OAAO,GAAa,EAAE,CAAC;QAE7B,SAAS,IAAI;YACZ,MAAM,CAAC,GAAG,MAAM,CAAC,IAAI,EAAE,CAAC;YACxB,IAAI,CAAC;gBAAE,MAAM,CAAC,CAAC,CAAC,CAAC;;gBACZ,MAAM,CAAC,IAAI,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;QACpC,CAAC;QAED,SAAS,OAAO;YACf,MAAM,CAAC,cAAc,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;YACpC,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YACxC,MAAM,CAAC,cAAc,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;YACxC,MAAM,CAAC,cAAc,CAAC,UAAU,EAAE,IAAI,CAAC,CAAC;QACzC,CAAC;QAED,SAAS,OAAO,CAAC,GAAW;YAC3B,KAAK,CAAC,sBAAsB,EAAE,GAAG,CAAC,CAAC;QACpC,CAAC;QAED,SAAS,KAAK;YACb,KAAK,CAAC,OAAO,CAAC,CAAC;QAChB,CAAC;QAED,SAAS,OAAO,CAAC,GAAU;YAC1B,OAAO,EAAE,CAAC;YACV,KAAK,CAAC,YAAY,EAAE,GAAG,CAAC,CAAC;YACzB,MAAM,CAAC,GAAG,CAAC,CAAC;QACb,CAAC;QAED,SAAS,MAAM,CAAC,CAAS;YACxB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;YAChB,aAAa,IAAI,CAAC,CAAC,MAAM,CAAC;YAE1B,MAAM,QAAQ,GAAG,MAAM,CAAC,MAAM,CAAC,OAAO,EAAE,aAAa,CAAC,CAAC;YACvD,MAAM,YAAY,GAAG,QAAQ,CAAC,OAAO,CAAC,UAAU,CAAC,CAAC;YAElD,IAAI,YAAY,KAAK,CAAC,CAAC,EAAE;gBACxB,iBAAiB;gBACjB,KAAK,CAAC,8CAA8C,CAAC,CAAC;gBACtD,IAAI,EAAE,CAAC;gBACP,OAAO;aACP;YAED,MAAM,SAAS,GAAG,QAAQ,CAAC,QAAQ,CAClC,OAAO,EACP,CAAC,EACD,QAAQ,CAAC,OAAO,CAAC,MAAM,CAAC,CACxB,CAAC;YACF,MAAM,UAAU,GAAG,CAAC,SAAS,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC;YAC5C,KAAK,CAAC,+BAA+B,EAAE,SAAS,CAAC,CAAC;YAClD,OAAO,CAAC;gBACP,UAAU;gBACV,QAAQ;aACR,CAAC,CAAC;QACJ,CAAC;QAED,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAC5B,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,OAAO,CAAC,CAAC;QAC5B,MAAM,CAAC,EAAE,CAAC,KAAK,EAAE,KAAK,CAAC,CAAC;QAExB,IAAI,EAAE,CAAC;IACR,CAAC,CAAC,CAAC;AACJ,CAAC;AAvED,qCAuEC"} \ No newline at end of file diff --git a/node_modules/https-proxy-agent/package.json b/node_modules/https-proxy-agent/package.json new file mode 100644 index 0000000..f476369 --- /dev/null +++ b/node_modules/https-proxy-agent/package.json @@ -0,0 +1,88 @@ +{ + "_from": "https-proxy-agent@^5.0.0", + "_id": "https-proxy-agent@5.0.0", + "_inBundle": false, + "_integrity": "sha512-EkYm5BcKUGiduxzSt3Eppko+PiNWNEpa4ySk9vTC6wDsQJW9rHSa+UhGNJoRYp7bz6Ht1eaRIa6QaJqO5rCFbA==", + "_location": "/https-proxy-agent", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "https-proxy-agent@^5.0.0", + "name": "https-proxy-agent", + "escapedName": "https-proxy-agent", + "rawSpec": "^5.0.0", + "saveSpec": null, + "fetchSpec": "^5.0.0" + }, + "_requiredBy": [ + "/gaxios", + "/gcp-metadata/gaxios", + "/gtoken/gaxios" + ], + "_resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.0.tgz", + "_shasum": "e2a90542abb68a762e0a0850f6c9edadfd8506b2", + "_spec": "https-proxy-agent@^5.0.0", + "_where": "/Users/cday/Code/zendesk/fetch-build-from-gcb/node_modules/gaxios", + "author": { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net", + "url": "http://n8.io/" + }, + "bugs": { + "url": "https://github.com/TooTallNate/node-https-proxy-agent/issues" + }, + "bundleDependencies": false, + "dependencies": { + "agent-base": "6", + "debug": "4" + }, + "deprecated": false, + "description": "An HTTP(s) proxy `http.Agent` implementation for HTTPS", + "devDependencies": { + "@types/debug": "4", + "@types/node": "^12.12.11", + "@typescript-eslint/eslint-plugin": "1.6.0", + "@typescript-eslint/parser": "1.1.0", + "eslint": "5.16.0", + "eslint-config-airbnb": "17.1.0", + "eslint-config-prettier": "4.1.0", + "eslint-import-resolver-typescript": "1.1.1", + "eslint-plugin-import": "2.16.0", + "eslint-plugin-jsx-a11y": "6.2.1", + "eslint-plugin-react": "7.12.4", + "mocha": "^6.2.2", + "proxy": "1", + "rimraf": "^3.0.0", + "typescript": "^3.5.3" + }, + "engines": { + "node": ">= 6" + }, + "files": [ + "dist" + ], + "homepage": "https://github.com/TooTallNate/node-https-proxy-agent#readme", + "keywords": [ + "https", + "proxy", + "endpoint", + "agent" + ], + "license": "MIT", + "main": "dist/index", + "name": "https-proxy-agent", + "repository": { + "type": "git", + "url": "git://github.com/TooTallNate/node-https-proxy-agent.git" + }, + "scripts": { + "build": "tsc", + "prebuild": "rimraf dist", + "prepublishOnly": "npm run build", + "test": "mocha --reporter spec", + "test-lint": "eslint src --ext .js,.ts" + }, + "types": "dist/index", + "version": "5.0.0" +} diff --git a/node_modules/is-stream/index.d.ts b/node_modules/is-stream/index.d.ts new file mode 100644 index 0000000..b61027f --- /dev/null +++ b/node_modules/is-stream/index.d.ts @@ -0,0 +1,80 @@ +/// +import * as stream from 'stream'; + +declare const isStream: { + /** + @returns Whether `stream` is a [`Stream`](https://nodejs.org/api/stream.html#stream_stream). + + @example + ``` + import * as fs from 'fs'; + import isStream = require('is-stream'); + + isStream(fs.createReadStream('unicorn.png')); + //=> true + + isStream({}); + //=> false + ``` + */ + (stream: unknown): stream is stream.Stream; + + /** + @returns Whether `stream` is a [`stream.Writable`](https://nodejs.org/api/stream.html#stream_class_stream_writable). + + @example + ``` + import * as fs from 'fs'; + import isStream = require('is-stream'); + + isStream.writable(fs.createWriteStrem('unicorn.txt')); + //=> true + ``` + */ + writable(stream: unknown): stream is stream.Writable; + + /** + @returns Whether `stream` is a [`stream.Readable`](https://nodejs.org/api/stream.html#stream_class_stream_readable). + + @example + ``` + import * as fs from 'fs'; + import isStream = require('is-stream'); + + isStream.readable(fs.createReadStream('unicorn.png')); + //=> true + ``` + */ + readable(stream: unknown): stream is stream.Readable; + + /** + @returns Whether `stream` is a [`stream.Duplex`](https://nodejs.org/api/stream.html#stream_class_stream_duplex). + + @example + ``` + import {Duplex} from 'stream'; + import isStream = require('is-stream'); + + isStream.duplex(new Duplex()); + //=> true + ``` + */ + duplex(stream: unknown): stream is stream.Duplex; + + /** + @returns Whether `stream` is a [`stream.Transform`](https://nodejs.org/api/stream.html#stream_class_stream_transform). + + @example + ``` + import * as fs from 'fs'; + import Stringify = require('streaming-json-stringify'); + import isStream = require('is-stream'); + + isStream.transform(Stringify()); + //=> true + ``` + */ + transform(input: unknown): input is stream.Transform; +}; + +export = isStream; diff --git a/node_modules/is-stream/index.js b/node_modules/is-stream/index.js new file mode 100644 index 0000000..a8d571f --- /dev/null +++ b/node_modules/is-stream/index.js @@ -0,0 +1,29 @@ +'use strict'; + +const isStream = stream => + stream !== null && + typeof stream === 'object' && + typeof stream.pipe === 'function'; + +isStream.writable = stream => + isStream(stream) && + stream.writable !== false && + typeof stream._write === 'function' && + typeof stream._writableState === 'object'; + +isStream.readable = stream => + isStream(stream) && + stream.readable !== false && + typeof stream._read === 'function' && + typeof stream._readableState === 'object'; + +isStream.duplex = stream => + isStream.writable(stream) && + isStream.readable(stream); + +isStream.transform = stream => + isStream.duplex(stream) && + typeof stream._transform === 'function' && + typeof stream._transformState === 'object'; + +module.exports = isStream; diff --git a/node_modules/is-stream/license b/node_modules/is-stream/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/is-stream/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +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. diff --git a/node_modules/is-stream/package.json b/node_modules/is-stream/package.json new file mode 100644 index 0000000..b5f710d --- /dev/null +++ b/node_modules/is-stream/package.json @@ -0,0 +1,75 @@ +{ + "_from": "is-stream@^2.0.0", + "_id": "is-stream@2.0.0", + "_inBundle": false, + "_integrity": "sha512-XCoy+WlUr7d1+Z8GgSuXmpuUFC9fOhRXglJMx+dwLKTkL44Cjd4W1Z5P+BQZpr+cR93aGP4S/s7Ftw6Nd/kiEw==", + "_location": "/is-stream", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "is-stream@^2.0.0", + "name": "is-stream", + "escapedName": "is-stream", + "rawSpec": "^2.0.0", + "saveSpec": null, + "fetchSpec": "^2.0.0" + }, + "_requiredBy": [ + "/gaxios", + "/gcp-metadata/gaxios", + "/gtoken/gaxios" + ], + "_resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.0.tgz", + "_shasum": "bde9c32680d6fae04129d6ac9d921ce7815f78e3", + "_spec": "is-stream@^2.0.0", + "_where": "/Users/cday/Code/zendesk/fetch-build-from-gcb/node_modules/gaxios", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "bugs": { + "url": "https://github.com/sindresorhus/is-stream/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Check if something is a Node.js stream", + "devDependencies": { + "@types/node": "^11.13.6", + "ava": "^1.4.1", + "tempy": "^0.3.0", + "tsd": "^0.7.2", + "xo": "^0.24.0" + }, + "engines": { + "node": ">=8" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "homepage": "https://github.com/sindresorhus/is-stream#readme", + "keywords": [ + "stream", + "type", + "streams", + "writable", + "readable", + "duplex", + "transform", + "check", + "detect", + "is" + ], + "license": "MIT", + "name": "is-stream", + "repository": { + "type": "git", + "url": "git+https://github.com/sindresorhus/is-stream.git" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "version": "2.0.0" +} diff --git a/node_modules/is-stream/readme.md b/node_modules/is-stream/readme.md new file mode 100644 index 0000000..fdeadb9 --- /dev/null +++ b/node_modules/is-stream/readme.md @@ -0,0 +1,57 @@ +# is-stream [![Build Status](https://travis-ci.org/sindresorhus/is-stream.svg?branch=master)](https://travis-ci.org/sindresorhus/is-stream) + +> Check if something is a [Node.js stream](https://nodejs.org/api/stream.html) + + +## Install + +``` +$ npm install is-stream +``` + + +## Usage + +```js +const fs = require('fs'); +const isStream = require('is-stream'); + +isStream(fs.createReadStream('unicorn.png')); +//=> true + +isStream({}); +//=> false +``` + + +## API + +### isStream(stream) + +Returns a `boolean` for whether it's a [`Stream`](https://nodejs.org/api/stream.html#stream_stream). + +#### isStream.writable(stream) + +Returns a `boolean` for whether it's a [`stream.Writable`](https://nodejs.org/api/stream.html#stream_class_stream_writable). + +#### isStream.readable(stream) + +Returns a `boolean` for whether it's a [`stream.Readable`](https://nodejs.org/api/stream.html#stream_class_stream_readable). + +#### isStream.duplex(stream) + +Returns a `boolean` for whether it's a [`stream.Duplex`](https://nodejs.org/api/stream.html#stream_class_stream_duplex). + +#### isStream.transform(stream) + +Returns a `boolean` for whether it's a [`stream.Transform`](https://nodejs.org/api/stream.html#stream_class_stream_transform). + + +## Related + +- [is-file-stream](https://github.com/jamestalmage/is-file-stream) - Detect if a stream is a file stream + + +## License + +MIT © [Sindre Sorhus](https://sindresorhus.com) diff --git a/node_modules/json-bigint/.npmignore b/node_modules/json-bigint/.npmignore new file mode 100644 index 0000000..af4175f --- /dev/null +++ b/node_modules/json-bigint/.npmignore @@ -0,0 +1,16 @@ +lib-cov +*.seed +*.log +*.csv +*.dat +*.out +*.pid +*.gz +.*.swp +node_modules + +pids +logs +results + +npm-debug.log diff --git a/node_modules/json-bigint/.travis.yml b/node_modules/json-bigint/.travis.yml new file mode 100644 index 0000000..05d299e --- /dev/null +++ b/node_modules/json-bigint/.travis.yml @@ -0,0 +1,4 @@ +language: node_js +node_js: + - "0.10" + - "0.11" diff --git a/node_modules/json-bigint/LICENSE b/node_modules/json-bigint/LICENSE new file mode 100644 index 0000000..9ab4d83 --- /dev/null +++ b/node_modules/json-bigint/LICENSE @@ -0,0 +1,20 @@ +The MIT License (MIT) + +Copyright (c) 2013 Andrey Sidorov + +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. diff --git a/node_modules/json-bigint/README.md b/node_modules/json-bigint/README.md new file mode 100644 index 0000000..17421b8 --- /dev/null +++ b/node_modules/json-bigint/README.md @@ -0,0 +1,117 @@ +json-bigint +=========== + +[![Build Status](https://secure.travis-ci.org/sidorares/json-bigint.png)](http://travis-ci.org/sidorares/json-bigint) +[![NPM](https://nodei.co/npm/json-bigint.png?downloads=true&stars=true)](https://nodei.co/npm/json-bigint/) + +JSON.parse/stringify with bigints support. Based on Douglas Crockford [JSON.js](https://github.com/douglascrockford/JSON-js) package and [bignumber.js](https://github.com/MikeMcl/bignumber.js) library. + +While most JSON parsers assume numeric values have same precision restrictions as IEEE 754 double, JSON specification _does not_ say anything about number precision. Any floating point number in decimal (optionally scientific) notation is valid JSON value. It's a good idea to serialize values which might fall out of IEEE 754 integer precision as strings in your JSON api, but `{ "value" : 9223372036854775807}`, for example, is still a valid RFC4627 JSON string, and in most JS runtimes the result of `JSON.parse` is this object: `{ value: 9223372036854776000 }` + +========== + +example: + +```js +var JSONbig = require('json-bigint'); + +var json = '{ "value" : 9223372036854775807, "v2": 123 }'; +console.log('Input:', json); +console.log(''); + +console.log('node.js bult-in JSON:') +var r = JSON.parse(json); +console.log('JSON.parse(input).value : ', r.value.toString()); +console.log('JSON.stringify(JSON.parse(input)):', JSON.stringify(r)); + +console.log('\n\nbig number JSON:'); +var r1 = JSONbig.parse(json); +console.log('JSON.parse(input).value : ', r1.value.toString()); +console.log('JSON.stringify(JSON.parse(input)):', JSONbig.stringify(r1)); +``` + +Output: + +``` +Input: { "value" : 9223372036854775807, "v2": 123 } + +node.js bult-in JSON: +JSON.parse(input).value : 9223372036854776000 +JSON.stringify(JSON.parse(input)): {"value":9223372036854776000,"v2":123} + + +big number JSON: +JSON.parse(input).value : 9223372036854775807 +JSON.stringify(JSON.parse(input)): {"value":9223372036854775807,"v2":123} +``` +### Options +The behaviour of the parser is somewhat configurable through 'options' + +#### options.strict, boolean, default false +Specifies the parsing should be "strict" towards reporting duplicate-keys in the parsed string. +The default follows what is allowed in standard json and resembles the behavior of JSON.parse, but overwrites any previous values with the last one assigned to the duplicate-key. + +Setting options.strict = true will fail-fast on such duplicate-key occurances and thus warn you upfront of possible lost information. + +example: +```js +var JSONbig = require('json-bigint'); +var JSONstrict = require('json-bigint')({"strict": true}); + +var dupkeys = '{ "dupkey": "value 1", "dupkey": "value 2"}'; +console.log('\n\nDuplicate Key test with both lenient and strict JSON parsing'); +console.log('Input:', dupkeys); +var works = JSONbig.parse(dupkeys); +console.log('JSON.parse(dupkeys).dupkey: %s', works.dupkey); +var fails = "will stay like this"; +try { + fails = JSONstrict.parse(dupkeys); + console.log('ERROR!! Should never get here'); +} catch (e) { + console.log('Succesfully catched expected exception on duplicate keys: %j', e); +} +``` + +Output +``` +Duplicate Key test with big number JSON +Input: { "dupkey": "value 1", "dupkey": "value 2"} +JSON.parse(dupkeys).dupkey: value 2 +Succesfully catched expected exception on duplicate keys: {"name":"SyntaxError","message":"Duplicate key \"dupkey\"","at":33,"text":"{ \"dupkey\": \"value 1\", \"dupkey\": \"value 2\"}"} + +``` + +#### options.storeAsString, boolean, default false +Specifies if BigInts should be stored in the object as a string, rather than the default BigNumber. + +Note that this is a dangerous behavior as it breaks the default functionality of being able to convert back-and-forth without data type changes (as this will convert all BigInts to be-and-stay strings). + +example: +```js +var JSONbig = require('json-bigint'); +var JSONbigString = require('json-bigint')({"storeAsString": true}); +var key = '{ "key": 1234567890123456789 }'; +console.log('\n\nStoring the BigInt as a string, instead of a BigNumber'); +console.log('Input:', key); +var withInt = JSONbig.parse(key); +var withString = JSONbigString.parse(key); +console.log('Default type: %s, With option type: %s', typeof withInt.key, typeof withString.key); + +``` + +Output +``` +Storing the BigInt as a string, instead of a BigNumber +Input: { "key": 1234567890123456789 } +Default type: object, With option type: string + +``` + + +### Links: +- [RFC4627: The application/json Media Type for JavaScript Object Notation (JSON)](http://www.ietf.org/rfc/rfc4627.txt) +- [Re: \[Json\] Limitations on number size?](http://www.ietf.org/mail-archive/web/json/current/msg00297.html) +- [Is there any proper way to parse JSON with large numbers? (long, bigint, int64)](http://stackoverflow.com/questions/18755125/node-js-is-there-any-proper-way-to-parse-json-with-large-numbers-long-bigint) +- [What is JavaScript's Max Int? What's the highest Integer value a Number can go to without losing precision?](http://stackoverflow.com/questions/307179/what-is-javascripts-max-int-whats-the-highest-integer-value-a-number-can-go-t) +- [Large numbers erroneously rounded in Javascript](http://stackoverflow.com/questions/1379934/large-numbers-erroneously-rounded-in-javascript) + diff --git a/node_modules/json-bigint/index.js b/node_modules/json-bigint/index.js new file mode 100644 index 0000000..4757600 --- /dev/null +++ b/node_modules/json-bigint/index.js @@ -0,0 +1,12 @@ +var json_stringify = require('./lib/stringify.js').stringify; +var json_parse = require('./lib/parse.js'); + +module.exports = function(options) { + return { + parse: json_parse(options), + stringify: json_stringify + } +}; +//create the default method members with no options applied for backwards compatibility +module.exports.parse = json_parse(); +module.exports.stringify = json_stringify; diff --git a/node_modules/json-bigint/lib/parse.js b/node_modules/json-bigint/lib/parse.js new file mode 100644 index 0000000..2941c81 --- /dev/null +++ b/node_modules/json-bigint/lib/parse.js @@ -0,0 +1,384 @@ +var BigNumber = null; +/* + json_parse.js + 2012-06-20 + + Public Domain. + + NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. + + This file creates a json_parse function. + During create you can (optionally) specify some behavioural switches + + require('json-bigint')(options) + + The optional options parameter holds switches that drive certain + aspects of the parsing process: + * options.strict = true will warn about duplicate-key usage in the json. + The default (strict = false) will silently ignore those and overwrite + values for keys that are in duplicate use. + + The resulting function follows this signature: + json_parse(text, reviver) + This method parses a JSON text to produce an object or array. + It can throw a SyntaxError exception. + + The optional reviver parameter is a function that can filter and + transform the results. It receives each of the keys and values, + and its return value is used instead of the original value. + If it returns what it received, then the structure is not modified. + If it returns undefined then the member is deleted. + + Example: + + // Parse the text. Values that look like ISO date strings will + // be converted to Date objects. + + myData = json_parse(text, function (key, value) { + var a; + if (typeof value === 'string') { + a = +/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); + if (a) { + return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], + +a[5], +a[6])); + } + } + return value; + }); + + This is a reference implementation. You are free to copy, modify, or + redistribute. + + This code should be minified before deployment. + See http://javascript.crockford.com/jsmin.html + + USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO + NOT CONTROL. +*/ + +/*members "", "\"", "\/", "\\", at, b, call, charAt, f, fromCharCode, + hasOwnProperty, message, n, name, prototype, push, r, t, text +*/ + +var json_parse = function (options) { + "use strict"; + +// This is a function that can parse a JSON text, producing a JavaScript +// data structure. It is a simple, recursive descent parser. It does not use +// eval or regular expressions, so it can be used as a model for implementing +// a JSON parser in other languages. + +// We are defining the function inside of another function to avoid creating +// global variables. + + +// Default options one can override by passing options to the parse() + var _options = { + "strict": false, // not being strict means do not generate syntax errors for "duplicate key" + "storeAsString": false // toggles whether the values should be stored as BigNumber (default) or a string + }; + + +// If there are options, then use them to override the default _options + if (options !== undefined && options !== null) { + if (options.strict === true) { + _options.strict = true; + } + if (options.storeAsString === true) { + _options.storeAsString = true; + } + } + + + var at, // The index of the current character + ch, // The current character + escapee = { + '"': '"', + '\\': '\\', + '/': '/', + b: '\b', + f: '\f', + n: '\n', + r: '\r', + t: '\t' + }, + text, + + error = function (m) { + +// Call error when something is wrong. + + throw { + name: 'SyntaxError', + message: m, + at: at, + text: text + }; + }, + + next = function (c) { + +// If a c parameter is provided, verify that it matches the current character. + + if (c && c !== ch) { + error("Expected '" + c + "' instead of '" + ch + "'"); + } + +// Get the next character. When there are no more characters, +// return the empty string. + + ch = text.charAt(at); + at += 1; + return ch; + }, + + number = function () { +// Parse a number value. + + var number, + string = ''; + + if (ch === '-') { + string = '-'; + next('-'); + } + while (ch >= '0' && ch <= '9') { + string += ch; + next(); + } + if (ch === '.') { + string += '.'; + while (next() && ch >= '0' && ch <= '9') { + string += ch; + } + } + if (ch === 'e' || ch === 'E') { + string += ch; + next(); + if (ch === '-' || ch === '+') { + string += ch; + next(); + } + while (ch >= '0' && ch <= '9') { + string += ch; + next(); + } + } + number = +string; + if (!isFinite(number)) { + error("Bad number"); + } else { + if (BigNumber == null) + BigNumber = require('bignumber.js'); + //if (number > 9007199254740992 || number < -9007199254740992) + // Bignumber has stricter check: everything with length > 15 digits disallowed + if (string.length > 15) + return (_options.storeAsString === true) ? string : new BigNumber(string); + return number; + } + }, + + string = function () { + +// Parse a string value. + + var hex, + i, + string = '', + uffff; + +// When parsing for string values, we must look for " and \ characters. + + if (ch === '"') { + while (next()) { + if (ch === '"') { + next(); + return string; + } + if (ch === '\\') { + next(); + if (ch === 'u') { + uffff = 0; + for (i = 0; i < 4; i += 1) { + hex = parseInt(next(), 16); + if (!isFinite(hex)) { + break; + } + uffff = uffff * 16 + hex; + } + string += String.fromCharCode(uffff); + } else if (typeof escapee[ch] === 'string') { + string += escapee[ch]; + } else { + break; + } + } else { + string += ch; + } + } + } + error("Bad string"); + }, + + white = function () { + +// Skip whitespace. + + while (ch && ch <= ' ') { + next(); + } + }, + + word = function () { + +// true, false, or null. + + switch (ch) { + case 't': + next('t'); + next('r'); + next('u'); + next('e'); + return true; + case 'f': + next('f'); + next('a'); + next('l'); + next('s'); + next('e'); + return false; + case 'n': + next('n'); + next('u'); + next('l'); + next('l'); + return null; + } + error("Unexpected '" + ch + "'"); + }, + + value, // Place holder for the value function. + + array = function () { + +// Parse an array value. + + var array = []; + + if (ch === '[') { + next('['); + white(); + if (ch === ']') { + next(']'); + return array; // empty array + } + while (ch) { + array.push(value()); + white(); + if (ch === ']') { + next(']'); + return array; + } + next(','); + white(); + } + } + error("Bad array"); + }, + + object = function () { + +// Parse an object value. + + var key, + object = {}; + + if (ch === '{') { + next('{'); + white(); + if (ch === '}') { + next('}'); + return object; // empty object + } + while (ch) { + key = string(); + white(); + next(':'); + if (_options.strict === true && Object.hasOwnProperty.call(object, key)) { + error('Duplicate key "' + key + '"'); + } + object[key] = value(); + white(); + if (ch === '}') { + next('}'); + return object; + } + next(','); + white(); + } + } + error("Bad object"); + }; + + value = function () { + +// Parse a JSON value. It could be an object, an array, a string, a number, +// or a word. + + white(); + switch (ch) { + case '{': + return object(); + case '[': + return array(); + case '"': + return string(); + case '-': + return number(); + default: + return ch >= '0' && ch <= '9' ? number() : word(); + } + }; + +// Return the json_parse function. It will have access to all of the above +// functions and variables. + + return function (source, reviver) { + var result; + + text = source + ''; + at = 0; + ch = ' '; + result = value(); + white(); + if (ch) { + error("Syntax error"); + } + +// If there is a reviver function, we recursively walk the new structure, +// passing each name/value pair to the reviver function for possible +// transformation, starting with a temporary root object that holds the result +// in an empty key. If there is not a reviver function, we simply return the +// result. + + return typeof reviver === 'function' + ? (function walk(holder, key) { + var k, v, value = holder[key]; + if (value && typeof value === 'object') { + Object.keys(value).forEach(function(k) { + v = walk(value, k); + if (v !== undefined) { + value[k] = v; + } else { + delete value[k]; + } + }); + } + return reviver.call(holder, key, value); + }({'': result}, '')) + : result; + }; +} + +module.exports = json_parse; diff --git a/node_modules/json-bigint/lib/stringify.js b/node_modules/json-bigint/lib/stringify.js new file mode 100644 index 0000000..ce0592e --- /dev/null +++ b/node_modules/json-bigint/lib/stringify.js @@ -0,0 +1,383 @@ +var BigNumber = require('bignumber.js'); + +/* + json2.js + 2013-05-26 + + Public Domain. + + NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK. + + See http://www.JSON.org/js.html + + + This code should be minified before deployment. + See http://javascript.crockford.com/jsmin.html + + USE YOUR OWN COPY. IT IS EXTREMELY UNWISE TO LOAD CODE FROM SERVERS YOU DO + NOT CONTROL. + + + This file creates a global JSON object containing two methods: stringify + and parse. + + JSON.stringify(value, replacer, space) + value any JavaScript value, usually an object or array. + + replacer an optional parameter that determines how object + values are stringified for objects. It can be a + function or an array of strings. + + space an optional parameter that specifies the indentation + of nested structures. If it is omitted, the text will + be packed without extra whitespace. If it is a number, + it will specify the number of spaces to indent at each + level. If it is a string (such as '\t' or ' '), + it contains the characters used to indent at each level. + + This method produces a JSON text from a JavaScript value. + + When an object value is found, if the object contains a toJSON + method, its toJSON method will be called and the result will be + stringified. A toJSON method does not serialize: it returns the + value represented by the name/value pair that should be serialized, + or undefined if nothing should be serialized. The toJSON method + will be passed the key associated with the value, and this will be + bound to the value + + For example, this would serialize Dates as ISO strings. + + Date.prototype.toJSON = function (key) { + function f(n) { + // Format integers to have at least two digits. + return n < 10 ? '0' + n : n; + } + + return this.getUTCFullYear() + '-' + + f(this.getUTCMonth() + 1) + '-' + + f(this.getUTCDate()) + 'T' + + f(this.getUTCHours()) + ':' + + f(this.getUTCMinutes()) + ':' + + f(this.getUTCSeconds()) + 'Z'; + }; + + You can provide an optional replacer method. It will be passed the + key and value of each member, with this bound to the containing + object. The value that is returned from your method will be + serialized. If your method returns undefined, then the member will + be excluded from the serialization. + + If the replacer parameter is an array of strings, then it will be + used to select the members to be serialized. It filters the results + such that only members with keys listed in the replacer array are + stringified. + + Values that do not have JSON representations, such as undefined or + functions, will not be serialized. Such values in objects will be + dropped; in arrays they will be replaced with null. You can use + a replacer function to replace those with JSON values. + JSON.stringify(undefined) returns undefined. + + The optional space parameter produces a stringification of the + value that is filled with line breaks and indentation to make it + easier to read. + + If the space parameter is a non-empty string, then that string will + be used for indentation. If the space parameter is a number, then + the indentation will be that many spaces. + + Example: + + text = JSON.stringify(['e', {pluribus: 'unum'}]); + // text is '["e",{"pluribus":"unum"}]' + + + text = JSON.stringify(['e', {pluribus: 'unum'}], null, '\t'); + // text is '[\n\t"e",\n\t{\n\t\t"pluribus": "unum"\n\t}\n]' + + text = JSON.stringify([new Date()], function (key, value) { + return this[key] instanceof Date ? + 'Date(' + this[key] + ')' : value; + }); + // text is '["Date(---current time---)"]' + + + JSON.parse(text, reviver) + This method parses a JSON text to produce an object or array. + It can throw a SyntaxError exception. + + The optional reviver parameter is a function that can filter and + transform the results. It receives each of the keys and values, + and its return value is used instead of the original value. + If it returns what it received, then the structure is not modified. + If it returns undefined then the member is deleted. + + Example: + + // Parse the text. Values that look like ISO date strings will + // be converted to Date objects. + + myData = JSON.parse(text, function (key, value) { + var a; + if (typeof value === 'string') { + a = +/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d*)?)Z$/.exec(value); + if (a) { + return new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], + +a[5], +a[6])); + } + } + return value; + }); + + myData = JSON.parse('["Date(09/09/2001)"]', function (key, value) { + var d; + if (typeof value === 'string' && + value.slice(0, 5) === 'Date(' && + value.slice(-1) === ')') { + d = new Date(value.slice(5, -1)); + if (d) { + return d; + } + } + return value; + }); + + + This is a reference implementation. You are free to copy, modify, or + redistribute. +*/ + +/*jslint evil: true, regexp: true */ + +/*members "", "\b", "\t", "\n", "\f", "\r", "\"", JSON, "\\", apply, + call, charCodeAt, getUTCDate, getUTCFullYear, getUTCHours, + getUTCMinutes, getUTCMonth, getUTCSeconds, hasOwnProperty, join, + lastIndex, length, parse, prototype, push, replace, slice, stringify, + test, toJSON, toString, valueOf +*/ + + +// Create a JSON object only if one does not already exist. We create the +// methods in a closure to avoid creating global variables. + +var JSON = module.exports; + +(function () { + 'use strict'; + + function f(n) { + // Format integers to have at least two digits. + return n < 10 ? '0' + n : n; + } + + var cx = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, + escapable = /[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, + gap, + indent, + meta = { // table of character substitutions + '\b': '\\b', + '\t': '\\t', + '\n': '\\n', + '\f': '\\f', + '\r': '\\r', + '"' : '\\"', + '\\': '\\\\' + }, + rep; + + + function quote(string) { + +// If the string contains no control characters, no quote characters, and no +// backslash characters, then we can safely slap some quotes around it. +// Otherwise we must also replace the offending characters with safe escape +// sequences. + + escapable.lastIndex = 0; + return escapable.test(string) ? '"' + string.replace(escapable, function (a) { + var c = meta[a]; + return typeof c === 'string' + ? c + : '\\u' + ('0000' + a.charCodeAt(0).toString(16)).slice(-4); + }) + '"' : '"' + string + '"'; + } + + + function str(key, holder) { + +// Produce a string from holder[key]. + + var i, // The loop counter. + k, // The member key. + v, // The member value. + length, + mind = gap, + partial, + value = holder[key], + isBigNumber = value != null && (value instanceof BigNumber || BigNumber.isBigNumber(value)); + +// If the value has a toJSON method, call it to obtain a replacement value. + + if (value && typeof value === 'object' && + typeof value.toJSON === 'function') { + value = value.toJSON(key); + } + +// If we were called with a replacer function, then call the replacer to +// obtain a replacement value. + + if (typeof rep === 'function') { + value = rep.call(holder, key, value); + } + +// What happens next depends on the value's type. + + switch (typeof value) { + case 'string': + if (isBigNumber) { + return value; + } else { + return quote(value); + } + + case 'number': + +// JSON numbers must be finite. Encode non-finite numbers as null. + + return isFinite(value) ? String(value) : 'null'; + + case 'boolean': + case 'null': + +// If the value is a boolean or null, convert it to a string. Note: +// typeof null does not produce 'null'. The case is included here in +// the remote chance that this gets fixed someday. + + return String(value); + +// If the type is 'object', we might be dealing with an object or an array or +// null. + + case 'object': + +// Due to a specification blunder in ECMAScript, typeof null is 'object', +// so watch out for that case. + + if (!value) { + return 'null'; + } + +// Make an array to hold the partial results of stringifying this object value. + + gap += indent; + partial = []; + +// Is the value an array? + + if (Object.prototype.toString.apply(value) === '[object Array]') { + +// The value is an array. Stringify every element. Use null as a placeholder +// for non-JSON values. + + length = value.length; + for (i = 0; i < length; i += 1) { + partial[i] = str(i, value) || 'null'; + } + +// Join all of the elements together, separated with commas, and wrap them in +// brackets. + + v = partial.length === 0 + ? '[]' + : gap + ? '[\n' + gap + partial.join(',\n' + gap) + '\n' + mind + ']' + : '[' + partial.join(',') + ']'; + gap = mind; + return v; + } + +// If the replacer is an array, use it to select the members to be stringified. + + if (rep && typeof rep === 'object') { + length = rep.length; + for (i = 0; i < length; i += 1) { + if (typeof rep[i] === 'string') { + k = rep[i]; + v = str(k, value); + if (v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v); + } + } + } + } else { + +// Otherwise, iterate through all of the keys in the object. + + Object.keys(value).forEach(function(k) { + var v = str(k, value); + if (v) { + partial.push(quote(k) + (gap ? ': ' : ':') + v); + } + }); + } + +// Join all of the member texts together, separated with commas, +// and wrap them in braces. + + v = partial.length === 0 + ? '{}' + : gap + ? '{\n' + gap + partial.join(',\n' + gap) + '\n' + mind + '}' + : '{' + partial.join(',') + '}'; + gap = mind; + return v; + } + } + +// If the JSON object does not yet have a stringify method, give it one. + + if (typeof JSON.stringify !== 'function') { + JSON.stringify = function (value, replacer, space) { + +// The stringify method takes a value and an optional replacer, and an optional +// space parameter, and returns a JSON text. The replacer can be a function +// that can replace values, or an array of strings that will select the keys. +// A default replacer method can be provided. Use of the space parameter can +// produce text that is more easily readable. + + var i; + gap = ''; + indent = ''; + +// If the space parameter is a number, make an indent string containing that +// many spaces. + + if (typeof space === 'number') { + for (i = 0; i < space; i += 1) { + indent += ' '; + } + +// If the space parameter is a string, it will be used as the indent string. + + } else if (typeof space === 'string') { + indent = space; + } + +// If there is a replacer, it must be a function or an array. +// Otherwise, throw an error. + + rep = replacer; + if (replacer && typeof replacer !== 'function' && + (typeof replacer !== 'object' || + typeof replacer.length !== 'number')) { + throw new Error('JSON.stringify'); + } + +// Make a fake root object containing our value under the key of ''. +// Return the result of stringifying the value. + + return str('', {'': value}); + }; + } +}()); diff --git a/node_modules/json-bigint/package.json b/node_modules/json-bigint/package.json new file mode 100644 index 0000000..751ae0f --- /dev/null +++ b/node_modules/json-bigint/package.json @@ -0,0 +1,61 @@ +{ + "_from": "json-bigint@^0.3.0", + "_id": "json-bigint@0.3.0", + "_inBundle": false, + "_integrity": "sha1-DM2RLEuCcNBfBW+9E4FLU9OCWx4=", + "_location": "/json-bigint", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "json-bigint@^0.3.0", + "name": "json-bigint", + "escapedName": "json-bigint", + "rawSpec": "^0.3.0", + "saveSpec": null, + "fetchSpec": "^0.3.0" + }, + "_requiredBy": [ + "/gcp-metadata" + ], + "_resolved": "https://registry.npmjs.org/json-bigint/-/json-bigint-0.3.0.tgz", + "_shasum": "0ccd912c4b8270d05f056fbd13814b53d3825b1e", + "_spec": "json-bigint@^0.3.0", + "_where": "/Users/cday/Code/zendesk/fetch-build-from-gcb/node_modules/gcp-metadata", + "author": { + "name": "Andrey Sidorov", + "email": "sidorares@yandex.ru" + }, + "bugs": { + "url": "https://github.com/sidorares/json-bigint/issues" + }, + "bundleDependencies": false, + "dependencies": { + "bignumber.js": "^7.0.0" + }, + "deprecated": false, + "description": "JSON.parse with bigints support", + "devDependencies": { + "chai": "~1.9.1", + "mocha": "~1.20.1" + }, + "homepage": "https://github.com/sidorares/json-bigint#readme", + "keywords": [ + "JSON", + "bigint", + "bignumber", + "parse", + "json" + ], + "license": "MIT", + "main": "index.js", + "name": "json-bigint", + "repository": { + "type": "git", + "url": "git+ssh://git@github.com/sidorares/json-bigint.git" + }, + "scripts": { + "test": "./node_modules/mocha/bin/mocha -R spec --check-leaks test/*-test.js" + }, + "version": "0.3.0" +} diff --git a/node_modules/json-bigint/test/bigint-test.js b/node_modules/json-bigint/test/bigint-test.js new file mode 100644 index 0000000..5f5e1a3 --- /dev/null +++ b/node_modules/json-bigint/test/bigint-test.js @@ -0,0 +1,31 @@ +var mocha = require('mocha') + , assert = require('chai').assert + , expect = require('chai').expect + , BigNumber = require('bignumber.js') + ; + +describe("Testing bigint support", function(){ + var input = '{"big":9223372036854775807,"small":123}'; + + it("Should show classic JSON.parse lacks bigint support", function(done){ + var obj = JSON.parse(input); + expect(obj.small.toString(), "string from small int").to.equal("123"); + expect(obj.big.toString(), "string from big int").to.not.equal("9223372036854775807"); + + var output = JSON.stringify(obj); + expect(output).to.not.equal(input); + done(); + }); + + it("Should show JSNbig does support bigint parse/stringify roundtrip", function(done){ + var JSONbig = require('../index'); + var obj = JSONbig.parse(input); + expect(obj.small.toString(), "string from small int").to.equal("123"); + expect(obj.big.toString(), "string from big int").to.equal("9223372036854775807"); + expect(obj.big, "instanceof big int").to.be.instanceof(BigNumber); + + var output = JSONbig.stringify(obj); + expect(output).to.equal(input); + done(); + }); +}); diff --git a/node_modules/json-bigint/test/strict-option-test.js b/node_modules/json-bigint/test/strict-option-test.js new file mode 100644 index 0000000..bb27bd9 --- /dev/null +++ b/node_modules/json-bigint/test/strict-option-test.js @@ -0,0 +1,34 @@ +var mocha = require('mocha') + , assert = require('chai').assert + , expect = require('chai').expect + ; + +describe("Testing 'strict' option", function(){ + var dupkeys = '{ "dupkey": "value 1", "dupkey": "value 2"}'; + it("Should show that duplicate keys just get overwritten by default", function(done){ + var JSONbig = require('../index'); + var result = "before"; + function tryParse() { + result = JSONbig.parse(dupkeys); + } + expect(tryParse).to.not.throw("anything"); + expect(result.dupkey).to.equal("value 2"); + done(); + }); + + it("Should show that the 'strict' option will fail-fast on duplicate keys", function(done){ + var JSONstrict = require('../index')({"strict": true}); + var result = "before"; + function tryParse() { + result = JSONstrict.parse(dupkeys); + } + expect(tryParse).to.throw({ + name: 'SyntaxError', + message: 'Duplicate key "dupkey"', + at: 33, + text: '{ "dupkey": "value 1", "dupkey": "value 2"}' + }); + expect(result).to.equal("before"); + done(); + }); +}); diff --git a/node_modules/json-bigint/test/string-option-test.js b/node_modules/json-bigint/test/string-option-test.js new file mode 100644 index 0000000..c729f34 --- /dev/null +++ b/node_modules/json-bigint/test/string-option-test.js @@ -0,0 +1,21 @@ +var mocha = require('mocha') + , assert = require('chai').assert + , expect = require('chai').expect + ; + +describe("Testing 'storeAsString' option", function(){ + var key = '{ "key": 12345678901234567 }'; + it("Should show that the key is of type object", function(done){ + var JSONbig = require('../index'); + var result = JSONbig.parse(key); + expect(typeof result.key).to.equal("object"); + done(); + }); + + it("Should show that key is of type string, when storeAsString option is true", function(done){ + var JSONstring = require('../index')({"storeAsString": true}); + var result = JSONstring.parse(key); + expect(typeof result.key).to.equal("string"); + done(); + }); +}); diff --git a/node_modules/jwa/LICENSE b/node_modules/jwa/LICENSE new file mode 100644 index 0000000..caeb849 --- /dev/null +++ b/node_modules/jwa/LICENSE @@ -0,0 +1,17 @@ +Copyright (c) 2013 Brian J. Brennan + +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. diff --git a/node_modules/jwa/README.md b/node_modules/jwa/README.md new file mode 100644 index 0000000..09e9648 --- /dev/null +++ b/node_modules/jwa/README.md @@ -0,0 +1,150 @@ +# node-jwa [![Build Status](https://travis-ci.org/brianloveswords/node-jwa.svg?branch=master)](https://travis-ci.org/brianloveswords/node-jwa) + +A +[JSON Web Algorithms](http://tools.ietf.org/id/draft-ietf-jose-json-web-algorithms-08.html) +implementation focusing (exclusively, at this point) on the algorithms necessary for +[JSON Web Signatures](http://self-issued.info/docs/draft-ietf-jose-json-web-signature.html). + +This library supports all of the required, recommended and optional cryptographic algorithms for JWS: + +alg Parameter Value | Digital Signature or MAC Algorithm +----------------|---------------------------- +HS256 | HMAC using SHA-256 hash algorithm +HS384 | HMAC using SHA-384 hash algorithm +HS512 | HMAC using SHA-512 hash algorithm +RS256 | RSASSA using SHA-256 hash algorithm +RS384 | RSASSA using SHA-384 hash algorithm +RS512 | RSASSA using SHA-512 hash algorithm +PS256 | RSASSA-PSS using SHA-256 hash algorithm +PS384 | RSASSA-PSS using SHA-384 hash algorithm +PS512 | RSASSA-PSS using SHA-512 hash algorithm +ES256 | ECDSA using P-256 curve and SHA-256 hash algorithm +ES384 | ECDSA using P-384 curve and SHA-384 hash algorithm +ES512 | ECDSA using P-521 curve and SHA-512 hash algorithm +none | No digital signature or MAC value included + +Please note that PS* only works on Node 6.12+ (excluding 7.x). + +# Requirements + +In order to run the tests, a recent version of OpenSSL is +required. **The version that comes with OS X (OpenSSL 0.9.8r 8 Feb +2011) is not recent enough**, as it does not fully support ECDSA +keys. You'll need to use a version > 1.0.0; I tested with OpenSSL 1.0.1c 10 May 2012. + +# Testing + +To run the tests, do + +```bash +$ npm test +``` + +This will generate a bunch of keypairs to use in testing. If you want to +generate new keypairs, do `make clean` before running `npm test` again. + +## Methodology + +I spawn `openssl dgst -sign` to test OpenSSL sign → JS verify and +`openssl dgst -verify` to test JS sign → OpenSSL verify for each of the +RSA and ECDSA algorithms. + +# Usage + +## jwa(algorithm) + +Creates a new `jwa` object with `sign` and `verify` methods for the +algorithm. Valid values for algorithm can be found in the table above +(`'HS256'`, `'HS384'`, etc) and are case-sensitive. Passing an invalid +algorithm value will throw a `TypeError`. + + +## jwa#sign(input, secretOrPrivateKey) + +Sign some input with either a secret for HMAC algorithms, or a private +key for RSA and ECDSA algorithms. + +If input is not already a string or buffer, `JSON.stringify` will be +called on it to attempt to coerce it. + +For the HMAC algorithm, `secretOrPrivateKey` should be a string or a +buffer. For ECDSA and RSA, the value should be a string representing a +PEM encoded **private** key. + +Output [base64url](http://en.wikipedia.org/wiki/Base64#URL_applications) +formatted. This is for convenience as JWS expects the signature in this +format. If your application needs the output in a different format, +[please open an issue](https://github.com/brianloveswords/node-jwa/issues). In +the meantime, you can use +[brianloveswords/base64url](https://github.com/brianloveswords/base64url) +to decode the signature. + +As of nodejs *v0.11.8*, SPKAC support was introduce. If your nodeJs +version satisfies, then you can pass an object `{ key: '..', passphrase: '...' }` + + +## jwa#verify(input, signature, secretOrPublicKey) + +Verify a signature. Returns `true` or `false`. + +`signature` should be a base64url encoded string. + +For the HMAC algorithm, `secretOrPublicKey` should be a string or a +buffer. For ECDSA and RSA, the value should be a string represented a +PEM encoded **public** key. + + +# Example + +HMAC +```js +const jwa = require('jwa'); + +const hmac = jwa('HS256'); +const input = 'super important stuff'; +const secret = 'shhhhhh'; + +const signature = hmac.sign(input, secret); +hmac.verify(input, signature, secret) // === true +hmac.verify(input, signature, 'trickery!') // === false +``` + +With keys +```js +const fs = require('fs'); +const jwa = require('jwa'); +const privateKey = fs.readFileSync(__dirname + '/ecdsa-p521-private.pem'); +const publicKey = fs.readFileSync(__dirname + '/ecdsa-p521-public.pem'); + +const ecdsa = jwa('ES512'); +const input = 'very important stuff'; + +const signature = ecdsa.sign(input, privateKey); +ecdsa.verify(input, signature, publicKey) // === true +``` +## License + +MIT + +``` +Copyright (c) 2013 Brian J. Brennan + +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. +``` diff --git a/node_modules/jwa/index.js b/node_modules/jwa/index.js new file mode 100644 index 0000000..d2061ef --- /dev/null +++ b/node_modules/jwa/index.js @@ -0,0 +1,252 @@ +var bufferEqual = require('buffer-equal-constant-time'); +var Buffer = require('safe-buffer').Buffer; +var crypto = require('crypto'); +var formatEcdsa = require('ecdsa-sig-formatter'); +var util = require('util'); + +var MSG_INVALID_ALGORITHM = '"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".' +var MSG_INVALID_SECRET = 'secret must be a string or buffer'; +var MSG_INVALID_VERIFIER_KEY = 'key must be a string or a buffer'; +var MSG_INVALID_SIGNER_KEY = 'key must be a string, a buffer or an object'; + +var supportsKeyObjects = typeof crypto.createPublicKey === 'function'; +if (supportsKeyObjects) { + MSG_INVALID_VERIFIER_KEY += ' or a KeyObject'; + MSG_INVALID_SECRET += 'or a KeyObject'; +} + +function checkIsPublicKey(key) { + if (Buffer.isBuffer(key)) { + return; + } + + if (typeof key === 'string') { + return; + } + + if (!supportsKeyObjects) { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } + + if (typeof key !== 'object') { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } + + if (typeof key.type !== 'string') { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } + + if (typeof key.asymmetricKeyType !== 'string') { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } + + if (typeof key.export !== 'function') { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } +}; + +function checkIsPrivateKey(key) { + if (Buffer.isBuffer(key)) { + return; + } + + if (typeof key === 'string') { + return; + } + + if (typeof key === 'object') { + return; + } + + throw typeError(MSG_INVALID_SIGNER_KEY); +}; + +function checkIsSecretKey(key) { + if (Buffer.isBuffer(key)) { + return; + } + + if (typeof key === 'string') { + return key; + } + + if (!supportsKeyObjects) { + throw typeError(MSG_INVALID_SECRET); + } + + if (typeof key !== 'object') { + throw typeError(MSG_INVALID_SECRET); + } + + if (key.type !== 'secret') { + throw typeError(MSG_INVALID_SECRET); + } + + if (typeof key.export !== 'function') { + throw typeError(MSG_INVALID_SECRET); + } +} + +function fromBase64(base64) { + return base64 + .replace(/=/g, '') + .replace(/\+/g, '-') + .replace(/\//g, '_'); +} + +function toBase64(base64url) { + base64url = base64url.toString(); + + var padding = 4 - base64url.length % 4; + if (padding !== 4) { + for (var i = 0; i < padding; ++i) { + base64url += '='; + } + } + + return base64url + .replace(/\-/g, '+') + .replace(/_/g, '/'); +} + +function typeError(template) { + var args = [].slice.call(arguments, 1); + var errMsg = util.format.bind(util, template).apply(null, args); + return new TypeError(errMsg); +} + +function bufferOrString(obj) { + return Buffer.isBuffer(obj) || typeof obj === 'string'; +} + +function normalizeInput(thing) { + if (!bufferOrString(thing)) + thing = JSON.stringify(thing); + return thing; +} + +function createHmacSigner(bits) { + return function sign(thing, secret) { + checkIsSecretKey(secret); + thing = normalizeInput(thing); + var hmac = crypto.createHmac('sha' + bits, secret); + var sig = (hmac.update(thing), hmac.digest('base64')) + return fromBase64(sig); + } +} + +function createHmacVerifier(bits) { + return function verify(thing, signature, secret) { + var computedSig = createHmacSigner(bits)(thing, secret); + return bufferEqual(Buffer.from(signature), Buffer.from(computedSig)); + } +} + +function createKeySigner(bits) { + return function sign(thing, privateKey) { + checkIsPrivateKey(privateKey); + thing = normalizeInput(thing); + // Even though we are specifying "RSA" here, this works with ECDSA + // keys as well. + var signer = crypto.createSign('RSA-SHA' + bits); + var sig = (signer.update(thing), signer.sign(privateKey, 'base64')); + return fromBase64(sig); + } +} + +function createKeyVerifier(bits) { + return function verify(thing, signature, publicKey) { + checkIsPublicKey(publicKey); + thing = normalizeInput(thing); + signature = toBase64(signature); + var verifier = crypto.createVerify('RSA-SHA' + bits); + verifier.update(thing); + return verifier.verify(publicKey, signature, 'base64'); + } +} + +function createPSSKeySigner(bits) { + return function sign(thing, privateKey) { + checkIsPrivateKey(privateKey); + thing = normalizeInput(thing); + var signer = crypto.createSign('RSA-SHA' + bits); + var sig = (signer.update(thing), signer.sign({ + key: privateKey, + padding: crypto.constants.RSA_PKCS1_PSS_PADDING, + saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST + }, 'base64')); + return fromBase64(sig); + } +} + +function createPSSKeyVerifier(bits) { + return function verify(thing, signature, publicKey) { + checkIsPublicKey(publicKey); + thing = normalizeInput(thing); + signature = toBase64(signature); + var verifier = crypto.createVerify('RSA-SHA' + bits); + verifier.update(thing); + return verifier.verify({ + key: publicKey, + padding: crypto.constants.RSA_PKCS1_PSS_PADDING, + saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST + }, signature, 'base64'); + } +} + +function createECDSASigner(bits) { + var inner = createKeySigner(bits); + return function sign() { + var signature = inner.apply(null, arguments); + signature = formatEcdsa.derToJose(signature, 'ES' + bits); + return signature; + }; +} + +function createECDSAVerifer(bits) { + var inner = createKeyVerifier(bits); + return function verify(thing, signature, publicKey) { + signature = formatEcdsa.joseToDer(signature, 'ES' + bits).toString('base64'); + var result = inner(thing, signature, publicKey); + return result; + }; +} + +function createNoneSigner() { + return function sign() { + return ''; + } +} + +function createNoneVerifier() { + return function verify(thing, signature) { + return signature === ''; + } +} + +module.exports = function jwa(algorithm) { + var signerFactories = { + hs: createHmacSigner, + rs: createKeySigner, + ps: createPSSKeySigner, + es: createECDSASigner, + none: createNoneSigner, + } + var verifierFactories = { + hs: createHmacVerifier, + rs: createKeyVerifier, + ps: createPSSKeyVerifier, + es: createECDSAVerifer, + none: createNoneVerifier, + } + var match = algorithm.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/); + if (!match) + throw typeError(MSG_INVALID_ALGORITHM, algorithm); + var algo = (match[1] || match[3]).toLowerCase(); + var bits = match[2]; + + return { + sign: signerFactories[algo](bits), + verify: verifierFactories[algo](bits), + } +}; diff --git a/node_modules/jwa/package.json b/node_modules/jwa/package.json new file mode 100644 index 0000000..649e085 --- /dev/null +++ b/node_modules/jwa/package.json @@ -0,0 +1,69 @@ +{ + "_from": "jwa@^2.0.0", + "_id": "jwa@2.0.0", + "_inBundle": false, + "_integrity": "sha512-jrZ2Qx916EA+fq9cEAeCROWPTfCwi1IVHqT2tapuqLEVVDKFDENFw1oL+MwrTvH6msKxsd1YTDVw6uKEcsrLEA==", + "_location": "/jwa", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "jwa@^2.0.0", + "name": "jwa", + "escapedName": "jwa", + "rawSpec": "^2.0.0", + "saveSpec": null, + "fetchSpec": "^2.0.0" + }, + "_requiredBy": [ + "/jws" + ], + "_resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.0.tgz", + "_shasum": "a7e9c3f29dae94027ebcaf49975c9345593410fc", + "_spec": "jwa@^2.0.0", + "_where": "/Users/cday/Code/zendesk/fetch-build-from-gcb/node_modules/jws", + "author": { + "name": "Brian J. Brennan", + "email": "brianloveswords@gmail.com" + }, + "bugs": { + "url": "https://github.com/brianloveswords/node-jwa/issues" + }, + "bundleDependencies": false, + "dependencies": { + "buffer-equal-constant-time": "1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + }, + "deprecated": false, + "description": "JWA implementation (supports all JWS algorithms)", + "devDependencies": { + "base64url": "^2.0.0", + "jwk-to-pem": "^2.0.1", + "semver": "4.3.6", + "tap": "6.2.0" + }, + "directories": { + "test": "test" + }, + "homepage": "https://github.com/brianloveswords/node-jwa#readme", + "keywords": [ + "jwa", + "jws", + "jwt", + "rsa", + "ecdsa", + "hmac" + ], + "license": "MIT", + "main": "index.js", + "name": "jwa", + "repository": { + "type": "git", + "url": "git://github.com/brianloveswords/node-jwa.git" + }, + "scripts": { + "test": "make test" + }, + "version": "2.0.0" +} diff --git a/node_modules/jws/CHANGELOG.md b/node_modules/jws/CHANGELOG.md new file mode 100644 index 0000000..af8fc28 --- /dev/null +++ b/node_modules/jws/CHANGELOG.md @@ -0,0 +1,34 @@ +# Change Log +All notable changes to this project will be documented in this file. + +## [3.0.0] +### Changed +- **BREAKING**: `jwt.verify` now requires an `algorithm` parameter, and + `jws.createVerify` requires an `algorithm` option. The `"alg"` field + signature headers is ignored. This mitigates a critical security flaw + in the library which would allow an attacker to generate signatures with + arbitrary contents that would be accepted by `jwt.verify`. See + https://auth0.com/blog/2015/03/31/critical-vulnerabilities-in-json-web-token-libraries/ + for details. + +## [2.0.0] - 2015-01-30 +### Changed +- **BREAKING**: Default payload encoding changed from `binary` to + `utf8`. `utf8` is a is a more sensible default than `binary` because + many payloads, as far as I can tell, will contain user-facing + strings that could be in any language. ([6b6de48]) + +- Code reorganization, thanks [@fearphage]! ([7880050]) + +### Added +- Option in all relevant methods for `encoding`. For those few users + that might be depending on a `binary` encoding of the messages, this + is for them. ([6b6de48]) + +[unreleased]: https://github.com/brianloveswords/node-jws/compare/v2.0.0...HEAD +[2.0.0]: https://github.com/brianloveswords/node-jws/compare/v1.0.1...v2.0.0 + +[7880050]: https://github.com/brianloveswords/node-jws/commit/7880050 +[6b6de48]: https://github.com/brianloveswords/node-jws/commit/6b6de48 + +[@fearphage]: https://github.com/fearphage diff --git a/node_modules/jws/LICENSE b/node_modules/jws/LICENSE new file mode 100644 index 0000000..caeb849 --- /dev/null +++ b/node_modules/jws/LICENSE @@ -0,0 +1,17 @@ +Copyright (c) 2013 Brian J. Brennan + +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. diff --git a/node_modules/jws/index.js b/node_modules/jws/index.js new file mode 100644 index 0000000..8c8da93 --- /dev/null +++ b/node_modules/jws/index.js @@ -0,0 +1,22 @@ +/*global exports*/ +var SignStream = require('./lib/sign-stream'); +var VerifyStream = require('./lib/verify-stream'); + +var ALGORITHMS = [ + 'HS256', 'HS384', 'HS512', + 'RS256', 'RS384', 'RS512', + 'PS256', 'PS384', 'PS512', + 'ES256', 'ES384', 'ES512' +]; + +exports.ALGORITHMS = ALGORITHMS; +exports.sign = SignStream.sign; +exports.verify = VerifyStream.verify; +exports.decode = VerifyStream.decode; +exports.isValid = VerifyStream.isValid; +exports.createSign = function createSign(opts) { + return new SignStream(opts); +}; +exports.createVerify = function createVerify(opts) { + return new VerifyStream(opts); +}; diff --git a/node_modules/jws/lib/data-stream.js b/node_modules/jws/lib/data-stream.js new file mode 100644 index 0000000..3535d31 --- /dev/null +++ b/node_modules/jws/lib/data-stream.js @@ -0,0 +1,55 @@ +/*global module, process*/ +var Buffer = require('safe-buffer').Buffer; +var Stream = require('stream'); +var util = require('util'); + +function DataStream(data) { + this.buffer = null; + this.writable = true; + this.readable = true; + + // No input + if (!data) { + this.buffer = Buffer.alloc(0); + return this; + } + + // Stream + if (typeof data.pipe === 'function') { + this.buffer = Buffer.alloc(0); + data.pipe(this); + return this; + } + + // Buffer or String + // or Object (assumedly a passworded key) + if (data.length || typeof data === 'object') { + this.buffer = data; + this.writable = false; + process.nextTick(function () { + this.emit('end', data); + this.readable = false; + this.emit('close'); + }.bind(this)); + return this; + } + + throw new TypeError('Unexpected data type ('+ typeof data + ')'); +} +util.inherits(DataStream, Stream); + +DataStream.prototype.write = function write(data) { + this.buffer = Buffer.concat([this.buffer, Buffer.from(data)]); + this.emit('data', data); +}; + +DataStream.prototype.end = function end(data) { + if (data) + this.write(data); + this.emit('end', data); + this.emit('close'); + this.writable = false; + this.readable = false; +}; + +module.exports = DataStream; diff --git a/node_modules/jws/lib/sign-stream.js b/node_modules/jws/lib/sign-stream.js new file mode 100644 index 0000000..6a7ee42 --- /dev/null +++ b/node_modules/jws/lib/sign-stream.js @@ -0,0 +1,78 @@ +/*global module*/ +var Buffer = require('safe-buffer').Buffer; +var DataStream = require('./data-stream'); +var jwa = require('jwa'); +var Stream = require('stream'); +var toString = require('./tostring'); +var util = require('util'); + +function base64url(string, encoding) { + return Buffer + .from(string, encoding) + .toString('base64') + .replace(/=/g, '') + .replace(/\+/g, '-') + .replace(/\//g, '_'); +} + +function jwsSecuredInput(header, payload, encoding) { + encoding = encoding || 'utf8'; + var encodedHeader = base64url(toString(header), 'binary'); + var encodedPayload = base64url(toString(payload), encoding); + return util.format('%s.%s', encodedHeader, encodedPayload); +} + +function jwsSign(opts) { + var header = opts.header; + var payload = opts.payload; + var secretOrKey = opts.secret || opts.privateKey; + var encoding = opts.encoding; + var algo = jwa(header.alg); + var securedInput = jwsSecuredInput(header, payload, encoding); + var signature = algo.sign(securedInput, secretOrKey); + return util.format('%s.%s', securedInput, signature); +} + +function SignStream(opts) { + var secret = opts.secret||opts.privateKey||opts.key; + var secretStream = new DataStream(secret); + this.readable = true; + this.header = opts.header; + this.encoding = opts.encoding; + this.secret = this.privateKey = this.key = secretStream; + this.payload = new DataStream(opts.payload); + this.secret.once('close', function () { + if (!this.payload.writable && this.readable) + this.sign(); + }.bind(this)); + + this.payload.once('close', function () { + if (!this.secret.writable && this.readable) + this.sign(); + }.bind(this)); +} +util.inherits(SignStream, Stream); + +SignStream.prototype.sign = function sign() { + try { + var signature = jwsSign({ + header: this.header, + payload: this.payload.buffer, + secret: this.secret.buffer, + encoding: this.encoding + }); + this.emit('done', signature); + this.emit('data', signature); + this.emit('end'); + this.readable = false; + return signature; + } catch (e) { + this.readable = false; + this.emit('error', e); + this.emit('close'); + } +}; + +SignStream.sign = jwsSign; + +module.exports = SignStream; diff --git a/node_modules/jws/lib/tostring.js b/node_modules/jws/lib/tostring.js new file mode 100644 index 0000000..f5a49a3 --- /dev/null +++ b/node_modules/jws/lib/tostring.js @@ -0,0 +1,10 @@ +/*global module*/ +var Buffer = require('buffer').Buffer; + +module.exports = function toString(obj) { + if (typeof obj === 'string') + return obj; + if (typeof obj === 'number' || Buffer.isBuffer(obj)) + return obj.toString(); + return JSON.stringify(obj); +}; diff --git a/node_modules/jws/lib/verify-stream.js b/node_modules/jws/lib/verify-stream.js new file mode 100644 index 0000000..39f7c73 --- /dev/null +++ b/node_modules/jws/lib/verify-stream.js @@ -0,0 +1,120 @@ +/*global module*/ +var Buffer = require('safe-buffer').Buffer; +var DataStream = require('./data-stream'); +var jwa = require('jwa'); +var Stream = require('stream'); +var toString = require('./tostring'); +var util = require('util'); +var JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/; + +function isObject(thing) { + return Object.prototype.toString.call(thing) === '[object Object]'; +} + +function safeJsonParse(thing) { + if (isObject(thing)) + return thing; + try { return JSON.parse(thing); } + catch (e) { return undefined; } +} + +function headerFromJWS(jwsSig) { + var encodedHeader = jwsSig.split('.', 1)[0]; + return safeJsonParse(Buffer.from(encodedHeader, 'base64').toString('binary')); +} + +function securedInputFromJWS(jwsSig) { + return jwsSig.split('.', 2).join('.'); +} + +function signatureFromJWS(jwsSig) { + return jwsSig.split('.')[2]; +} + +function payloadFromJWS(jwsSig, encoding) { + encoding = encoding || 'utf8'; + var payload = jwsSig.split('.')[1]; + return Buffer.from(payload, 'base64').toString(encoding); +} + +function isValidJws(string) { + return JWS_REGEX.test(string) && !!headerFromJWS(string); +} + +function jwsVerify(jwsSig, algorithm, secretOrKey) { + if (!algorithm) { + var err = new Error("Missing algorithm parameter for jws.verify"); + err.code = "MISSING_ALGORITHM"; + throw err; + } + jwsSig = toString(jwsSig); + var signature = signatureFromJWS(jwsSig); + var securedInput = securedInputFromJWS(jwsSig); + var algo = jwa(algorithm); + return algo.verify(securedInput, signature, secretOrKey); +} + +function jwsDecode(jwsSig, opts) { + opts = opts || {}; + jwsSig = toString(jwsSig); + + if (!isValidJws(jwsSig)) + return null; + + var header = headerFromJWS(jwsSig); + + if (!header) + return null; + + var payload = payloadFromJWS(jwsSig); + if (header.typ === 'JWT' || opts.json) + payload = JSON.parse(payload, opts.encoding); + + return { + header: header, + payload: payload, + signature: signatureFromJWS(jwsSig) + }; +} + +function VerifyStream(opts) { + opts = opts || {}; + var secretOrKey = opts.secret||opts.publicKey||opts.key; + var secretStream = new DataStream(secretOrKey); + this.readable = true; + this.algorithm = opts.algorithm; + this.encoding = opts.encoding; + this.secret = this.publicKey = this.key = secretStream; + this.signature = new DataStream(opts.signature); + this.secret.once('close', function () { + if (!this.signature.writable && this.readable) + this.verify(); + }.bind(this)); + + this.signature.once('close', function () { + if (!this.secret.writable && this.readable) + this.verify(); + }.bind(this)); +} +util.inherits(VerifyStream, Stream); +VerifyStream.prototype.verify = function verify() { + try { + var valid = jwsVerify(this.signature.buffer, this.algorithm, this.key.buffer); + var obj = jwsDecode(this.signature.buffer, this.encoding); + this.emit('done', valid, obj); + this.emit('data', valid); + this.emit('end'); + this.readable = false; + return valid; + } catch (e) { + this.readable = false; + this.emit('error', e); + this.emit('close'); + } +}; + +VerifyStream.decode = jwsDecode; +VerifyStream.isValid = isValidJws; +VerifyStream.verify = jwsVerify; + +module.exports = VerifyStream; diff --git a/node_modules/jws/package.json b/node_modules/jws/package.json new file mode 100644 index 0000000..82643f9 --- /dev/null +++ b/node_modules/jws/package.json @@ -0,0 +1,65 @@ +{ + "_from": "jws@^4.0.0", + "_id": "jws@4.0.0", + "_inBundle": false, + "_integrity": "sha512-KDncfTmOZoOMTFG4mBlG0qUIOlc03fmzH+ru6RgYVZhPkyiy/92Owlt/8UEN+a4TXR1FQetfIpJE8ApdvdVxTg==", + "_location": "/jws", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "jws@^4.0.0", + "name": "jws", + "escapedName": "jws", + "rawSpec": "^4.0.0", + "saveSpec": null, + "fetchSpec": "^4.0.0" + }, + "_requiredBy": [ + "/google-auth-library", + "/gtoken" + ], + "_resolved": "https://registry.npmjs.org/jws/-/jws-4.0.0.tgz", + "_shasum": "2d4e8cf6a318ffaa12615e9dec7e86e6c97310f4", + "_spec": "jws@^4.0.0", + "_where": "/Users/cday/Code/zendesk/fetch-build-from-gcb/node_modules/google-auth-library", + "author": { + "name": "Brian J Brennan" + }, + "bugs": { + "url": "https://github.com/brianloveswords/node-jws/issues" + }, + "bundleDependencies": false, + "dependencies": { + "jwa": "^2.0.0", + "safe-buffer": "^5.0.1" + }, + "deprecated": false, + "description": "Implementation of JSON Web Signatures", + "devDependencies": { + "semver": "^5.1.0", + "tape": "~2.14.0" + }, + "directories": { + "test": "test" + }, + "gitHead": "c0f6b27bcea5a2ad2e304d91c2e842e4076a6b03", + "homepage": "https://github.com/brianloveswords/node-jws#readme", + "keywords": [ + "jws", + "json", + "web", + "signatures" + ], + "license": "MIT", + "main": "index.js", + "name": "jws", + "repository": { + "type": "git", + "url": "git://github.com/brianloveswords/node-jws.git" + }, + "scripts": { + "test": "make test" + }, + "version": "4.0.0" +} diff --git a/node_modules/jws/readme.md b/node_modules/jws/readme.md new file mode 100644 index 0000000..2f32dca --- /dev/null +++ b/node_modules/jws/readme.md @@ -0,0 +1,255 @@ +# node-jws [![Build Status](https://secure.travis-ci.org/brianloveswords/node-jws.svg)](http://travis-ci.org/brianloveswords/node-jws) + +An implementation of [JSON Web Signatures](http://self-issued.info/docs/draft-ietf-jose-json-web-signature.html). + +This was developed against `draft-ietf-jose-json-web-signature-08` and +implements the entire spec **except** X.509 Certificate Chain +signing/verifying (patches welcome). + +There are both synchronous (`jws.sign`, `jws.verify`) and streaming +(`jws.createSign`, `jws.createVerify`) APIs. + +# Install + +```bash +$ npm install jws +``` + +# Usage + +## jws.ALGORITHMS + +Array of supported algorithms. The following algorithms are currently supported. + +alg Parameter Value | Digital Signature or MAC Algorithm +----------------|---------------------------- +HS256 | HMAC using SHA-256 hash algorithm +HS384 | HMAC using SHA-384 hash algorithm +HS512 | HMAC using SHA-512 hash algorithm +RS256 | RSASSA using SHA-256 hash algorithm +RS384 | RSASSA using SHA-384 hash algorithm +RS512 | RSASSA using SHA-512 hash algorithm +PS256 | RSASSA-PSS using SHA-256 hash algorithm +PS384 | RSASSA-PSS using SHA-384 hash algorithm +PS512 | RSASSA-PSS using SHA-512 hash algorithm +ES256 | ECDSA using P-256 curve and SHA-256 hash algorithm +ES384 | ECDSA using P-384 curve and SHA-384 hash algorithm +ES512 | ECDSA using P-521 curve and SHA-512 hash algorithm +none | No digital signature or MAC value included + +## jws.sign(options) + +(Synchronous) Return a JSON Web Signature for a header and a payload. + +Options: + +* `header` +* `payload` +* `secret` or `privateKey` +* `encoding` (Optional, defaults to 'utf8') + +`header` must be an object with an `alg` property. `header.alg` must be +one a value found in `jws.ALGORITHMS`. See above for a table of +supported algorithms. + +If `payload` is not a buffer or a string, it will be coerced into a string +using `JSON.stringify`. + +Example + +```js +const signature = jws.sign({ + header: { alg: 'HS256' }, + payload: 'h. jon benjamin', + secret: 'has a van', +}); +``` + +## jws.verify(signature, algorithm, secretOrKey) + +(Synchronous) Returns `true` or `false` for whether a signature matches a +secret or key. + +`signature` is a JWS Signature. `header.alg` must be a value found in `jws.ALGORITHMS`. +See above for a table of supported algorithms. `secretOrKey` is a string or +buffer containing either the secret for HMAC algorithms, or the PEM +encoded public key for RSA and ECDSA. + +Note that the `"alg"` value from the signature header is ignored. + + +## jws.decode(signature) + +(Synchronous) Returns the decoded header, decoded payload, and signature +parts of the JWS Signature. + +Returns an object with three properties, e.g. +```js +{ header: { alg: 'HS256' }, + payload: 'h. jon benjamin', + signature: 'YOWPewyGHKu4Y_0M_vtlEnNlqmFOclqp4Hy6hVHfFT4' +} +``` + +## jws.createSign(options) + +Returns a new SignStream object. + +Options: + +* `header` (required) +* `payload` +* `key` || `privateKey` || `secret` +* `encoding` (Optional, defaults to 'utf8') + +Other than `header`, all options expect a string or a buffer when the +value is known ahead of time, or a stream for convenience. +`key`/`privateKey`/`secret` may also be an object when using an encrypted +private key, see the [crypto documentation][encrypted-key-docs]. + +Example: + +```js + +// This... +jws.createSign({ + header: { alg: 'RS256' }, + privateKey: privateKeyStream, + payload: payloadStream, +}).on('done', function(signature) { + // ... +}); + +// is equivalent to this: +const signer = jws.createSign({ + header: { alg: 'RS256' }, +}); +privateKeyStream.pipe(signer.privateKey); +payloadStream.pipe(signer.payload); +signer.on('done', function(signature) { + // ... +}); +``` + +## jws.createVerify(options) + +Returns a new VerifyStream object. + +Options: + +* `signature` +* `algorithm` +* `key` || `publicKey` || `secret` +* `encoding` (Optional, defaults to 'utf8') + +All options expect a string or a buffer when the value is known ahead of +time, or a stream for convenience. + +Example: + +```js + +// This... +jws.createVerify({ + publicKey: pubKeyStream, + signature: sigStream, +}).on('done', function(verified, obj) { + // ... +}); + +// is equivilant to this: +const verifier = jws.createVerify(); +pubKeyStream.pipe(verifier.publicKey); +sigStream.pipe(verifier.signature); +verifier.on('done', function(verified, obj) { + // ... +}); +``` + +## Class: SignStream + +A `Readable Stream` that emits a single data event (the calculated +signature) when done. + +### Event: 'done' +`function (signature) { }` + +### signer.payload + +A `Writable Stream` that expects the JWS payload. Do *not* use if you +passed a `payload` option to the constructor. + +Example: + +```js +payloadStream.pipe(signer.payload); +``` + +### signer.secret
signer.key
signer.privateKey + +A `Writable Stream`. Expects the JWS secret for HMAC, or the privateKey +for ECDSA and RSA. Do *not* use if you passed a `secret` or `key` option +to the constructor. + +Example: + +```js +privateKeyStream.pipe(signer.privateKey); +``` + +## Class: VerifyStream + +This is a `Readable Stream` that emits a single data event, the result +of whether or not that signature was valid. + +### Event: 'done' +`function (valid, obj) { }` + +`valid` is a boolean for whether or not the signature is valid. + +### verifier.signature + +A `Writable Stream` that expects a JWS Signature. Do *not* use if you +passed a `signature` option to the constructor. + +### verifier.secret
verifier.key
verifier.publicKey + +A `Writable Stream` that expects a public key or secret. Do *not* use if you +passed a `key` or `secret` option to the constructor. + +# TODO + +* It feels like there should be some convenience options/APIs for + defining the algorithm rather than having to define a header object + with `{ alg: 'ES512' }` or whatever every time. + +* X.509 support, ugh + +# License + +MIT + +``` +Copyright (c) 2013-2015 Brian J. Brennan + +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. +``` + +[encrypted-key-docs]: https://nodejs.org/api/crypto.html#crypto_sign_sign_private_key_output_format diff --git a/node_modules/lru-cache/LICENSE b/node_modules/lru-cache/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/lru-cache/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/lru-cache/README.md b/node_modules/lru-cache/README.md new file mode 100644 index 0000000..435dfeb --- /dev/null +++ b/node_modules/lru-cache/README.md @@ -0,0 +1,166 @@ +# lru cache + +A cache object that deletes the least-recently-used items. + +[![Build Status](https://travis-ci.org/isaacs/node-lru-cache.svg?branch=master)](https://travis-ci.org/isaacs/node-lru-cache) [![Coverage Status](https://coveralls.io/repos/isaacs/node-lru-cache/badge.svg?service=github)](https://coveralls.io/github/isaacs/node-lru-cache) + +## Installation: + +```javascript +npm install lru-cache --save +``` + +## Usage: + +```javascript +var LRU = require("lru-cache") + , options = { max: 500 + , length: function (n, key) { return n * 2 + key.length } + , dispose: function (key, n) { n.close() } + , maxAge: 1000 * 60 * 60 } + , cache = new LRU(options) + , otherCache = new LRU(50) // sets just the max size + +cache.set("key", "value") +cache.get("key") // "value" + +// non-string keys ARE fully supported +// but note that it must be THE SAME object, not +// just a JSON-equivalent object. +var someObject = { a: 1 } +cache.set(someObject, 'a value') +// Object keys are not toString()-ed +cache.set('[object Object]', 'a different value') +assert.equal(cache.get(someObject), 'a value') +// A similar object with same keys/values won't work, +// because it's a different object identity +assert.equal(cache.get({ a: 1 }), undefined) + +cache.reset() // empty the cache +``` + +If you put more stuff in it, then items will fall out. + +If you try to put an oversized thing in it, then it'll fall out right +away. + +## Options + +* `max` The maximum size of the cache, checked by applying the length + function to all values in the cache. Not setting this is kind of + silly, since that's the whole purpose of this lib, but it defaults + to `Infinity`. Setting it to a non-number or negative number will + throw a `TypeError`. Setting it to 0 makes it be `Infinity`. +* `maxAge` Maximum age in ms. Items are not pro-actively pruned out + as they age, but if you try to get an item that is too old, it'll + drop it and return undefined instead of giving it to you. + Setting this to a negative value will make everything seem old! + Setting it to a non-number will throw a `TypeError`. +* `length` Function that is used to calculate the length of stored + items. If you're storing strings or buffers, then you probably want + to do something like `function(n, key){return n.length}`. The default is + `function(){return 1}`, which is fine if you want to store `max` + like-sized things. The item is passed as the first argument, and + the key is passed as the second argumnet. +* `dispose` Function that is called on items when they are dropped + from the cache. This can be handy if you want to close file + descriptors or do other cleanup tasks when items are no longer + accessible. Called with `key, value`. It's called *before* + actually removing the item from the internal cache, so if you want + to immediately put it back in, you'll have to do that in a + `nextTick` or `setTimeout` callback or it won't do anything. +* `stale` By default, if you set a `maxAge`, it'll only actually pull + stale items out of the cache when you `get(key)`. (That is, it's + not pre-emptively doing a `setTimeout` or anything.) If you set + `stale:true`, it'll return the stale value before deleting it. If + you don't set this, then it'll return `undefined` when you try to + get a stale entry, as if it had already been deleted. +* `noDisposeOnSet` By default, if you set a `dispose()` method, then + it'll be called whenever a `set()` operation overwrites an existing + key. If you set this option, `dispose()` will only be called when a + key falls out of the cache, not when it is overwritten. +* `updateAgeOnGet` When using time-expiring entries with `maxAge`, + setting this to `true` will make each item's effective time update + to the current time whenever it is retrieved from cache, causing it + to not expire. (It can still fall out of cache based on recency of + use, of course.) + +## API + +* `set(key, value, maxAge)` +* `get(key) => value` + + Both of these will update the "recently used"-ness of the key. + They do what you think. `maxAge` is optional and overrides the + cache `maxAge` option if provided. + + If the key is not found, `get()` will return `undefined`. + + The key and val can be any value. + +* `peek(key)` + + Returns the key value (or `undefined` if not found) without + updating the "recently used"-ness of the key. + + (If you find yourself using this a lot, you *might* be using the + wrong sort of data structure, but there are some use cases where + it's handy.) + +* `del(key)` + + Deletes a key out of the cache. + +* `reset()` + + Clear the cache entirely, throwing away all values. + +* `has(key)` + + Check if a key is in the cache, without updating the recent-ness + or deleting it for being stale. + +* `forEach(function(value,key,cache), [thisp])` + + Just like `Array.prototype.forEach`. Iterates over all the keys + in the cache, in order of recent-ness. (Ie, more recently used + items are iterated over first.) + +* `rforEach(function(value,key,cache), [thisp])` + + The same as `cache.forEach(...)` but items are iterated over in + reverse order. (ie, less recently used items are iterated over + first.) + +* `keys()` + + Return an array of the keys in the cache. + +* `values()` + + Return an array of the values in the cache. + +* `length` + + Return total length of objects in cache taking into account + `length` options function. + +* `itemCount` + + Return total quantity of objects currently in cache. Note, that + `stale` (see options) items are returned as part of this item + count. + +* `dump()` + + Return an array of the cache entries ready for serialization and usage + with 'destinationCache.load(arr)`. + +* `load(cacheEntriesArray)` + + Loads another cache entries array, obtained with `sourceCache.dump()`, + into the cache. The destination cache is reset before loading new entries + +* `prune()` + + Manually iterates over the entire cache proactively pruning old entries diff --git a/node_modules/lru-cache/index.js b/node_modules/lru-cache/index.js new file mode 100644 index 0000000..573b6b8 --- /dev/null +++ b/node_modules/lru-cache/index.js @@ -0,0 +1,334 @@ +'use strict' + +// A linked list to keep track of recently-used-ness +const Yallist = require('yallist') + +const MAX = Symbol('max') +const LENGTH = Symbol('length') +const LENGTH_CALCULATOR = Symbol('lengthCalculator') +const ALLOW_STALE = Symbol('allowStale') +const MAX_AGE = Symbol('maxAge') +const DISPOSE = Symbol('dispose') +const NO_DISPOSE_ON_SET = Symbol('noDisposeOnSet') +const LRU_LIST = Symbol('lruList') +const CACHE = Symbol('cache') +const UPDATE_AGE_ON_GET = Symbol('updateAgeOnGet') + +const naiveLength = () => 1 + +// lruList is a yallist where the head is the youngest +// item, and the tail is the oldest. the list contains the Hit +// objects as the entries. +// Each Hit object has a reference to its Yallist.Node. This +// never changes. +// +// cache is a Map (or PseudoMap) that matches the keys to +// the Yallist.Node object. +class LRUCache { + constructor (options) { + if (typeof options === 'number') + options = { max: options } + + if (!options) + options = {} + + if (options.max && (typeof options.max !== 'number' || options.max < 0)) + throw new TypeError('max must be a non-negative number') + // Kind of weird to have a default max of Infinity, but oh well. + const max = this[MAX] = options.max || Infinity + + const lc = options.length || naiveLength + this[LENGTH_CALCULATOR] = (typeof lc !== 'function') ? naiveLength : lc + this[ALLOW_STALE] = options.stale || false + if (options.maxAge && typeof options.maxAge !== 'number') + throw new TypeError('maxAge must be a number') + this[MAX_AGE] = options.maxAge || 0 + this[DISPOSE] = options.dispose + this[NO_DISPOSE_ON_SET] = options.noDisposeOnSet || false + this[UPDATE_AGE_ON_GET] = options.updateAgeOnGet || false + this.reset() + } + + // resize the cache when the max changes. + set max (mL) { + if (typeof mL !== 'number' || mL < 0) + throw new TypeError('max must be a non-negative number') + + this[MAX] = mL || Infinity + trim(this) + } + get max () { + return this[MAX] + } + + set allowStale (allowStale) { + this[ALLOW_STALE] = !!allowStale + } + get allowStale () { + return this[ALLOW_STALE] + } + + set maxAge (mA) { + if (typeof mA !== 'number') + throw new TypeError('maxAge must be a non-negative number') + + this[MAX_AGE] = mA + trim(this) + } + get maxAge () { + return this[MAX_AGE] + } + + // resize the cache when the lengthCalculator changes. + set lengthCalculator (lC) { + if (typeof lC !== 'function') + lC = naiveLength + + if (lC !== this[LENGTH_CALCULATOR]) { + this[LENGTH_CALCULATOR] = lC + this[LENGTH] = 0 + this[LRU_LIST].forEach(hit => { + hit.length = this[LENGTH_CALCULATOR](hit.value, hit.key) + this[LENGTH] += hit.length + }) + } + trim(this) + } + get lengthCalculator () { return this[LENGTH_CALCULATOR] } + + get length () { return this[LENGTH] } + get itemCount () { return this[LRU_LIST].length } + + rforEach (fn, thisp) { + thisp = thisp || this + for (let walker = this[LRU_LIST].tail; walker !== null;) { + const prev = walker.prev + forEachStep(this, fn, walker, thisp) + walker = prev + } + } + + forEach (fn, thisp) { + thisp = thisp || this + for (let walker = this[LRU_LIST].head; walker !== null;) { + const next = walker.next + forEachStep(this, fn, walker, thisp) + walker = next + } + } + + keys () { + return this[LRU_LIST].toArray().map(k => k.key) + } + + values () { + return this[LRU_LIST].toArray().map(k => k.value) + } + + reset () { + if (this[DISPOSE] && + this[LRU_LIST] && + this[LRU_LIST].length) { + this[LRU_LIST].forEach(hit => this[DISPOSE](hit.key, hit.value)) + } + + this[CACHE] = new Map() // hash of items by key + this[LRU_LIST] = new Yallist() // list of items in order of use recency + this[LENGTH] = 0 // length of items in the list + } + + dump () { + return this[LRU_LIST].map(hit => + isStale(this, hit) ? false : { + k: hit.key, + v: hit.value, + e: hit.now + (hit.maxAge || 0) + }).toArray().filter(h => h) + } + + dumpLru () { + return this[LRU_LIST] + } + + set (key, value, maxAge) { + maxAge = maxAge || this[MAX_AGE] + + if (maxAge && typeof maxAge !== 'number') + throw new TypeError('maxAge must be a number') + + const now = maxAge ? Date.now() : 0 + const len = this[LENGTH_CALCULATOR](value, key) + + if (this[CACHE].has(key)) { + if (len > this[MAX]) { + del(this, this[CACHE].get(key)) + return false + } + + const node = this[CACHE].get(key) + const item = node.value + + // dispose of the old one before overwriting + // split out into 2 ifs for better coverage tracking + if (this[DISPOSE]) { + if (!this[NO_DISPOSE_ON_SET]) + this[DISPOSE](key, item.value) + } + + item.now = now + item.maxAge = maxAge + item.value = value + this[LENGTH] += len - item.length + item.length = len + this.get(key) + trim(this) + return true + } + + const hit = new Entry(key, value, len, now, maxAge) + + // oversized objects fall out of cache automatically. + if (hit.length > this[MAX]) { + if (this[DISPOSE]) + this[DISPOSE](key, value) + + return false + } + + this[LENGTH] += hit.length + this[LRU_LIST].unshift(hit) + this[CACHE].set(key, this[LRU_LIST].head) + trim(this) + return true + } + + has (key) { + if (!this[CACHE].has(key)) return false + const hit = this[CACHE].get(key).value + return !isStale(this, hit) + } + + get (key) { + return get(this, key, true) + } + + peek (key) { + return get(this, key, false) + } + + pop () { + const node = this[LRU_LIST].tail + if (!node) + return null + + del(this, node) + return node.value + } + + del (key) { + del(this, this[CACHE].get(key)) + } + + load (arr) { + // reset the cache + this.reset() + + const now = Date.now() + // A previous serialized cache has the most recent items first + for (let l = arr.length - 1; l >= 0; l--) { + const hit = arr[l] + const expiresAt = hit.e || 0 + if (expiresAt === 0) + // the item was created without expiration in a non aged cache + this.set(hit.k, hit.v) + else { + const maxAge = expiresAt - now + // dont add already expired items + if (maxAge > 0) { + this.set(hit.k, hit.v, maxAge) + } + } + } + } + + prune () { + this[CACHE].forEach((value, key) => get(this, key, false)) + } +} + +const get = (self, key, doUse) => { + const node = self[CACHE].get(key) + if (node) { + const hit = node.value + if (isStale(self, hit)) { + del(self, node) + if (!self[ALLOW_STALE]) + return undefined + } else { + if (doUse) { + if (self[UPDATE_AGE_ON_GET]) + node.value.now = Date.now() + self[LRU_LIST].unshiftNode(node) + } + } + return hit.value + } +} + +const isStale = (self, hit) => { + if (!hit || (!hit.maxAge && !self[MAX_AGE])) + return false + + const diff = Date.now() - hit.now + return hit.maxAge ? diff > hit.maxAge + : self[MAX_AGE] && (diff > self[MAX_AGE]) +} + +const trim = self => { + if (self[LENGTH] > self[MAX]) { + for (let walker = self[LRU_LIST].tail; + self[LENGTH] > self[MAX] && walker !== null;) { + // We know that we're about to delete this one, and also + // what the next least recently used key will be, so just + // go ahead and set it now. + const prev = walker.prev + del(self, walker) + walker = prev + } + } +} + +const del = (self, node) => { + if (node) { + const hit = node.value + if (self[DISPOSE]) + self[DISPOSE](hit.key, hit.value) + + self[LENGTH] -= hit.length + self[CACHE].delete(hit.key) + self[LRU_LIST].removeNode(node) + } +} + +class Entry { + constructor (key, value, length, now, maxAge) { + this.key = key + this.value = value + this.length = length + this.now = now + this.maxAge = maxAge || 0 + } +} + +const forEachStep = (self, fn, node, thisp) => { + let hit = node.value + if (isStale(self, hit)) { + del(self, node) + if (!self[ALLOW_STALE]) + hit = undefined + } + if (hit) + fn.call(thisp, hit.value, hit.key, self) +} + +module.exports = LRUCache diff --git a/node_modules/lru-cache/package.json b/node_modules/lru-cache/package.json new file mode 100644 index 0000000..d7cad8f --- /dev/null +++ b/node_modules/lru-cache/package.json @@ -0,0 +1,67 @@ +{ + "_from": "lru-cache@^5.0.0", + "_id": "lru-cache@5.1.1", + "_inBundle": false, + "_integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "_location": "/lru-cache", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "lru-cache@^5.0.0", + "name": "lru-cache", + "escapedName": "lru-cache", + "rawSpec": "^5.0.0", + "saveSpec": null, + "fetchSpec": "^5.0.0" + }, + "_requiredBy": [ + "/google-auth-library" + ], + "_resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "_shasum": "1da27e6710271947695daf6848e847f01d84b920", + "_spec": "lru-cache@^5.0.0", + "_where": "/Users/cday/Code/zendesk/fetch-build-from-gcb/node_modules/google-auth-library", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me" + }, + "bugs": { + "url": "https://github.com/isaacs/node-lru-cache/issues" + }, + "bundleDependencies": false, + "dependencies": { + "yallist": "^3.0.2" + }, + "deprecated": false, + "description": "A cache object that deletes the least-recently-used items.", + "devDependencies": { + "benchmark": "^2.1.4", + "tap": "^12.1.0" + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/isaacs/node-lru-cache#readme", + "keywords": [ + "mru", + "lru", + "cache" + ], + "license": "ISC", + "main": "index.js", + "name": "lru-cache", + "repository": { + "type": "git", + "url": "git://github.com/isaacs/node-lru-cache.git" + }, + "scripts": { + "coveragerport": "tap --coverage-report=html", + "postpublish": "git push origin --all; git push origin --tags", + "postversion": "npm publish", + "preversion": "npm test", + "snap": "TAP_SNAPSHOT=1 tap test/*.js -J", + "test": "tap test/*.js --100 -J" + }, + "version": "5.1.1" +} diff --git a/node_modules/mime/.eslintrc.json b/node_modules/mime/.eslintrc.json new file mode 100644 index 0000000..845527f --- /dev/null +++ b/node_modules/mime/.eslintrc.json @@ -0,0 +1,51 @@ +{ + "root": true, + "parserOptions": { + "ecmaVersion": 6 + }, + "env": { + "browser": true, + "commonjs": true, + "node": true, + "mocha": true + }, + "extends": ["eslint:recommended"], + "rules": { + "array-bracket-spacing": ["warn", "never"], + "arrow-body-style": ["warn", "as-needed"], + "arrow-parens": ["warn", "as-needed"], + "arrow-spacing": "warn", + "brace-style": ["warn", "1tbs"], + "camelcase": "warn", + "comma-spacing": ["warn", {"after": true}], + "dot-notation": "warn", + "eqeqeq": ["warn", "smart"], + "indent": ["warn", 2, { + "SwitchCase": 1, + "FunctionDeclaration": {"parameters": 1}, + "MemberExpression": 1, + "CallExpression": {"arguments": 1} + }], + "key-spacing": ["warn", {"beforeColon": false, "afterColon": true, "mode": "minimum"}], + "keyword-spacing": "warn", + "no-console": "off", + "no-empty": "off", + "no-multi-spaces": "warn", + "no-redeclare": "off", + "no-restricted-globals": ["warn", "Promise"], + "no-trailing-spaces": "warn", + "no-undef": "error", + "no-unused-vars": ["warn", {"args": "none"}], + "one-var": ["warn", "never"], + "padded-blocks": ["warn", "never"], + "object-curly-spacing": ["warn", "never"], + "quotes": ["warn", "single"], + "react/prop-types": "off", + "react/jsx-no-bind": "off", + "semi": ["warn", "always"], + "space-before-blocks": ["warn", "always"], + "space-before-function-paren": ["warn", "never"], + "space-in-parens": ["warn", "never"], + "strict": ["warn", "global"] + } +} diff --git a/node_modules/mime/.github/ISSUE_TEMPLATE.md b/node_modules/mime/.github/ISSUE_TEMPLATE.md new file mode 100644 index 0000000..53bf23e --- /dev/null +++ b/node_modules/mime/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,6 @@ +### If you have an issue with a specific extension or type + +Locate the definition for your extension/type in the [db.json file](https://github.com/jshttp/mime-db/blob/master/db.json) in the `mime-db` project. Does it look right? + +- [ ] No. [File a `mime-db` issue](https://github.com/jshttp/mime-db/issues/new). +- [ ] Yes: Go ahead and submit your issue/PR here and I'll look into it. diff --git a/node_modules/mime/.github/PULL_REQUEST_TEMPLATE.md b/node_modules/mime/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..53bf23e --- /dev/null +++ b/node_modules/mime/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,6 @@ +### If you have an issue with a specific extension or type + +Locate the definition for your extension/type in the [db.json file](https://github.com/jshttp/mime-db/blob/master/db.json) in the `mime-db` project. Does it look right? + +- [ ] No. [File a `mime-db` issue](https://github.com/jshttp/mime-db/issues/new). +- [ ] Yes: Go ahead and submit your issue/PR here and I'll look into it. diff --git a/node_modules/mime/.travis.yml b/node_modules/mime/.travis.yml new file mode 100644 index 0000000..045b41b --- /dev/null +++ b/node_modules/mime/.travis.yml @@ -0,0 +1,5 @@ +language: node_js +node_js: + - "6" + - "8" + - "10" diff --git a/node_modules/mime/CHANGELOG.md b/node_modules/mime/CHANGELOG.md new file mode 100644 index 0000000..ba9cd97 --- /dev/null +++ b/node_modules/mime/CHANGELOG.md @@ -0,0 +1,262 @@ +# Changelog + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +### [2.4.4](https://github.com/broofa/node-mime/compare/v2.4.3...v2.4.4) (2019-06-07) + + + +## [2.4.3](https://github.com/broofa/node-mime/compare/v2.4.2...v2.4.3) (2019-05-15) + + + +## [2.4.2](https://github.com/broofa/node-mime/compare/v2.4.1...v2.4.2) (2019-04-07) + + +### Bug Fixes + +* don't use arrow function introduced in 2.4.1 ([2e00b5c](https://github.com/broofa/node-mime/commit/2e00b5c)) + + + +## [2.4.1](https://github.com/broofa/node-mime/compare/v2.4.0...v2.4.1) (2019-04-03) + + +### Bug Fixes + +* update MDN and mime-db types ([3e567a9](https://github.com/broofa/node-mime/commit/3e567a9)) + + + + +# [2.4.0](https://github.com/broofa/node-mime/compare/v2.3.1...v2.4.0) (2018-11-26) + + +### Features + +* Bind exported methods ([9d2a7b8](https://github.com/broofa/node-mime/commit/9d2a7b8)) +* update to mime-db@1.37.0 ([49e6e41](https://github.com/broofa/node-mime/commit/49e6e41)) + + + + +## [2.3.1](https://github.com/broofa/node-mime/compare/v2.3.0...v2.3.1) (2018-04-11) + + +### Bug Fixes + +* fix [#198](https://github.com/broofa/node-mime/issues/198) ([25ca180](https://github.com/broofa/node-mime/commit/25ca180)) + + + + +# [2.3.0](https://github.com/broofa/node-mime/compare/v2.2.2...v2.3.0) (2018-04-11) + + +### Bug Fixes + +* fix [#192](https://github.com/broofa/node-mime/issues/192) ([5c35df6](https://github.com/broofa/node-mime/commit/5c35df6)) + + +### Features + +* add travis-ci testing ([d64160f](https://github.com/broofa/node-mime/commit/d64160f)) + + + + +## [2.2.2](https://github.com/broofa/node-mime/compare/v2.2.1...v2.2.2) (2018-03-30) + + +### Bug Fixes + +* update types files to mime-db@1.32.0 ([85aac16](https://github.com/broofa/node-mime/commit/85aac16)) + + + + +## [2.2.1](https://github.com/broofa/node-mime/compare/v2.2.0...v2.2.1) (2018-03-30) + + +### Bug Fixes + +* Retain type->extension mappings for non-default types. Fixes [#180](https://github.com/broofa/node-mime/issues/180) ([b5c83fb](https://github.com/broofa/node-mime/commit/b5c83fb)) + + + + +# [2.2.0](https://github.com/broofa/node-mime/compare/v2.1.0...v2.2.0) (2018-01-04) + + +### Features + +* Retain type->extension mappings for non-default types. Fixes [#180](https://github.com/broofa/node-mime/issues/180) ([10f82ac](https://github.com/broofa/node-mime/commit/10f82ac)) + + + + +# [2.1.0](https://github.com/broofa/node-mime/compare/v2.0.5...v2.1.0) (2017-12-22) + + +### Features + +* Upgrade to mime-db@1.32.0. Fixes [#185](https://github.com/broofa/node-mime/issues/185) ([3f775ba](https://github.com/broofa/node-mime/commit/3f775ba)) + + + + +## [2.0.5](https://github.com/broofa/node-mime/compare/v2.0.1...v2.0.5) (2017-12-22) + + +### Bug Fixes + +* ES5 support (back to node v0.4) ([f14ccb6](https://github.com/broofa/node-mime/commit/f14ccb6)) + + + +# Changelog + +## v2.0.4 (24/11/2017) +- [**closed**] Switch to mime-score module for resolving extension contention issues. [#182](https://github.com/broofa/node-mime/issues/182) +- [**closed**] Update mime-db to 1.31.0 in v1.x branch [#181](https://github.com/broofa/node-mime/issues/181) + +--- + +## v1.5.0 (22/11/2017) +- [**closed**] need ES5 version ready in npm package [#179](https://github.com/broofa/node-mime/issues/179) +- [**closed**] mime-db no trace of iWork - pages / numbers / etc. [#178](https://github.com/broofa/node-mime/issues/178) +- [**closed**] How it works in brownser ? [#176](https://github.com/broofa/node-mime/issues/176) +- [**closed**] Missing `./Mime` [#175](https://github.com/broofa/node-mime/issues/175) +- [**closed**] Vulnerable Regular Expression [#167](https://github.com/broofa/node-mime/issues/167) + +--- + +## v2.0.3 (25/09/2017) +*No changelog for this release.* + +--- + +## v1.4.1 (25/09/2017) +- [**closed**] Issue when bundling with webpack [#172](https://github.com/broofa/node-mime/issues/172) + +--- + +## v2.0.2 (15/09/2017) +- [**V2**] fs.readFileSync is not a function [#165](https://github.com/broofa/node-mime/issues/165) +- [**closed**] The extension for video/quicktime should map to .mov, not .qt [#164](https://github.com/broofa/node-mime/issues/164) +- [**V2**] [v2 Feedback request] Mime class API [#163](https://github.com/broofa/node-mime/issues/163) +- [**V2**] [v2 Feedback request] Resolving conflicts over extensions [#162](https://github.com/broofa/node-mime/issues/162) +- [**V2**] Allow callers to load module with official, full, or no defined types. [#161](https://github.com/broofa/node-mime/issues/161) +- [**V2**] Use "facets" to resolve extension conflicts [#160](https://github.com/broofa/node-mime/issues/160) +- [**V2**] Remove fs and path dependencies [#152](https://github.com/broofa/node-mime/issues/152) +- [**V2**] Default content-type should not be application/octet-stream [#139](https://github.com/broofa/node-mime/issues/139) +- [**V2**] reset mime-types [#124](https://github.com/broofa/node-mime/issues/124) +- [**V2**] Extensionless paths should return null or false [#113](https://github.com/broofa/node-mime/issues/113) + +--- + +## v2.0.1 (14/09/2017) +- [**closed**] Changelog for v2.0 does not mention breaking changes [#171](https://github.com/broofa/node-mime/issues/171) +- [**closed**] MIME breaking with 'class' declaration as it is without 'use strict mode' [#170](https://github.com/broofa/node-mime/issues/170) + +--- + +## v2.0.0 (12/09/2017) +- [**closed**] woff and woff2 [#168](https://github.com/broofa/node-mime/issues/168) + +--- + +## v1.4.0 (28/08/2017) +- [**closed**] support for ac3 voc files [#159](https://github.com/broofa/node-mime/issues/159) +- [**closed**] Help understanding change from application/xml to text/xml [#158](https://github.com/broofa/node-mime/issues/158) +- [**closed**] no longer able to override mimetype [#157](https://github.com/broofa/node-mime/issues/157) +- [**closed**] application/vnd.adobe.photoshop [#147](https://github.com/broofa/node-mime/issues/147) +- [**closed**] Directories should appear as something other than application/octet-stream [#135](https://github.com/broofa/node-mime/issues/135) +- [**closed**] requested features [#131](https://github.com/broofa/node-mime/issues/131) +- [**closed**] Make types.json loading optional? [#129](https://github.com/broofa/node-mime/issues/129) +- [**closed**] Cannot find module './types.json' [#120](https://github.com/broofa/node-mime/issues/120) +- [**V2**] .wav files show up as "audio/x-wav" instead of "audio/x-wave" [#118](https://github.com/broofa/node-mime/issues/118) +- [**closed**] Don't be a pain in the ass for node community [#108](https://github.com/broofa/node-mime/issues/108) +- [**closed**] don't make default_type global [#78](https://github.com/broofa/node-mime/issues/78) +- [**closed**] mime.extension() fails if the content-type is parameterized [#74](https://github.com/broofa/node-mime/issues/74) + +--- + +## v1.3.6 (11/05/2017) +- [**closed**] .md should be text/markdown as of March 2016 [#154](https://github.com/broofa/node-mime/issues/154) +- [**closed**] Error while installing mime [#153](https://github.com/broofa/node-mime/issues/153) +- [**closed**] application/manifest+json [#149](https://github.com/broofa/node-mime/issues/149) +- [**closed**] Dynamic adaptive streaming over HTTP (DASH) file extension typo [#141](https://github.com/broofa/node-mime/issues/141) +- [**closed**] charsets image/png undefined [#140](https://github.com/broofa/node-mime/issues/140) +- [**closed**] Mime-db dependency out of date [#130](https://github.com/broofa/node-mime/issues/130) +- [**closed**] how to support plist? [#126](https://github.com/broofa/node-mime/issues/126) +- [**closed**] how does .types file format look like? [#123](https://github.com/broofa/node-mime/issues/123) +- [**closed**] Feature: support for expanding MIME patterns [#121](https://github.com/broofa/node-mime/issues/121) +- [**closed**] DEBUG_MIME doesn't work [#117](https://github.com/broofa/node-mime/issues/117) + +--- + +## v1.3.4 (06/02/2015) +*No changelog for this release.* + +--- + +## v1.3.3 (06/02/2015) +*No changelog for this release.* + +--- + +## v1.3.1 (05/02/2015) +- [**closed**] Consider adding support for Handlebars .hbs file ending [#111](https://github.com/broofa/node-mime/issues/111) +- [**closed**] Consider adding support for hjson. [#110](https://github.com/broofa/node-mime/issues/110) +- [**closed**] Add mime type for Opus audio files [#94](https://github.com/broofa/node-mime/issues/94) +- [**closed**] Consider making the `Requesting New Types` information more visible [#77](https://github.com/broofa/node-mime/issues/77) + +--- + +## v1.3.0 (05/02/2015) +- [**closed**] Add common name? [#114](https://github.com/broofa/node-mime/issues/114) +- [**closed**] application/x-yaml [#104](https://github.com/broofa/node-mime/issues/104) +- [**closed**] Add mime type for WOFF file format 2.0 [#102](https://github.com/broofa/node-mime/issues/102) +- [**closed**] application/x-msi for .msi [#99](https://github.com/broofa/node-mime/issues/99) +- [**closed**] Add mimetype for gettext translation files [#98](https://github.com/broofa/node-mime/issues/98) +- [**closed**] collaborators [#88](https://github.com/broofa/node-mime/issues/88) +- [**closed**] getting errot in installation of mime module...any1 can help? [#87](https://github.com/broofa/node-mime/issues/87) +- [**closed**] should application/json's charset be utf8? [#86](https://github.com/broofa/node-mime/issues/86) +- [**closed**] Add "license" and "licenses" to package.json [#81](https://github.com/broofa/node-mime/issues/81) +- [**closed**] lookup with extension-less file on Windows returns wrong type [#68](https://github.com/broofa/node-mime/issues/68) + +--- + +## v1.2.11 (15/08/2013) +- [**closed**] Update mime.types [#65](https://github.com/broofa/node-mime/issues/65) +- [**closed**] Publish a new version [#63](https://github.com/broofa/node-mime/issues/63) +- [**closed**] README should state upfront that "application/octet-stream" is default for unknown extension [#55](https://github.com/broofa/node-mime/issues/55) +- [**closed**] Suggested improvement to the charset API [#52](https://github.com/broofa/node-mime/issues/52) + +--- + +## v1.2.10 (25/07/2013) +- [**closed**] Mime type for woff files should be application/font-woff and not application/x-font-woff [#62](https://github.com/broofa/node-mime/issues/62) +- [**closed**] node.types in conflict with mime.types [#51](https://github.com/broofa/node-mime/issues/51) + +--- + +## v1.2.9 (17/01/2013) +- [**closed**] Please update "mime" NPM [#49](https://github.com/broofa/node-mime/issues/49) +- [**closed**] Please add semicolon [#46](https://github.com/broofa/node-mime/issues/46) +- [**closed**] parse full mime types [#43](https://github.com/broofa/node-mime/issues/43) + +--- + +## v1.2.8 (10/01/2013) +- [**closed**] /js directory mime is application/javascript. Is it correct? [#47](https://github.com/broofa/node-mime/issues/47) +- [**closed**] Add mime types for lua code. [#45](https://github.com/broofa/node-mime/issues/45) + +--- + +## v1.2.7 (19/10/2012) +- [**closed**] cannot install 1.2.7 via npm [#41](https://github.com/broofa/node-mime/issues/41) +- [**closed**] Transfer ownership to @broofa [#36](https://github.com/broofa/node-mime/issues/36) +- [**closed**] it's wrong to set charset to UTF-8 for text [#30](https://github.com/broofa/node-mime/issues/30) +- [**closed**] Allow multiple instances of MIME types container [#27](https://github.com/broofa/node-mime/issues/27) diff --git a/node_modules/mime/CONTRIBUTING.md b/node_modules/mime/CONTRIBUTING.md new file mode 100644 index 0000000..dd5c86a --- /dev/null +++ b/node_modules/mime/CONTRIBUTING.md @@ -0,0 +1,5 @@ +1. Commit messages should have a [Conventional Commit](https://conventionalcommits.org/) prefix. +2. If you're editing the `types/*` files, just stop. These are auto-generated from [mime-db](https://github.com/jshttp/mime-db). Go talk to those folks. +3. README edits should be made to [src/README_md.js](src/README_md.js). + +Thanks for helping out with this project. You rock! diff --git a/node_modules/mime/LICENSE b/node_modules/mime/LICENSE new file mode 100644 index 0000000..d3f46f7 --- /dev/null +++ b/node_modules/mime/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2010 Benjamin Thomas, Robert Kieffer + +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. diff --git a/node_modules/mime/Mime.js b/node_modules/mime/Mime.js new file mode 100644 index 0000000..7fe3921 --- /dev/null +++ b/node_modules/mime/Mime.js @@ -0,0 +1,95 @@ +'use strict'; + +/** + * @param typeMap [Object] Map of MIME type -> Array[extensions] + * @param ... + */ +function Mime() { + this._types = Object.create(null); + this._extensions = Object.create(null); + + for (var i = 0; i < arguments.length; i++) { + this.define(arguments[i]); + } + + this.define = this.define.bind(this); + this.getType = this.getType.bind(this); + this.getExtension = this.getExtension.bind(this); +} + +/** + * Define mimetype -> extension mappings. Each key is a mime-type that maps + * to an array of extensions associated with the type. The first extension is + * used as the default extension for the type. + * + * e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']}); + * + * If a type declares an extension that has already been defined, an error will + * be thrown. To suppress this error and force the extension to be associated + * with the new type, pass `force`=true. Alternatively, you may prefix the + * extension with "*" to map the type to extension, without mapping the + * extension to the type. + * + * e.g. mime.define({'audio/wav', ['wav']}, {'audio/x-wav', ['*wav']}); + * + * + * @param map (Object) type definitions + * @param force (Boolean) if true, force overriding of existing definitions + */ +Mime.prototype.define = function(typeMap, force) { + for (var type in typeMap) { + var extensions = typeMap[type].map(function(t) {return t.toLowerCase()}); + type = type.toLowerCase(); + + for (var i = 0; i < extensions.length; i++) { + var ext = extensions[i]; + + // '*' prefix = not the preferred type for this extension. So fixup the + // extension, and skip it. + if (ext[0] == '*') { + continue; + } + + if (!force && (ext in this._types)) { + throw new Error( + 'Attempt to change mapping for "' + ext + + '" extension from "' + this._types[ext] + '" to "' + type + + '". Pass `force=true` to allow this, otherwise remove "' + ext + + '" from the list of extensions for "' + type + '".' + ); + } + + this._types[ext] = type; + } + + // Use first extension as default + if (force || !this._extensions[type]) { + var ext = extensions[0]; + this._extensions[type] = (ext[0] != '*') ? ext : ext.substr(1) + } + } +}; + +/** + * Lookup a mime type based on extension + */ +Mime.prototype.getType = function(path) { + path = String(path); + var last = path.replace(/^.*[/\\]/, '').toLowerCase(); + var ext = last.replace(/^.*\./, '').toLowerCase(); + + var hasPath = last.length < path.length; + var hasDot = ext.length < last.length - 1; + + return (hasDot || !hasPath) && this._types[ext] || null; +}; + +/** + * Return file extension associated with a mime type + */ +Mime.prototype.getExtension = function(type) { + type = /^\s*([^;\s]*)/.test(type) && RegExp.$1; + return type && this._extensions[type.toLowerCase()] || null; +}; + +module.exports = Mime; diff --git a/node_modules/mime/README.md b/node_modules/mime/README.md new file mode 100644 index 0000000..37bd2b8 --- /dev/null +++ b/node_modules/mime/README.md @@ -0,0 +1,193 @@ + +# Mime + +A comprehensive, compact MIME type module. + +[![Build Status](https://travis-ci.org/broofa/node-mime.svg?branch=master)](https://travis-ci.org/broofa/node-mime) + +## Version 2 Notes + +Version 2 is a breaking change from 1.x as the semver implies. Specifically: + +* `lookup()` renamed to `getType()` +* `extension()` renamed to `getExtension()` +* `charset()` and `load()` methods have been removed + +If you prefer the legacy version of this module please `npm install mime@^1`. Version 1 docs may be found [here](https://github.com/broofa/node-mime/tree/v1.4.0). + +## Install + +### NPM +``` +npm install mime +``` + +### Browser + +It is recommended that you use a bundler such as +[webpack](https://webpack.github.io/) or [browserify](http://browserify.org/) to +package your code. However, browser-ready versions are available via wzrd.in. +E.g. For the full version: + + + + + + +``` + +### unpkg CDN + +To use it via [unpkg](https://unpkg.com/#/) include this in your html: + +```html + +``` + +### Development Requirements + +The core JavaScript has the following requirements to build and test: + +* Building a browser bundle: + * Node.js + * npm +* Testing + * Node.js + * npm + * Chrome, Firefox, Safari (optional) + +Some special networking features can optionally use a Flash component. See the +[Flash README](./flash/README.md) for details. + +### Building for a web browser + +To create single file bundles for use with browsers run the following: + + npm install + npm run build + +This will create single non-minimized and minimized files that can be +included in the browser: + + dist/forge.js + dist/forge.min.js + +A bundle that adds some utilities and networking support is also available: + + dist/forge.all.js + dist/forge.all.min.js + +Include the file via: + +```html + +``` +or +```html + +``` + +The above bundles will synchronously create a global 'forge' object. + +**Note**: These bundles will not include any WebWorker scripts (eg: +`dist/prime.worker.js`), so these will need to be accessible from the browser +if any WebWorkers are used. + +### Building a custom browser bundle + +The build process uses [webpack][] and the [config](./webpack.config.js) file +can be modified to generate a file or files that only contain the parts of +forge you need. + +[Browserify][] override support is also present in `package.json`. + +Testing +------- + +### Prepare to run tests + + npm install + +### Running automated tests with Node.js + +Forge natively runs in a [Node.js][] environment: + + npm test + +### Running automated tests with Headless Chrome + +Automated testing is done via [Karma][]. By default it will run the tests with +Headless Chrome. + + npm run test-karma + +Is 'mocha' reporter output too verbose? Other reporters are available. Try +'dots', 'progress', or 'tap'. + + npm run test-karma -- --reporters progress + +By default [webpack][] is used. [Browserify][] can also be used. + + BUNDLER=browserify npm run test-karma + +### Running automated tests with one or more browsers + +You can also specify one or more browsers to use. + + npm run test-karma -- --browsers Chrome,Firefox,Safari,ChromeHeadless + +The reporter option and `BUNDLER` environment variable can also be used. + +### Running manual tests in a browser + +Testing in a browser uses [webpack][] to combine forge and all tests and then +loading the result in a browser. A simple web server is provided that will +output the HTTP or HTTPS URLs to load. It also will start a simple Flash Policy +Server. Unit tests and older legacy tests are provided. Custom ports can be +used by running `node tests/server.js` manually. + +To run the unit tests in a browser a special forge build is required: + + npm run test-build + +To run legacy browser based tests the main forge build is required: + + npm run build + +The tests are run with a custom server that prints out the URLs to use: + + npm run test-server + +### Running other tests + +There are some other random tests and benchmarks available in the tests +directory. + +### Coverage testing + +To perform coverage testing of the unit tests, run the following. The results +will be put in the `coverage/` directory. Note that coverage testing can slow +down some tests considerably. + + npm install + npm run coverage + +Contributing +------------ + +Any contributions (eg: PRs) that are accepted will be brought under the same +license used by the rest of the Forge project. This license allows Forge to +be used under the terms of either the BSD License or the GNU General Public +License (GPL) Version 2. + +See: [LICENSE](https://github.com/digitalbazaar/forge/blob/cbebca3780658703d925b61b2caffb1d263a6c1d/LICENSE) + +If a contribution contains 3rd party source code with its own license, it +may retain it, so long as that license is compatible with the Forge license. + +API +--- + + + +### Options + +If at any time you wish to disable the use of native code, where available, +for particular forge features like its secure random number generator, you +may set the ```forge.options.usePureJavaScript``` flag to ```true```. It is +not recommended that you set this flag as native code is typically more +performant and may have stronger security properties. It may be useful to +set this flag to test certain features that you plan to run in environments +that are different from your testing environment. + +To disable native code when including forge in the browser: + +```js +// run this *after* including the forge script +forge.options.usePureJavaScript = true; +``` + +To disable native code when using Node.js: + +```js +var forge = require('node-forge'); +forge.options.usePureJavaScript = true; +``` + +Transports +---------- + + + +### TLS + +Provides a native javascript client and server-side [TLS][] implementation. + +__Examples__ + +```js +// create TLS client +var client = forge.tls.createConnection({ + server: false, + caStore: /* Array of PEM-formatted certs or a CA store object */, + sessionCache: {}, + // supported cipher suites in order of preference + cipherSuites: [ + forge.tls.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA, + forge.tls.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA], + virtualHost: 'example.com', + verify: function(connection, verified, depth, certs) { + if(depth === 0) { + var cn = certs[0].subject.getField('CN').value; + if(cn !== 'example.com') { + verified = { + alert: forge.tls.Alert.Description.bad_certificate, + message: 'Certificate common name does not match hostname.' + }; + } + } + return verified; + }, + connected: function(connection) { + console.log('connected'); + // send message to server + connection.prepare(forge.util.encodeUtf8('Hi server!')); + /* NOTE: experimental, start heartbeat retransmission timer + myHeartbeatTimer = setInterval(function() { + connection.prepareHeartbeatRequest(forge.util.createBuffer('1234')); + }, 5*60*1000);*/ + }, + /* provide a client-side cert if you want + getCertificate: function(connection, hint) { + return myClientCertificate; + }, + /* the private key for the client-side cert if provided */ + getPrivateKey: function(connection, cert) { + return myClientPrivateKey; + }, + tlsDataReady: function(connection) { + // TLS data (encrypted) is ready to be sent to the server + sendToServerSomehow(connection.tlsData.getBytes()); + // if you were communicating with the server below, you'd do: + // server.process(connection.tlsData.getBytes()); + }, + dataReady: function(connection) { + // clear data from the server is ready + console.log('the server sent: ' + + forge.util.decodeUtf8(connection.data.getBytes())); + // close connection + connection.close(); + }, + /* NOTE: experimental + heartbeatReceived: function(connection, payload) { + // restart retransmission timer, look at payload + clearInterval(myHeartbeatTimer); + myHeartbeatTimer = setInterval(function() { + connection.prepareHeartbeatRequest(forge.util.createBuffer('1234')); + }, 5*60*1000); + payload.getBytes(); + },*/ + closed: function(connection) { + console.log('disconnected'); + }, + error: function(connection, error) { + console.log('uh oh', error); + } +}); + +// start the handshake process +client.handshake(); + +// when encrypted TLS data is received from the server, process it +client.process(encryptedBytesFromServer); + +// create TLS server +var server = forge.tls.createConnection({ + server: true, + caStore: /* Array of PEM-formatted certs or a CA store object */, + sessionCache: {}, + // supported cipher suites in order of preference + cipherSuites: [ + forge.tls.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA, + forge.tls.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA], + // require a client-side certificate if you want + verifyClient: true, + verify: function(connection, verified, depth, certs) { + if(depth === 0) { + var cn = certs[0].subject.getField('CN').value; + if(cn !== 'the-client') { + verified = { + alert: forge.tls.Alert.Description.bad_certificate, + message: 'Certificate common name does not match expected client.' + }; + } + } + return verified; + }, + connected: function(connection) { + console.log('connected'); + // send message to client + connection.prepare(forge.util.encodeUtf8('Hi client!')); + /* NOTE: experimental, start heartbeat retransmission timer + myHeartbeatTimer = setInterval(function() { + connection.prepareHeartbeatRequest(forge.util.createBuffer('1234')); + }, 5*60*1000);*/ + }, + getCertificate: function(connection, hint) { + return myServerCertificate; + }, + getPrivateKey: function(connection, cert) { + return myServerPrivateKey; + }, + tlsDataReady: function(connection) { + // TLS data (encrypted) is ready to be sent to the client + sendToClientSomehow(connection.tlsData.getBytes()); + // if you were communicating with the client above you'd do: + // client.process(connection.tlsData.getBytes()); + }, + dataReady: function(connection) { + // clear data from the client is ready + console.log('the client sent: ' + + forge.util.decodeUtf8(connection.data.getBytes())); + // close connection + connection.close(); + }, + /* NOTE: experimental + heartbeatReceived: function(connection, payload) { + // restart retransmission timer, look at payload + clearInterval(myHeartbeatTimer); + myHeartbeatTimer = setInterval(function() { + connection.prepareHeartbeatRequest(forge.util.createBuffer('1234')); + }, 5*60*1000); + payload.getBytes(); + },*/ + closed: function(connection) { + console.log('disconnected'); + }, + error: function(connection, error) { + console.log('uh oh', error); + } +}); + +// when encrypted TLS data is received from the client, process it +server.process(encryptedBytesFromClient); +``` + +Connect to a TLS server using node's net.Socket: + +```js +var socket = new net.Socket(); + +var client = forge.tls.createConnection({ + server: false, + verify: function(connection, verified, depth, certs) { + // skip verification for testing + console.log('[tls] server certificate verified'); + return true; + }, + connected: function(connection) { + console.log('[tls] connected'); + // prepare some data to send (note that the string is interpreted as + // 'binary' encoded, which works for HTTP which only uses ASCII, use + // forge.util.encodeUtf8(str) otherwise + client.prepare('GET / HTTP/1.0\r\n\r\n'); + }, + tlsDataReady: function(connection) { + // encrypted data is ready to be sent to the server + var data = connection.tlsData.getBytes(); + socket.write(data, 'binary'); // encoding should be 'binary' + }, + dataReady: function(connection) { + // clear data from the server is ready + var data = connection.data.getBytes(); + console.log('[tls] data received from the server: ' + data); + }, + closed: function() { + console.log('[tls] disconnected'); + }, + error: function(connection, error) { + console.log('[tls] error', error); + } +}); + +socket.on('connect', function() { + console.log('[socket] connected'); + client.handshake(); +}); +socket.on('data', function(data) { + client.process(data.toString('binary')); // encoding should be 'binary' +}); +socket.on('end', function() { + console.log('[socket] disconnected'); +}); + +// connect to google.com +socket.connect(443, 'google.com'); + +// or connect to gmail's imap server (but don't send the HTTP header above) +//socket.connect(993, 'imap.gmail.com'); +``` + + + +### HTTP + +Provides a native [JavaScript][] mini-implementation of an http client that +uses pooled sockets. + +__Examples__ + +```js +// create an HTTP GET request +var request = forge.http.createRequest({method: 'GET', path: url.path}); + +// send the request somewhere +sendSomehow(request.toString()); + +// receive response +var buffer = forge.util.createBuffer(); +var response = forge.http.createResponse(); +var someAsyncDataHandler = function(bytes) { + if(!response.bodyReceived) { + buffer.putBytes(bytes); + if(!response.headerReceived) { + if(response.readHeader(buffer)) { + console.log('HTTP response header: ' + response.toString()); + } + } + if(response.headerReceived && !response.bodyReceived) { + if(response.readBody(buffer)) { + console.log('HTTP response body: ' + response.body); + } + } + } +}; +``` + + + +### SSH + +Provides some SSH utility functions. + +__Examples__ + +```js +// encodes (and optionally encrypts) a private RSA key as a Putty PPK file +forge.ssh.privateKeyToPutty(privateKey, passphrase, comment); + +// encodes a public RSA key as an OpenSSH file +forge.ssh.publicKeyToOpenSSH(key, comment); + +// encodes a private RSA key as an OpenSSH file +forge.ssh.privateKeyToOpenSSH(privateKey, passphrase); + +// gets the SSH public key fingerprint in a byte buffer +forge.ssh.getPublicKeyFingerprint(key); + +// gets a hex-encoded, colon-delimited SSH public key fingerprint +forge.ssh.getPublicKeyFingerprint(key, {encoding: 'hex', delimiter: ':'}); +``` + + + +### XHR + +Provides an XmlHttpRequest implementation using forge.http as a backend. + +__Examples__ + +```js +// TODO +``` + + + +### Sockets + +Provides an interface to create and use raw sockets provided via Flash. + +__Examples__ + +```js +// TODO +``` + +Ciphers +------- + + + +### CIPHER + +Provides a basic API for block encryption and decryption. There is built-in +support for the ciphers: [AES][], [3DES][], and [DES][], and for the modes +of operation: [ECB][], [CBC][], [CFB][], [OFB][], [CTR][], and [GCM][]. + +These algorithms are currently supported: + +* AES-ECB +* AES-CBC +* AES-CFB +* AES-OFB +* AES-CTR +* AES-GCM +* 3DES-ECB +* 3DES-CBC +* DES-ECB +* DES-CBC + +When using an [AES][] algorithm, the key size will determine whether +AES-128, AES-192, or AES-256 is used (all are supported). When a [DES][] +algorithm is used, the key size will determine whether [3DES][] or regular +[DES][] is used. Use a [3DES][] algorithm to enforce Triple-DES. + +__Examples__ + +```js +// generate a random key and IV +// Note: a key size of 16 bytes will use AES-128, 24 => AES-192, 32 => AES-256 +var key = forge.random.getBytesSync(16); +var iv = forge.random.getBytesSync(16); + +/* alternatively, generate a password-based 16-byte key +var salt = forge.random.getBytesSync(128); +var key = forge.pkcs5.pbkdf2('password', salt, numIterations, 16); +*/ + +// encrypt some bytes using CBC mode +// (other modes include: ECB, CFB, OFB, CTR, and GCM) +// Note: CBC and ECB modes use PKCS#7 padding as default +var cipher = forge.cipher.createCipher('AES-CBC', key); +cipher.start({iv: iv}); +cipher.update(forge.util.createBuffer(someBytes)); +cipher.finish(); +var encrypted = cipher.output; +// outputs encrypted hex +console.log(encrypted.toHex()); + +// decrypt some bytes using CBC mode +// (other modes include: CFB, OFB, CTR, and GCM) +var decipher = forge.cipher.createDecipher('AES-CBC', key); +decipher.start({iv: iv}); +decipher.update(encrypted); +var result = decipher.finish(); // check 'result' for true/false +// outputs decrypted hex +console.log(decipher.output.toHex()); + +// decrypt bytes using CBC mode and streaming +// Performance can suffer for large multi-MB inputs due to buffer +// manipulations. Stream processing in chunks can offer significant +// improvement. CPU intensive update() calls could also be performed with +// setImmediate/setTimeout to avoid blocking the main browser UI thread (not +// shown here). Optimal block size depends on the JavaScript VM and other +// factors. Encryption can use a simple technique for increased performance. +var encryptedBytes = encrypted.bytes(); +var decipher = forge.cipher.createDecipher('AES-CBC', key); +decipher.start({iv: iv}); +var length = encryptedBytes.length; +var chunkSize = 1024 * 64; +var index = 0; +var decrypted = ''; +do { + decrypted += decipher.output.getBytes(); + var buf = forge.util.createBuffer(encryptedBytes.substr(index, chunkSize)); + decipher.update(buf); + index += chunkSize; +} while(index < length); +var result = decipher.finish(); +assert(result); +decrypted += decipher.output.getBytes(); +console.log(forge.util.bytesToHex(decrypted)); + +// encrypt some bytes using GCM mode +var cipher = forge.cipher.createCipher('AES-GCM', key); +cipher.start({ + iv: iv, // should be a 12-byte binary-encoded string or byte buffer + additionalData: 'binary-encoded string', // optional + tagLength: 128 // optional, defaults to 128 bits +}); +cipher.update(forge.util.createBuffer(someBytes)); +cipher.finish(); +var encrypted = cipher.output; +var tag = cipher.mode.tag; +// outputs encrypted hex +console.log(encrypted.toHex()); +// outputs authentication tag +console.log(tag.toHex()); + +// decrypt some bytes using GCM mode +var decipher = forge.cipher.createDecipher('AES-GCM', key); +decipher.start({ + iv: iv, + additionalData: 'binary-encoded string', // optional + tagLength: 128, // optional, defaults to 128 bits + tag: tag // authentication tag from encryption +}); +decipher.update(encrypted); +var pass = decipher.finish(); +// pass is false if there was a failure (eg: authentication tag didn't match) +if(pass) { + // outputs decrypted hex + console.log(decipher.output.toHex()); +} +``` + +Using forge in Node.js to match openssl's "enc" command line tool (**Note**: OpenSSL "enc" uses a non-standard file format with a custom key derivation function and a fixed iteration count of 1, which some consider less secure than alternatives such as [OpenPGP](https://tools.ietf.org/html/rfc4880)/[GnuPG](https://www.gnupg.org/)): + +```js +var forge = require('node-forge'); +var fs = require('fs'); + +// openssl enc -des3 -in input.txt -out input.enc +function encrypt(password) { + var input = fs.readFileSync('input.txt', {encoding: 'binary'}); + + // 3DES key and IV sizes + var keySize = 24; + var ivSize = 8; + + // get derived bytes + // Notes: + // 1. If using an alternative hash (eg: "-md sha1") pass + // "forge.md.sha1.create()" as the final parameter. + // 2. If using "-nosalt", set salt to null. + var salt = forge.random.getBytesSync(8); + // var md = forge.md.sha1.create(); // "-md sha1" + var derivedBytes = forge.pbe.opensslDeriveBytes( + password, salt, keySize + ivSize/*, md*/); + var buffer = forge.util.createBuffer(derivedBytes); + var key = buffer.getBytes(keySize); + var iv = buffer.getBytes(ivSize); + + var cipher = forge.cipher.createCipher('3DES-CBC', key); + cipher.start({iv: iv}); + cipher.update(forge.util.createBuffer(input, 'binary')); + cipher.finish(); + + var output = forge.util.createBuffer(); + + // if using a salt, prepend this to the output: + if(salt !== null) { + output.putBytes('Salted__'); // (add to match openssl tool output) + output.putBytes(salt); + } + output.putBuffer(cipher.output); + + fs.writeFileSync('input.enc', output.getBytes(), {encoding: 'binary'}); +} + +// openssl enc -d -des3 -in input.enc -out input.dec.txt +function decrypt(password) { + var input = fs.readFileSync('input.enc', {encoding: 'binary'}); + + // parse salt from input + input = forge.util.createBuffer(input, 'binary'); + // skip "Salted__" (if known to be present) + input.getBytes('Salted__'.length); + // read 8-byte salt + var salt = input.getBytes(8); + + // Note: if using "-nosalt", skip above parsing and use + // var salt = null; + + // 3DES key and IV sizes + var keySize = 24; + var ivSize = 8; + + var derivedBytes = forge.pbe.opensslDeriveBytes( + password, salt, keySize + ivSize); + var buffer = forge.util.createBuffer(derivedBytes); + var key = buffer.getBytes(keySize); + var iv = buffer.getBytes(ivSize); + + var decipher = forge.cipher.createDecipher('3DES-CBC', key); + decipher.start({iv: iv}); + decipher.update(input); + var result = decipher.finish(); // check 'result' for true/false + + fs.writeFileSync( + 'input.dec.txt', decipher.output.getBytes(), {encoding: 'binary'}); +} +``` + + + +### AES + +Provides [AES][] encryption and decryption in [CBC][], [CFB][], [OFB][], +[CTR][], and [GCM][] modes. See [CIPHER](#cipher) for examples. + + + +### DES + +Provides [3DES][] and [DES][] encryption and decryption in [ECB][] and +[CBC][] modes. See [CIPHER](#cipher) for examples. + + + +### RC2 + +__Examples__ + +```js +// generate a random key and IV +var key = forge.random.getBytesSync(16); +var iv = forge.random.getBytesSync(8); + +// encrypt some bytes +var cipher = forge.rc2.createEncryptionCipher(key); +cipher.start(iv); +cipher.update(forge.util.createBuffer(someBytes)); +cipher.finish(); +var encrypted = cipher.output; +// outputs encrypted hex +console.log(encrypted.toHex()); + +// decrypt some bytes +var cipher = forge.rc2.createDecryptionCipher(key); +cipher.start(iv); +cipher.update(encrypted); +cipher.finish(); +// outputs decrypted hex +console.log(cipher.output.toHex()); +``` + +PKI +--- + +Provides [X.509][] certificate support, ED25519 key generation and +signing/verifying, and RSA public and private key encoding, decoding, +encryption/decryption, and signing/verifying. + + + +### ED25519 + +Special thanks to [TweetNaCl.js][] for providing the bulk of the implementation. + +__Examples__ + +```js +var ed25519 = forge.pki.ed25519; + +// generate a random ED25519 keypair +var keypair = ed25519.generateKeyPair(); +// `keypair.publicKey` is a node.js Buffer or Uint8Array +// `keypair.privateKey` is a node.js Buffer or Uint8Array + +// generate a random ED25519 keypair based on a random 32-byte seed +var seed = forge.random.getBytesSync(32); +var keypair = ed25519.generateKeyPair({seed: seed}); + +// generate a random ED25519 keypair based on a "password" 32-byte seed +var password = 'Mai9ohgh6ahxee0jutheew0pungoozil'; +var seed = new forge.util.ByteBuffer(password, 'utf8'); +var keypair = ed25519.generateKeyPair({seed: seed}); + +// sign a UTF-8 message +var signature = ED25519.sign({ + message: 'test', + // also accepts `binary` if you want to pass a binary string + encoding: 'utf8', + // node.js Buffer, Uint8Array, forge ByteBuffer, binary string + privateKey: privateKey +}); +// `signature` is a node.js Buffer or Uint8Array + +// sign a message passed as a buffer +var signature = ED25519.sign({ + // also accepts a forge ByteBuffer or Uint8Array + message: Buffer.from('test', 'utf8'), + privateKey: privateKey +}); + +// sign a message digest (shorter "message" == better performance) +var md = forge.md.sha256.create(); +md.update('test', 'utf8'); +var signature = ED25519.sign({ + md: md, + privateKey: privateKey +}); + +// verify a signature on a UTF-8 message +var verified = ED25519.verify({ + message: 'test', + encoding: 'utf8', + // node.js Buffer, Uint8Array, forge ByteBuffer, or binary string + signature: signature, + // node.js Buffer, Uint8Array, forge ByteBuffer, or binary string + publicKey: publicKey +}); +// `verified` is true/false + +// sign a message passed as a buffer +var verified = ED25519.verify({ + // also accepts a forge ByteBuffer or Uint8Array + message: Buffer.from('test', 'utf8'), + // node.js Buffer, Uint8Array, forge ByteBuffer, or binary string + signature: signature, + // node.js Buffer, Uint8Array, forge ByteBuffer, or binary string + publicKey: publicKey +}); + +// verify a signature on a message digest +var md = forge.md.sha256.create(); +md.update('test', 'utf8'); +var verified = ED25519.verify({ + md: md, + // node.js Buffer, Uint8Array, forge ByteBuffer, or binary string + signature: signature, + // node.js Buffer, Uint8Array, forge ByteBuffer, or binary string + publicKey: publicKey +}); +``` + + + +### RSA + +__Examples__ + +```js +var rsa = forge.pki.rsa; + +// generate an RSA key pair synchronously +// *NOT RECOMMENDED*: Can be significantly slower than async and may block +// JavaScript execution. Will use native Node.js 10.12.0+ API if possible. +var keypair = rsa.generateKeyPair({bits: 2048, e: 0x10001}); + +// generate an RSA key pair asynchronously (uses web workers if available) +// use workers: -1 to run a fast core estimator to optimize # of workers +// *RECOMMENDED*: Can be significantly faster than sync. Will use native +// Node.js 10.12.0+ or WebCrypto API if possible. +rsa.generateKeyPair({bits: 2048, workers: 2}, function(err, keypair) { + // keypair.privateKey, keypair.publicKey +}); + +// generate an RSA key pair in steps that attempt to run for a specified period +// of time on the main JS thread +var state = rsa.createKeyPairGenerationState(2048, 0x10001); +var step = function() { + // run for 100 ms + if(!rsa.stepKeyPairGenerationState(state, 100)) { + setTimeout(step, 1); + } + else { + // done, turn off progress indicator, use state.keys + } +}; +// turn on progress indicator, schedule generation to run +setTimeout(step); + +// sign data with a private key and output DigestInfo DER-encoded bytes +// (defaults to RSASSA PKCS#1 v1.5) +var md = forge.md.sha1.create(); +md.update('sign this', 'utf8'); +var signature = privateKey.sign(md); + +// verify data with a public key +// (defaults to RSASSA PKCS#1 v1.5) +var verified = publicKey.verify(md.digest().bytes(), signature); + +// sign data using RSASSA-PSS where PSS uses a SHA-1 hash, a SHA-1 based +// masking function MGF1, and a 20 byte salt +var md = forge.md.sha1.create(); +md.update('sign this', 'utf8'); +var pss = forge.pss.create({ + md: forge.md.sha1.create(), + mgf: forge.mgf.mgf1.create(forge.md.sha1.create()), + saltLength: 20 + // optionally pass 'prng' with a custom PRNG implementation + // optionalls pass 'salt' with a forge.util.ByteBuffer w/custom salt +}); +var signature = privateKey.sign(md, pss); + +// verify RSASSA-PSS signature +var pss = forge.pss.create({ + md: forge.md.sha1.create(), + mgf: forge.mgf.mgf1.create(forge.md.sha1.create()), + saltLength: 20 + // optionally pass 'prng' with a custom PRNG implementation +}); +var md = forge.md.sha1.create(); +md.update('sign this', 'utf8'); +publicKey.verify(md.digest().getBytes(), signature, pss); + +// encrypt data with a public key (defaults to RSAES PKCS#1 v1.5) +var encrypted = publicKey.encrypt(bytes); + +// decrypt data with a private key (defaults to RSAES PKCS#1 v1.5) +var decrypted = privateKey.decrypt(encrypted); + +// encrypt data with a public key using RSAES PKCS#1 v1.5 +var encrypted = publicKey.encrypt(bytes, 'RSAES-PKCS1-V1_5'); + +// decrypt data with a private key using RSAES PKCS#1 v1.5 +var decrypted = privateKey.decrypt(encrypted, 'RSAES-PKCS1-V1_5'); + +// encrypt data with a public key using RSAES-OAEP +var encrypted = publicKey.encrypt(bytes, 'RSA-OAEP'); + +// decrypt data with a private key using RSAES-OAEP +var decrypted = privateKey.decrypt(encrypted, 'RSA-OAEP'); + +// encrypt data with a public key using RSAES-OAEP/SHA-256 +var encrypted = publicKey.encrypt(bytes, 'RSA-OAEP', { + md: forge.md.sha256.create() +}); + +// decrypt data with a private key using RSAES-OAEP/SHA-256 +var decrypted = privateKey.decrypt(encrypted, 'RSA-OAEP', { + md: forge.md.sha256.create() +}); + +// encrypt data with a public key using RSAES-OAEP/SHA-256/MGF1-SHA-1 +// compatible with Java's RSA/ECB/OAEPWithSHA-256AndMGF1Padding +var encrypted = publicKey.encrypt(bytes, 'RSA-OAEP', { + md: forge.md.sha256.create(), + mgf1: { + md: forge.md.sha1.create() + } +}); + +// decrypt data with a private key using RSAES-OAEP/SHA-256/MGF1-SHA-1 +// compatible with Java's RSA/ECB/OAEPWithSHA-256AndMGF1Padding +var decrypted = privateKey.decrypt(encrypted, 'RSA-OAEP', { + md: forge.md.sha256.create(), + mgf1: { + md: forge.md.sha1.create() + } +}); + +``` + + + +### RSA-KEM + +__Examples__ + +```js +// generate an RSA key pair asynchronously (uses web workers if available) +// use workers: -1 to run a fast core estimator to optimize # of workers +forge.rsa.generateKeyPair({bits: 2048, workers: -1}, function(err, keypair) { + // keypair.privateKey, keypair.publicKey +}); + +// generate and encapsulate a 16-byte secret key +var kdf1 = new forge.kem.kdf1(forge.md.sha1.create()); +var kem = forge.kem.rsa.create(kdf1); +var result = kem.encrypt(keypair.publicKey, 16); +// result has 'encapsulation' and 'key' + +// encrypt some bytes +var iv = forge.random.getBytesSync(12); +var someBytes = 'hello world!'; +var cipher = forge.cipher.createCipher('AES-GCM', result.key); +cipher.start({iv: iv}); +cipher.update(forge.util.createBuffer(someBytes)); +cipher.finish(); +var encrypted = cipher.output.getBytes(); +var tag = cipher.mode.tag.getBytes(); + +// send 'encrypted', 'iv', 'tag', and result.encapsulation to recipient + +// decrypt encapsulated 16-byte secret key +var kdf1 = new forge.kem.kdf1(forge.md.sha1.create()); +var kem = forge.kem.rsa.create(kdf1); +var key = kem.decrypt(keypair.privateKey, result.encapsulation, 16); + +// decrypt some bytes +var decipher = forge.cipher.createDecipher('AES-GCM', key); +decipher.start({iv: iv, tag: tag}); +decipher.update(forge.util.createBuffer(encrypted)); +var pass = decipher.finish(); +// pass is false if there was a failure (eg: authentication tag didn't match) +if(pass) { + // outputs 'hello world!' + console.log(decipher.output.getBytes()); +} + +``` + + + +### X.509 + +__Examples__ + +```js +var pki = forge.pki; + +// convert a PEM-formatted public key to a Forge public key +var publicKey = pki.publicKeyFromPem(pem); + +// convert a Forge public key to PEM-format +var pem = pki.publicKeyToPem(publicKey); + +// convert an ASN.1 SubjectPublicKeyInfo to a Forge public key +var publicKey = pki.publicKeyFromAsn1(subjectPublicKeyInfo); + +// convert a Forge public key to an ASN.1 SubjectPublicKeyInfo +var subjectPublicKeyInfo = pki.publicKeyToAsn1(publicKey); + +// gets a SHA-1 RSAPublicKey fingerprint a byte buffer +pki.getPublicKeyFingerprint(key); + +// gets a SHA-1 SubjectPublicKeyInfo fingerprint a byte buffer +pki.getPublicKeyFingerprint(key, {type: 'SubjectPublicKeyInfo'}); + +// gets a hex-encoded, colon-delimited SHA-1 RSAPublicKey public key fingerprint +pki.getPublicKeyFingerprint(key, {encoding: 'hex', delimiter: ':'}); + +// gets a hex-encoded, colon-delimited SHA-1 SubjectPublicKeyInfo public key fingerprint +pki.getPublicKeyFingerprint(key, { + type: 'SubjectPublicKeyInfo', + encoding: 'hex', + delimiter: ':' +}); + +// gets a hex-encoded, colon-delimited MD5 RSAPublicKey public key fingerprint +pki.getPublicKeyFingerprint(key, { + md: forge.md.md5.create(), + encoding: 'hex', + delimiter: ':' +}); + +// creates a CA store +var caStore = pki.createCaStore([/* PEM-encoded cert */, ...]); + +// add a certificate to the CA store +caStore.addCertificate(certObjectOrPemString); + +// gets the issuer (its certificate) for the given certificate +var issuerCert = caStore.getIssuer(subjectCert); + +// verifies a certificate chain against a CA store +pki.verifyCertificateChain(caStore, chain, customVerifyCallback); + +// signs a certificate using the given private key +cert.sign(privateKey); + +// signs a certificate using SHA-256 instead of SHA-1 +cert.sign(privateKey, forge.md.sha256.create()); + +// verifies an issued certificate using the certificates public key +var verified = issuer.verify(issued); + +// generate a keypair and create an X.509v3 certificate +var keys = pki.rsa.generateKeyPair(2048); +var cert = pki.createCertificate(); +cert.publicKey = keys.publicKey; +// alternatively set public key from a csr +//cert.publicKey = csr.publicKey; +// NOTE: serialNumber is the hex encoded value of an ASN.1 INTEGER. +// Conforming CAs should ensure serialNumber is: +// - no more than 20 octets +// - non-negative (prefix a '00' if your value starts with a '1' bit) +cert.serialNumber = '01'; +cert.validity.notBefore = new Date(); +cert.validity.notAfter = new Date(); +cert.validity.notAfter.setFullYear(cert.validity.notBefore.getFullYear() + 1); +var attrs = [{ + name: 'commonName', + value: 'example.org' +}, { + name: 'countryName', + value: 'US' +}, { + shortName: 'ST', + value: 'Virginia' +}, { + name: 'localityName', + value: 'Blacksburg' +}, { + name: 'organizationName', + value: 'Test' +}, { + shortName: 'OU', + value: 'Test' +}]; +cert.setSubject(attrs); +// alternatively set subject from a csr +//cert.setSubject(csr.subject.attributes); +cert.setIssuer(attrs); +cert.setExtensions([{ + name: 'basicConstraints', + cA: true +}, { + name: 'keyUsage', + keyCertSign: true, + digitalSignature: true, + nonRepudiation: true, + keyEncipherment: true, + dataEncipherment: true +}, { + name: 'extKeyUsage', + serverAuth: true, + clientAuth: true, + codeSigning: true, + emailProtection: true, + timeStamping: true +}, { + name: 'nsCertType', + client: true, + server: true, + email: true, + objsign: true, + sslCA: true, + emailCA: true, + objCA: true +}, { + name: 'subjectAltName', + altNames: [{ + type: 6, // URI + value: 'http://example.org/webid#me' + }, { + type: 7, // IP + ip: '127.0.0.1' + }] +}, { + name: 'subjectKeyIdentifier' +}]); +/* alternatively set extensions from a csr +var extensions = csr.getAttribute({name: 'extensionRequest'}).extensions; +// optionally add more extensions +extensions.push.apply(extensions, [{ + name: 'basicConstraints', + cA: true +}, { + name: 'keyUsage', + keyCertSign: true, + digitalSignature: true, + nonRepudiation: true, + keyEncipherment: true, + dataEncipherment: true +}]); +cert.setExtensions(extensions); +*/ +// self-sign certificate +cert.sign(keys.privateKey); + +// convert a Forge certificate to PEM +var pem = pki.certificateToPem(cert); + +// convert a Forge certificate from PEM +var cert = pki.certificateFromPem(pem); + +// convert an ASN.1 X.509x3 object to a Forge certificate +var cert = pki.certificateFromAsn1(obj); + +// convert a Forge certificate to an ASN.1 X.509v3 object +var asn1Cert = pki.certificateToAsn1(cert); +``` + + + +### PKCS#5 + +Provides the password-based key-derivation function from [PKCS#5][]. + +__Examples__ + +```js +// generate a password-based 16-byte key +// note an optional message digest can be passed as the final parameter +var salt = forge.random.getBytesSync(128); +var derivedKey = forge.pkcs5.pbkdf2('password', salt, numIterations, 16); + +// generate key asynchronously +// note an optional message digest can be passed before the callback +forge.pkcs5.pbkdf2('password', salt, numIterations, 16, function(err, derivedKey) { + // do something w/derivedKey +}); +``` + + + +### PKCS#7 + +Provides cryptographically protected messages from [PKCS#7][]. + +__Examples__ + +```js +// convert a message from PEM +var p7 = forge.pkcs7.messageFromPem(pem); +// look at p7.recipients + +// find a recipient by the issuer of a certificate +var recipient = p7.findRecipient(cert); + +// decrypt +p7.decrypt(p7.recipients[0], privateKey); + +// create a p7 enveloped message +var p7 = forge.pkcs7.createEnvelopedData(); + +// add a recipient +var cert = forge.pki.certificateFromPem(certPem); +p7.addRecipient(cert); + +// set content +p7.content = forge.util.createBuffer('Hello'); + +// encrypt +p7.encrypt(); + +// convert message to PEM +var pem = forge.pkcs7.messageToPem(p7); + +// create a degenerate PKCS#7 certificate container +// (CRLs not currently supported, only certificates) +var p7 = forge.pkcs7.createSignedData(); +p7.addCertificate(certOrCertPem1); +p7.addCertificate(certOrCertPem2); +var pem = forge.pkcs7.messageToPem(p7); + +// create PKCS#7 signed data with authenticatedAttributes +// attributes include: PKCS#9 content-type, message-digest, and signing-time +var p7 = forge.pkcs7.createSignedData(); +p7.content = forge.util.createBuffer('Some content to be signed.', 'utf8'); +p7.addCertificate(certOrCertPem); +p7.addSigner({ + key: privateKeyAssociatedWithCert, + certificate: certOrCertPem, + digestAlgorithm: forge.pki.oids.sha256, + authenticatedAttributes: [{ + type: forge.pki.oids.contentType, + value: forge.pki.oids.data + }, { + type: forge.pki.oids.messageDigest + // value will be auto-populated at signing time + }, { + type: forge.pki.oids.signingTime, + // value can also be auto-populated at signing time + value: new Date() + }] +}); +p7.sign(); +var pem = forge.pkcs7.messageToPem(p7); + +// PKCS#7 Sign in detached mode. +// Includes the signature and certificate without the signed data. +p7.sign({detached: true}); + +``` + + + +### PKCS#8 + +__Examples__ + +```js +var pki = forge.pki; + +// convert a PEM-formatted private key to a Forge private key +var privateKey = pki.privateKeyFromPem(pem); + +// convert a Forge private key to PEM-format +var pem = pki.privateKeyToPem(privateKey); + +// convert an ASN.1 PrivateKeyInfo or RSAPrivateKey to a Forge private key +var privateKey = pki.privateKeyFromAsn1(rsaPrivateKey); + +// convert a Forge private key to an ASN.1 RSAPrivateKey +var rsaPrivateKey = pki.privateKeyToAsn1(privateKey); + +// wrap an RSAPrivateKey ASN.1 object in a PKCS#8 ASN.1 PrivateKeyInfo +var privateKeyInfo = pki.wrapRsaPrivateKey(rsaPrivateKey); + +// convert a PKCS#8 ASN.1 PrivateKeyInfo to PEM +var pem = pki.privateKeyInfoToPem(privateKeyInfo); + +// encrypts a PrivateKeyInfo using a custom password and +// outputs an EncryptedPrivateKeyInfo +var encryptedPrivateKeyInfo = pki.encryptPrivateKeyInfo( + privateKeyInfo, 'myCustomPasswordHere', { + algorithm: 'aes256', // 'aes128', 'aes192', 'aes256', '3des' + }); + +// decrypts an ASN.1 EncryptedPrivateKeyInfo that was encrypted +// with a custom password +var privateKeyInfo = pki.decryptPrivateKeyInfo( + encryptedPrivateKeyInfo, 'myCustomPasswordHere'); + +// converts an EncryptedPrivateKeyInfo to PEM +var pem = pki.encryptedPrivateKeyToPem(encryptedPrivateKeyInfo); + +// converts a PEM-encoded EncryptedPrivateKeyInfo to ASN.1 format +var encryptedPrivateKeyInfo = pki.encryptedPrivateKeyFromPem(pem); + +// wraps and encrypts a Forge private key and outputs it in PEM format +var pem = pki.encryptRsaPrivateKey(privateKey, 'password'); + +// encrypts a Forge private key and outputs it in PEM format using OpenSSL's +// proprietary legacy format + encapsulated PEM headers (DEK-Info) +var pem = pki.encryptRsaPrivateKey(privateKey, 'password', {legacy: true}); + +// decrypts a PEM-formatted, encrypted private key +var privateKey = pki.decryptRsaPrivateKey(pem, 'password'); + +// sets an RSA public key from a private key +var publicKey = pki.setRsaPublicKey(privateKey.n, privateKey.e); +``` + + + +### PKCS#10 + +Provides certification requests or certificate signing requests (CSR) from +[PKCS#10][]. + +__Examples__ + +```js +// generate a key pair +var keys = forge.pki.rsa.generateKeyPair(1024); + +// create a certification request (CSR) +var csr = forge.pki.createCertificationRequest(); +csr.publicKey = keys.publicKey; +csr.setSubject([{ + name: 'commonName', + value: 'example.org' +}, { + name: 'countryName', + value: 'US' +}, { + shortName: 'ST', + value: 'Virginia' +}, { + name: 'localityName', + value: 'Blacksburg' +}, { + name: 'organizationName', + value: 'Test' +}, { + shortName: 'OU', + value: 'Test' +}]); +// set (optional) attributes +csr.setAttributes([{ + name: 'challengePassword', + value: 'password' +}, { + name: 'unstructuredName', + value: 'My Company, Inc.' +}, { + name: 'extensionRequest', + extensions: [{ + name: 'subjectAltName', + altNames: [{ + // 2 is DNS type + type: 2, + value: 'test.domain.com' + }, { + type: 2, + value: 'other.domain.com', + }, { + type: 2, + value: 'www.domain.net' + }] + }] +}]); + +// sign certification request +csr.sign(keys.privateKey); + +// verify certification request +var verified = csr.verify(); + +// convert certification request to PEM-format +var pem = forge.pki.certificationRequestToPem(csr); + +// convert a Forge certification request from PEM-format +var csr = forge.pki.certificationRequestFromPem(pem); + +// get an attribute +csr.getAttribute({name: 'challengePassword'}); + +// get extensions array +csr.getAttribute({name: 'extensionRequest'}).extensions; + +``` + + + +### PKCS#12 + +Provides the cryptographic archive file format from [PKCS#12][]. + +**Note for Chrome/Firefox/iOS/similar users**: If you have trouble importing +a PKCS#12 container, try using the TripleDES algorithm. It can be passed +to `forge.pkcs12.toPkcs12Asn1` using the `{algorithm: '3des'}` option. + +__Examples__ + +```js +// decode p12 from base64 +var p12Der = forge.util.decode64(p12b64); +// get p12 as ASN.1 object +var p12Asn1 = forge.asn1.fromDer(p12Der); +// decrypt p12 using the password 'password' +var p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1, 'password'); +// decrypt p12 using non-strict parsing mode (resolves some ASN.1 parse errors) +var p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1, false, 'password'); +// decrypt p12 using literally no password (eg: Mac OS X/apple push) +var p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1); +// decrypt p12 using an "empty" password (eg: OpenSSL with no password input) +var p12 = forge.pkcs12.pkcs12FromAsn1(p12Asn1, ''); +// p12.safeContents is an array of safe contents, each of +// which contains an array of safeBags + +// get bags by friendlyName +var bags = p12.getBags({friendlyName: 'test'}); +// bags are key'd by attribute type (here "friendlyName") +// and the key values are an array of matching objects +var cert = bags.friendlyName[0]; + +// get bags by localKeyId +var bags = p12.getBags({localKeyId: buffer}); +// bags are key'd by attribute type (here "localKeyId") +// and the key values are an array of matching objects +var cert = bags.localKeyId[0]; + +// get bags by localKeyId (input in hex) +var bags = p12.getBags({localKeyIdHex: '7b59377ff142d0be4565e9ac3d396c01401cd879'}); +// bags are key'd by attribute type (here "localKeyId", *not* "localKeyIdHex") +// and the key values are an array of matching objects +var cert = bags.localKeyId[0]; + +// get bags by type +var bags = p12.getBags({bagType: forge.pki.oids.certBag}); +// bags are key'd by bagType and each bagType key's value +// is an array of matches (in this case, certificate objects) +var cert = bags[forge.pki.oids.certBag][0]; + +// get bags by friendlyName and filter on bag type +var bags = p12.getBags({ + friendlyName: 'test', + bagType: forge.pki.oids.certBag +}); + +// get key bags +var bags = p12.getBags({bagType: forge.pki.oids.keyBag}); +// get key +var bag = bags[forge.pki.oids.keyBag][0]; +var key = bag.key; +// if the key is in a format unrecognized by forge then +// bag.key will be `null`, use bag.asn1 to get the ASN.1 +// representation of the key +if(bag.key === null) { + var keyAsn1 = bag.asn1; + // can now convert back to DER/PEM/etc for export +} + +// generate a p12 using AES (default) +var p12Asn1 = forge.pkcs12.toPkcs12Asn1( + privateKey, certificateChain, 'password'); + +// generate a p12 that can be imported by Chrome/Firefox/iOS +// (requires the use of Triple DES instead of AES) +var p12Asn1 = forge.pkcs12.toPkcs12Asn1( + privateKey, certificateChain, 'password', + {algorithm: '3des'}); + +// base64-encode p12 +var p12Der = forge.asn1.toDer(p12Asn1).getBytes(); +var p12b64 = forge.util.encode64(p12Der); + +// create download link for p12 +var a = document.createElement('a'); +a.download = 'example.p12'; +a.setAttribute('href', 'data:application/x-pkcs12;base64,' + p12b64); +a.appendChild(document.createTextNode('Download')); +``` + + + +### ASN.1 + +Provides [ASN.1][] DER encoding and decoding. + +__Examples__ + +```js +var asn1 = forge.asn1; + +// create a SubjectPublicKeyInfo +var subjectPublicKeyInfo = + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // AlgorithmIdentifier + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(pki.oids['rsaEncryption']).getBytes()), + // parameters (null) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ]), + // subjectPublicKey + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, [ + // RSAPublicKey + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // modulus (n) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + _bnToBytes(key.n)), + // publicExponent (e) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + _bnToBytes(key.e)) + ]) + ]) + ]); + +// serialize an ASN.1 object to DER format +var derBuffer = asn1.toDer(subjectPublicKeyInfo); + +// deserialize to an ASN.1 object from a byte buffer filled with DER data +var object = asn1.fromDer(derBuffer); + +// convert an OID dot-separated string to a byte buffer +var derOidBuffer = asn1.oidToDer('1.2.840.113549.1.1.5'); + +// convert a byte buffer with a DER-encoded OID to a dot-separated string +console.log(asn1.derToOid(derOidBuffer)); +// output: 1.2.840.113549.1.1.5 + +// validates that an ASN.1 object matches a particular ASN.1 structure and +// captures data of interest from that structure for easy access +var publicKeyValidator = { + name: 'SubjectPublicKeyInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'subjectPublicKeyInfo', + value: [{ + name: 'SubjectPublicKeyInfo.AlgorithmIdentifier', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'AlgorithmIdentifier.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'publicKeyOid' + }] + }, { + // subjectPublicKey + name: 'SubjectPublicKeyInfo.subjectPublicKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + value: [{ + // RSAPublicKey + name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + optional: true, + captureAsn1: 'rsaPublicKey' + }] + }] +}; + +var capture = {}; +var errors = []; +if(!asn1.validate( + publicKeyValidator, subjectPublicKeyInfo, validator, capture, errors)) { + throw 'ASN.1 object is not a SubjectPublicKeyInfo.'; +} +// capture.subjectPublicKeyInfo contains the full ASN.1 object +// capture.rsaPublicKey contains the full ASN.1 object for the RSA public key +// capture.publicKeyOid only contains the value for the OID +var oid = asn1.derToOid(capture.publicKeyOid); +if(oid !== pki.oids['rsaEncryption']) { + throw 'Unsupported OID.'; +} + +// pretty print an ASN.1 object to a string for debugging purposes +asn1.prettyPrint(object); +``` + +Message Digests +---------------- + + + +### SHA1 + +Provides [SHA-1][] message digests. + +__Examples__ + +```js +var md = forge.md.sha1.create(); +md.update('The quick brown fox jumps over the lazy dog'); +console.log(md.digest().toHex()); +// output: 2fd4e1c67a2d28fced849ee1bb76e7391b93eb12 +``` + + + +### SHA256 + +Provides [SHA-256][] message digests. + +__Examples__ + +```js +var md = forge.md.sha256.create(); +md.update('The quick brown fox jumps over the lazy dog'); +console.log(md.digest().toHex()); +// output: d7a8fbb307d7809469ca9abcb0082e4f8d5651e46d3cdb762d02d0bf37c9e592 +``` + + + +### SHA384 + +Provides [SHA-384][] message digests. + +__Examples__ + +```js +var md = forge.md.sha384.create(); +md.update('The quick brown fox jumps over the lazy dog'); +console.log(md.digest().toHex()); +// output: ca737f1014a48f4c0b6dd43cb177b0afd9e5169367544c494011e3317dbf9a509cb1e5dc1e85a941bbee3d7f2afbc9b1 +``` + + + +### SHA512 + +Provides [SHA-512][] message digests. + +__Examples__ + +```js +// SHA-512 +var md = forge.md.sha512.create(); +md.update('The quick brown fox jumps over the lazy dog'); +console.log(md.digest().toHex()); +// output: 07e547d9586f6a73f73fbac0435ed76951218fb7d0c8d788a309d785436bbb642e93a252a954f23912547d1e8a3b5ed6e1bfd7097821233fa0538f3db854fee6 + +// SHA-512/224 +var md = forge.md.sha512.sha224.create(); +md.update('The quick brown fox jumps over the lazy dog'); +console.log(md.digest().toHex()); +// output: 944cd2847fb54558d4775db0485a50003111c8e5daa63fe722c6aa37 + +// SHA-512/256 +var md = forge.md.sha512.sha256.create(); +md.update('The quick brown fox jumps over the lazy dog'); +console.log(md.digest().toHex()); +// output: dd9d67b371519c339ed8dbd25af90e976a1eeefd4ad3d889005e532fc5bef04d +``` + + + +### MD5 + +Provides [MD5][] message digests. + +__Examples__ + +```js +var md = forge.md.md5.create(); +md.update('The quick brown fox jumps over the lazy dog'); +console.log(md.digest().toHex()); +// output: 9e107d9d372bb6826bd81d3542a419d6 +``` + + + +### HMAC + +Provides [HMAC][] w/any supported message digest algorithm. + +__Examples__ + +```js +var hmac = forge.hmac.create(); +hmac.start('sha1', 'Jefe'); +hmac.update('what do ya want for nothing?'); +console.log(hmac.digest().toHex()); +// output: effcdf6ae5eb2fa2d27416d5f184df9c259a7c79 +``` + +Utilities +--------- + + + +### Prime + +Provides an API for generating large, random, probable primes. + +__Examples__ + +```js +// generate a random prime on the main JS thread +var bits = 1024; +forge.prime.generateProbablePrime(bits, function(err, num) { + console.log('random prime', num.toString(16)); +}); + +// generate a random prime using Web Workers (if available, otherwise +// falls back to the main thread) +var bits = 1024; +var options = { + algorithm: { + name: 'PRIMEINC', + workers: -1 // auto-optimize # of workers + } +}; +forge.prime.generateProbablePrime(bits, options, function(err, num) { + console.log('random prime', num.toString(16)); +}); +``` + + + +### PRNG + +Provides a [Fortuna][]-based cryptographically-secure pseudo-random number +generator, to be used with a cryptographic function backend, e.g. [AES][]. An +implementation using [AES][] as a backend is provided. An API for collecting +entropy is given, though if window.crypto.getRandomValues is available, it will +be used automatically. + +__Examples__ + +```js +// get some random bytes synchronously +var bytes = forge.random.getBytesSync(32); +console.log(forge.util.bytesToHex(bytes)); + +// get some random bytes asynchronously +forge.random.getBytes(32, function(err, bytes) { + console.log(forge.util.bytesToHex(bytes)); +}); + +// collect some entropy if you'd like +forge.random.collect(someRandomBytes); +jQuery().mousemove(function(e) { + forge.random.collectInt(e.clientX, 16); + forge.random.collectInt(e.clientY, 16); +}); + +// specify a seed file for use with the synchronous API if you'd like +forge.random.seedFileSync = function(needed) { + // get 'needed' number of random bytes from somewhere + return fetchedRandomBytes; +}; + +// specify a seed file for use with the asynchronous API if you'd like +forge.random.seedFile = function(needed, callback) { + // get the 'needed' number of random bytes from somewhere + callback(null, fetchedRandomBytes); +}); + +// register the main thread to send entropy or a Web Worker to receive +// entropy on demand from the main thread +forge.random.registerWorker(self); + +// generate a new instance of a PRNG with no collected entropy +var myPrng = forge.random.createInstance(); +``` + + + +### Tasks + +Provides queuing and synchronizing tasks in a web application. + +__Examples__ + +```js +// TODO +``` + + + +### Utilities + +Provides utility functions, including byte buffer support, base64, +bytes to/from hex, zlib inflate/deflate, etc. + +__Examples__ + +```js +// encode/decode base64 +var encoded = forge.util.encode64(str); +var str = forge.util.decode64(encoded); + +// encode/decode UTF-8 +var encoded = forge.util.encodeUtf8(str); +var str = forge.util.decodeUtf8(encoded); + +// bytes to/from hex +var bytes = forge.util.hexToBytes(hex); +var hex = forge.util.bytesToHex(bytes); + +// create an empty byte buffer +var buffer = forge.util.createBuffer(); +// create a byte buffer from raw binary bytes +var buffer = forge.util.createBuffer(input, 'raw'); +// create a byte buffer from utf8 bytes +var buffer = forge.util.createBuffer(input, 'utf8'); + +// get the length of the buffer in bytes +buffer.length(); +// put bytes into the buffer +buffer.putBytes(bytes); +// put a 32-bit integer into the buffer +buffer.putInt32(10); +// buffer to hex +buffer.toHex(); +// get a copy of the bytes in the buffer +bytes.bytes(/* count */); +// empty this buffer and get its contents +bytes.getBytes(/* count */); + +// convert a forge buffer into a Node.js Buffer +// make sure you specify the encoding as 'binary' +var forgeBuffer = forge.util.createBuffer(); +var nodeBuffer = Buffer.from(forgeBuffer.getBytes(), 'binary'); + +// convert a Node.js Buffer into a forge buffer +// make sure you specify the encoding as 'binary' +var nodeBuffer = Buffer.from('CAFE', 'hex'); +var forgeBuffer = forge.util.createBuffer(nodeBuffer.toString('binary')); + +// parse a URL +var parsed = forge.util.parseUrl('http://example.com/foo?bar=baz'); +// parsed.scheme, parsed.host, parsed.port, parsed.path, parsed.fullHost +``` + + + +### Logging + +Provides logging to a javascript console using various categories and +levels of verbosity. + +__Examples__ + +```js +// TODO +``` + + + +### Debugging + +Provides storage of debugging information normally inaccessible in +closures for viewing/investigation. + +__Examples__ + +```js +// TODO +``` + + + +### Flash Networking Support + +The [flash README](./flash/README.md) provides details on rebuilding the +optional Flash component used for networking. It also provides details on +Policy Server support. + +Security Considerations +----------------------- + +When using this code please keep the following in mind: + +- Cryptography is hard. Please review and test this code before depending on it + for critical functionality. +- The nature of JavaScript is that execution of this code depends on trusting a + very large set of JavaScript tools and systems. Consider runtime variations, + runtime characteristics, runtime optimization, code optimization, code + minimization, code obfuscation, bundling tools, possible bugs, the Forge code + itself, and so on. +- If using pre-built bundles from [Bower][] or similar be aware someone else + ran the tools to create those files. +- Use a secure transport channel such as [TLS][] to load scripts and consider + using additional security mechanisms such as [Subresource Integrity][] script + attributes. +- Use "native" functionality where possible. This can be critical when dealing + with performance and random number generation. Note that the JavaScript + random number algorithms should perform well if given suitable entropy. +- Understand possible attacks against cryptographic systems. For instance side + channel and timing attacks may be possible due to the difficulty in + implementing constant time algorithms in pure JavaScript. +- Certain features in this library are less susceptible to attacks depending on + usage. This primarily includes features that deal with data format + manipulation or those that are not involved in communication. + +Library Background +------------------ + +* https://digitalbazaar.com/2010/07/20/javascript-tls-1/ +* https://digitalbazaar.com/2010/07/20/javascript-tls-2/ + +Contact +------- + +* Code: https://github.com/digitalbazaar/forge +* Bugs: https://github.com/digitalbazaar/forge/issues +* Email: support@digitalbazaar.com +* IRC: [#forgejs][] on [freenode][] + +Donations +--------- + +Financial support is welcome and helps contribute to futher development: + +* For [PayPal][] please send to paypal@digitalbazaar.com. +* Something else? Please contact support@digitalbazaar.com. + +[#forgejs]: https://webchat.freenode.net/?channels=#forgejs +[0.6.x]: https://github.com/digitalbazaar/forge/tree/0.6.x +[3DES]: https://en.wikipedia.org/wiki/Triple_DES +[AES]: https://en.wikipedia.org/wiki/Advanced_Encryption_Standard +[ASN.1]: https://en.wikipedia.org/wiki/ASN.1 +[Bower]: https://bower.io/ +[Browserify]: http://browserify.org/ +[CBC]: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation +[CFB]: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation +[CTR]: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation +[CommonJS]: https://en.wikipedia.org/wiki/CommonJS +[DES]: https://en.wikipedia.org/wiki/Data_Encryption_Standard +[ECB]: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation +[Fortuna]: https://en.wikipedia.org/wiki/Fortuna_(PRNG) +[GCM]: https://en.wikipedia.org/wiki/GCM_mode +[HMAC]: https://en.wikipedia.org/wiki/HMAC +[JavaScript]: https://en.wikipedia.org/wiki/JavaScript +[Karma]: https://karma-runner.github.io/ +[MD5]: https://en.wikipedia.org/wiki/MD5 +[Node.js]: https://nodejs.org/ +[OFB]: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation +[PKCS#10]: https://en.wikipedia.org/wiki/Certificate_signing_request +[PKCS#12]: https://en.wikipedia.org/wiki/PKCS_%E2%99%AF12 +[PKCS#5]: https://en.wikipedia.org/wiki/PKCS +[PKCS#7]: https://en.wikipedia.org/wiki/Cryptographic_Message_Syntax +[PayPal]: https://www.paypal.com/ +[RC2]: https://en.wikipedia.org/wiki/RC2 +[SHA-1]: https://en.wikipedia.org/wiki/SHA-1 +[SHA-256]: https://en.wikipedia.org/wiki/SHA-256 +[SHA-384]: https://en.wikipedia.org/wiki/SHA-384 +[SHA-512]: https://en.wikipedia.org/wiki/SHA-512 +[Subresource Integrity]: https://www.w3.org/TR/SRI/ +[TLS]: https://en.wikipedia.org/wiki/Transport_Layer_Security +[UMD]: https://github.com/umdjs/umd +[X.509]: https://en.wikipedia.org/wiki/X.509 +[freenode]: https://freenode.net/ +[unpkg]: https://unpkg.com/ +[webpack]: https://webpack.github.io/ +[TweetNaCl.js]: https://github.com/dchest/tweetnacl-js diff --git a/node_modules/node-forge/dist/forge.all.min.js b/node_modules/node-forge/dist/forge.all.min.js new file mode 100644 index 0000000..b84957e --- /dev/null +++ b/node_modules/node-forge/dist/forge.all.min.js @@ -0,0 +1,2 @@ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.forge=t():e.forge=t()}("undefined"!=typeof self?self:this,function(){return function(e){function t(n){if(r[n])return r[n].exports;var a=r[n]={i:n,l:!1,exports:{}};return e[n].call(a.exports,a,a.exports,t),a.l=!0,a.exports}var r={};return t.m=e,t.c=r,t.d=function(e,r,n){t.o(e,r)||Object.defineProperty(e,r,{configurable:!1,enumerable:!0,get:n})},t.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(r,"a",r),r},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=36)}([function(e,t){e.exports={options:{usePureJavaScript:!1}}},function(e,t,r){(function(t){function n(e){if(8!==e&&16!==e&&24!==e&&32!==e)throw new Error("Only 8, 16, 24, or 32 bits supported: "+e)}function a(e){if(this.data="",this.read=0,"string"==typeof e)this.data=e;else if(c.isArrayBuffer(e)||c.isArrayBufferView(e))if("undefined"!=typeof Buffer&&e instanceof Buffer)this.data=e.toString("binary");else{var t=new Uint8Array(e);try{this.data=String.fromCharCode.apply(null,t)}catch(e){for(var r=0;r15?(n=Date.now(),s(e)):(r.push(e),1===r.length&&i.setAttribute("a",a=!a))}}c.nextTick=c.setImmediate}(),c.isNodejs="undefined"!=typeof process&&process.versions&&process.versions.node,c.globalScope=function(){return c.isNodejs?t:"undefined"==typeof self?window:self}(),c.isArray=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},c.isArrayBuffer=function(e){return"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer},c.isArrayBufferView=function(e){return e&&c.isArrayBuffer(e.buffer)&&void 0!==e.byteLength},c.ByteBuffer=a,c.ByteStringBuffer=a;c.ByteStringBuffer.prototype._optimizeConstructedString=function(e){this._constructedStringLength+=e,this._constructedStringLength>4096&&(this.data.substr(0,1),this._constructedStringLength=0)},c.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read},c.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0},c.ByteStringBuffer.prototype.putByte=function(e){return this.putBytes(String.fromCharCode(e))},c.ByteStringBuffer.prototype.fillWithByte=function(e,t){e=String.fromCharCode(e);for(var r=this.data;t>0;)1&t&&(r+=e),(t>>>=1)>0&&(e+=e);return this.data=r,this._optimizeConstructedString(t),this},c.ByteStringBuffer.prototype.putBytes=function(e){return this.data+=e,this._optimizeConstructedString(e.length),this},c.ByteStringBuffer.prototype.putString=function(e){return this.putBytes(c.encodeUtf8(e))},c.ByteStringBuffer.prototype.putInt16=function(e){return this.putBytes(String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},c.ByteStringBuffer.prototype.putInt24=function(e){return this.putBytes(String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},c.ByteStringBuffer.prototype.putInt32=function(e){return this.putBytes(String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},c.ByteStringBuffer.prototype.putInt16Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255))},c.ByteStringBuffer.prototype.putInt24Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255))},c.ByteStringBuffer.prototype.putInt32Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>24&255))},c.ByteStringBuffer.prototype.putInt=function(e,t){n(t);var r="";do{t-=8,r+=String.fromCharCode(e>>t&255)}while(t>0);return this.putBytes(r)},c.ByteStringBuffer.prototype.putSignedInt=function(e,t){return e<0&&(e+=2<0);return t},c.ByteStringBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<=r&&(t-=r<<1),t},c.ByteStringBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):0===e?t="":(t=0===this.read?this.data:this.data.slice(this.read),this.clear()),t},c.ByteStringBuffer.prototype.bytes=function(e){return void 0===e?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},c.ByteStringBuffer.prototype.at=function(e){return this.data.charCodeAt(this.read+e)},c.ByteStringBuffer.prototype.setAt=function(e,t){return this.data=this.data.substr(0,this.read+e)+String.fromCharCode(t)+this.data.substr(this.read+e+1),this},c.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)},c.ByteStringBuffer.prototype.copy=function(){var e=c.createBuffer(this.data);return e.read=this.read,e},c.ByteStringBuffer.prototype.compact=function(){return this.read>0&&(this.data=this.data.slice(this.read),this.read=0),this},c.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this},c.ByteStringBuffer.prototype.truncate=function(e){var t=Math.max(0,this.length()-e);return this.data=this.data.substr(this.read,t),this.read=0,this},c.ByteStringBuffer.prototype.toHex=function(){for(var e="",t=this.read;t=e)return this;t=Math.max(t||this.growSize,e);var r=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),n=new Uint8Array(this.length()+t);return n.set(r),this.data=new DataView(n.buffer),this},c.DataBuffer.prototype.putByte=function(e){return this.accommodate(1),this.data.setUint8(this.write++,e),this},c.DataBuffer.prototype.fillWithByte=function(e,t){this.accommodate(t);for(var r=0;r>8&65535),this.data.setInt8(this.write,e>>16&255),this.write+=3,this},c.DataBuffer.prototype.putInt32=function(e){return this.accommodate(4),this.data.setInt32(this.write,e),this.write+=4,this},c.DataBuffer.prototype.putInt16Le=function(e){return this.accommodate(2),this.data.setInt16(this.write,e,!0),this.write+=2,this},c.DataBuffer.prototype.putInt24Le=function(e){return this.accommodate(3),this.data.setInt8(this.write,e>>16&255),this.data.setInt16(this.write,e>>8&65535,!0),this.write+=3,this},c.DataBuffer.prototype.putInt32Le=function(e){return this.accommodate(4),this.data.setInt32(this.write,e,!0),this.write+=4,this},c.DataBuffer.prototype.putInt=function(e,t){n(t),this.accommodate(t/8);do{t-=8,this.data.setInt8(this.write++,e>>t&255)}while(t>0);return this},c.DataBuffer.prototype.putSignedInt=function(e,t){return n(t),this.accommodate(t/8),e<0&&(e+=2<0);return t},c.DataBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<=r&&(t-=r<<1),t},c.DataBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):0===e?t="":(t=0===this.read?this.data:this.data.slice(this.read),this.clear()),t},c.DataBuffer.prototype.bytes=function(e){return void 0===e?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},c.DataBuffer.prototype.at=function(e){return this.data.getUint8(this.read+e)},c.DataBuffer.prototype.setAt=function(e,t){return this.data.setUint8(e,t),this},c.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)},c.DataBuffer.prototype.copy=function(){return new c.DataBuffer(this)},c.DataBuffer.prototype.compact=function(){if(this.read>0){var e=new Uint8Array(this.data.buffer,this.read),t=new Uint8Array(e.byteLength);t.set(e),this.data=new DataView(t),this.write-=this.read,this.read=0}return this},c.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this},c.DataBuffer.prototype.truncate=function(e){return this.write=Math.max(0,this.length()-e),this.read=Math.min(this.read,this.write),this},c.DataBuffer.prototype.toHex=function(){for(var e="",t=this.read;t0;)1&t&&(r+=e),(t>>>=1)>0&&(e+=e);return r},c.xorBytes=function(e,t,r){for(var n="",a="",i="",s=0,o=0;r>0;--r,++s)a=e.charCodeAt(s)^t.charCodeAt(s),o>=10&&(n+=i,i="",o=0),i+=String.fromCharCode(a),++o;return n+=i},c.hexToBytes=function(e){var t="",r=0;for(!0&e.length&&(r=1,t+=String.fromCharCode(parseInt(e[0],16)));r>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e)};var u="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",l=[62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],p="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";c.encode64=function(e,t){for(var r,n,a,i="",s="",o=0;o>2),i+=u.charAt((3&r)<<4|n>>4),isNaN(n)?i+="==":(i+=u.charAt((15&n)<<2|a>>6),i+=isNaN(a)?"=":u.charAt(63&a)),t&&i.length>t&&(s+=i.substr(0,t)+"\r\n",i=i.substr(t));return s+=i},c.decode64=function(e){e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var t,r,n,a,i="",s=0;s>4),64!==n&&(i+=String.fromCharCode((15&r)<<4|n>>2),64!==a&&(i+=String.fromCharCode((3&n)<<6|a)));return i},c.encodeUtf8=function(e){return unescape(encodeURIComponent(e))},c.decodeUtf8=function(e){return decodeURIComponent(escape(e))},c.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:o.encode,decode:o.decode}},c.binary.raw.encode=function(e){return String.fromCharCode.apply(null,e)},c.binary.raw.decode=function(e,t,r){var n=t;n||(n=new Uint8Array(e.length)),r=r||0;for(var a=r,i=0;i>2),i+=u.charAt((3&r)<<4|n>>4),isNaN(n)?i+="==":(i+=u.charAt((15&n)<<2|a>>6),i+=isNaN(a)?"=":u.charAt(63&a)),t&&i.length>t&&(s+=i.substr(0,t)+"\r\n",i=i.substr(t));return s+=i},c.binary.base64.decode=function(e,t,r){var n=t;n||(n=new Uint8Array(3*Math.ceil(e.length/4))),e=e.replace(/[^A-Za-z0-9\+\/\=]/g,""),r=r||0;for(var a,i,s,o,c=0,u=r;c>4,64!==s&&(n[u++]=(15&i)<<4|s>>2,64!==o&&(n[u++]=(3&s)<<6|o));return t?u-r:n.subarray(0,u)},c.binary.base58.encode=function(e,t){return c.binary.baseN.encode(e,p,t)},c.binary.base58.decode=function(e,t){return c.binary.baseN.decode(e,p,t)},c.text={utf8:{},utf16:{}},c.text.utf8.encode=function(e,t,r){e=c.encodeUtf8(e);var n=t;n||(n=new Uint8Array(e.length)),r=r||0;for(var a=r,i=0;i0?(a=r[n].substring(0,s),i=r[n].substring(s+1)):(a=r[n],i=null),a in t||(t[a]=[]),a in Object.prototype||null===i||t[a].push(unescape(i))}return t};return void 0===e?(null===C&&(C="undefined"!=typeof window&&window.location&&window.location.search?r(window.location.search.substring(1)):{}),t=C):t=r(e),t},c.parseFragment=function(e){var t=e,r="",n=e.indexOf("?");n>0&&(t=e.substring(0,n),r=e.substring(n+1));var a=t.split("/");return a.length>0&&""===a[0]&&a.shift(),{pathString:t,queryString:r,path:a,query:""===r?{}:c.getQueryVariables(r)}},c.makeRequest=function(e){var t=c.parseFragment(e),r={path:t.pathString,query:t.queryString,getPath:function(e){return void 0===e?t.path:t.path[e]},getQuery:function(e,r){var n;return void 0===e?n=t.query:(n=t.query[e])&&void 0!==r&&(n=n[r]),n},getQueryLast:function(e,t){var n=r.getQuery(e);return n?n[n.length-1]:t}};return r},c.makeLink=function(e,t,r){e=jQuery.isArray(e)?e.join("/"):e;var n=jQuery.param(t||{});return r=r||"",e+(n.length>0?"?"+n:"")+(r.length>0?"#"+r:"")},c.setPath=function(e,t,r){if("object"==typeof e&&null!==e)for(var n=0,a=t.length;n0&&i.push(r),s=n.lastIndex;var o=t[0][1];switch(o){case"s":case"o":a");break;case"%":i.push("%");break;default:i.push("<%"+o+"?>")}}return i.push(e.substring(s)),i.join("")},c.formatNumber=function(e,t,r,n){var a=e,i=isNaN(t=Math.abs(t))?2:t,s=void 0===r?",":r,o=void 0===n?".":n,c=a<0?"-":"",u=parseInt(a=Math.abs(+a||0).toFixed(i),10)+"",l=u.length>3?u.length%3:0;return c+(l?u.substr(0,l)+o:"")+u.substr(l).replace(/(\d{3})(?=\d)/g,"$1"+o)+(i?s+Math.abs(a-u).toFixed(i).slice(2):"")},c.formatSize=function(e){return e=e>=1073741824?c.formatNumber(e/1073741824,2,".","")+" GiB":e>=1048576?c.formatNumber(e/1048576,2,".","")+" MiB":e>=1024?c.formatNumber(e/1024,0)+" KiB":c.formatNumber(e,0)+" bytes"},c.bytesFromIP=function(e){return-1!==e.indexOf(".")?c.bytesFromIPv4(e):-1!==e.indexOf(":")?c.bytesFromIPv6(e):null},c.bytesFromIPv4=function(e){if(e=e.split("."),4!==e.length)return null;for(var t=c.createBuffer(),r=0;rr[n].end-r[n].start&&(n=r.length-1)):r.push({start:o,end:o})}t.push(i)}if(r.length>0){var u=r[n];u.end-u.start>0&&(t.splice(u.start,u.end-u.start+1,""),0===u.start&&t.unshift(""),7===u.end&&t.push(""))}return t.join(":")},c.estimateCores=function(e,t){function r(e,s,o){if(0===s){var u=Math.floor(e.reduce(function(e,t){return e+t},0)/e.length);return c.cores=Math.max(1,u),URL.revokeObjectURL(i),t(null,c.cores)}n(o,function(t,n){e.push(a(o,n)),r(e,s-1,o)})}function n(e,t){for(var r=[],n=[],a=0;ao.st&&a.sta.st&&o.st0)return c.cores=navigator.hardwareConcurrency,t(null,c.cores);if("undefined"==typeof Worker)return c.cores=1,t(null,c.cores);if("undefined"==typeof Blob)return c.cores=2,t(null,c.cores);var i=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",function(e){for(var t=Date.now(),r=t+4;Date.now()t){var n=new Error("Too few bytes to parse DER.");throw n.available=e.length(),n.remaining=t,n.requested=r,n}}function a(e,t,r,i){var c;n(e,t,2);var u=e.getByte();t--;var l=192&u,p=31&u;c=e.length();var f=o(e,t);if(t-=c-e.length(),void 0!==f&&f>t){if(i.strict){var h=new Error("Too few bytes to read ASN.1 value.");throw h.available=e.length(),h.remaining=t,h.requested=f,h}f=t}var d,y,g=32==(32&u);if(g)if(d=[],void 0===f)for(;;){if(n(e,t,2),e.bytes(2)===String.fromCharCode(0,0)){e.getBytes(2),t-=2;break}c=e.length(),d.push(a(e,t,r+1,i)),t-=c-e.length()}else for(;f>0;)c=e.length(),d.push(a(e,f,r+1,i)),t-=c-e.length(),f-=c-e.length();if(void 0===d&&l===s.Class.UNIVERSAL&&p===s.Type.BITSTRING&&(y=e.bytes(f)),void 0===d&&i.decodeBitStrings&&l===s.Class.UNIVERSAL&&p===s.Type.BITSTRING&&f>1){var v=e.read,m=t,C=0;if(p===s.Type.BITSTRING&&(n(e,t,1),C=e.getByte(),t--),0===C)try{c=e.length();var E={verbose:i.verbose,strict:!0,decodeBitStrings:!0},S=a(e,t,r+1,E),T=c-e.length();t-=T,p==s.Type.BITSTRING&&T++;var b=S.tagClass;T!==f||b!==s.Class.UNIVERSAL&&b!==s.Class.CONTEXT_SPECIFIC||(d=[S])}catch(e){}void 0===d&&(e.read=v,t=m)}if(void 0===d){if(void 0===f){if(i.strict)throw new Error("Non-constructed ASN.1 object of indefinite length.");f=t}if(p===s.Type.BMPSTRING)for(d="";f>0;f-=2)n(e,t,2),d+=String.fromCharCode(e.getInt16()),t-=2;else d=e.getBytes(f)}var I=void 0===y?null:{bitStringContents:y};return s.create(l,p,g,d,I)}var i=r(0);r(1),r(6);var s=e.exports=i.asn1=i.asn1||{};s.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192},s.Type={NONE:0,BOOLEAN:1,INTEGER:2,BITSTRING:3,OCTETSTRING:4,NULL:5,OID:6,ODESC:7,EXTERNAL:8,REAL:9,ENUMERATED:10,EMBEDDED:11,UTF8:12,ROID:13,SEQUENCE:16,SET:17,PRINTABLESTRING:19,IA5STRING:22,UTCTIME:23,GENERALIZEDTIME:24,BMPSTRING:30},s.create=function(e,t,r,n,a){if(i.util.isArray(n)){for(var o=[],c=0;c1&&(0===e.value.charCodeAt(0)&&0==(128&e.value.charCodeAt(1))||255===e.value.charCodeAt(0)&&128==(128&e.value.charCodeAt(1)))?n.putBytes(e.value.substr(1)):n.putBytes(e.value);if(t.putByte(r),n.length()<=127)t.putByte(127&n.length());else{var c=n.length(),u="";do{u+=String.fromCharCode(255&c),c>>>=8}while(c>0);t.putByte(128|u.length);for(var o=u.length-1;o>=0;--o)t.putByte(u.charCodeAt(o))}return t.putBuffer(n),t},s.oidToDer=function(e){var t=e.split("."),r=i.util.createBuffer();r.putByte(40*parseInt(t[0],10)+parseInt(t[1],10));for(var n,a,s,o,c=2;c>>=7,n||(o|=128),a.push(o),n=!1}while(s>0);for(var u=a.length-1;u>=0;--u)r.putByte(a[u])}return r},s.derToOid=function(e){var t;"string"==typeof e&&(e=i.util.createBuffer(e));var r=e.getByte();t=Math.floor(r/40)+"."+r%40;for(var n=0;e.length()>0;)r=e.getByte(),n<<=7,128&r?n+=127&r:(t+="."+(n+r),n=0);return t},s.utcTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,2),10);r=r>=50?1900+r:2e3+r;var n=parseInt(e.substr(2,2),10)-1,a=parseInt(e.substr(4,2),10),i=parseInt(e.substr(6,2),10),s=parseInt(e.substr(8,2),10),o=0;if(e.length>11){var c=e.charAt(10),u=10;"+"!==c&&"-"!==c&&(o=parseInt(e.substr(10,2),10),u+=2)}if(t.setUTCFullYear(r,n,a),t.setUTCHours(i,s,o,0),u&&("+"===(c=e.charAt(u))||"-"===c)){var l=parseInt(e.substr(u+1,2),10),p=parseInt(e.substr(u+4,2),10),f=60*l+p;f*=6e4,"+"===c?t.setTime(+t-f):t.setTime(+t+f)}return t},s.generalizedTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,4),10),n=parseInt(e.substr(4,2),10)-1,a=parseInt(e.substr(6,2),10),i=parseInt(e.substr(8,2),10),s=parseInt(e.substr(10,2),10),o=parseInt(e.substr(12,2),10),c=0,u=0,l=!1;"Z"===e.charAt(e.length-1)&&(l=!0);var p=e.length-5,f=e.charAt(p);if("+"===f||"-"===f){u=60*parseInt(e.substr(p+1,2),10)+parseInt(e.substr(p+4,2),10),u*=6e4,"+"===f&&(u*=-1),l=!0}return"."===e.charAt(14)&&(c=1e3*parseFloat(e.substr(14),10)),l?(t.setUTCFullYear(r,n,a),t.setUTCHours(i,s,o,c),t.setTime(+t+u)):(t.setFullYear(r,n,a),t.setHours(i,s,o,c)),t},s.dateToUtcTime=function(e){if("string"==typeof e)return e;var t="",r=[];r.push((""+e.getUTCFullYear()).substr(2)),r.push(""+(e.getUTCMonth()+1)),r.push(""+e.getUTCDate()),r.push(""+e.getUTCHours()),r.push(""+e.getUTCMinutes()),r.push(""+e.getUTCSeconds());for(var n=0;n=-128&&e<128)return t.putSignedInt(e,8);if(e>=-32768&&e<32768)return t.putSignedInt(e,16);if(e>=-8388608&&e<8388608)return t.putSignedInt(e,24);if(e>=-2147483648&&e<2147483648)return t.putSignedInt(e,32);var r=new Error("Integer too large; max is 32-bits.");throw r.integer=e,r},s.derToInteger=function(e){"string"==typeof e&&(e=i.util.createBuffer(e));var t=8*e.length();if(t>32)throw new Error("Integer too large; max is 32-bits.");return e.getSignedInt(t)},s.validate=function(e,t,r,n){var a=!1;if(e.tagClass!==t.tagClass&&void 0!==t.tagClass||e.type!==t.type&&void 0!==t.type)n&&(e.tagClass!==t.tagClass&&n.push("["+t.name+'] Expected tag class "'+t.tagClass+'", got "'+e.tagClass+'"'),e.type!==t.type&&n.push("["+t.name+'] Expected type "'+t.type+'", got "'+e.type+'"'));else if(e.constructed===t.constructed||void 0===t.constructed){if(a=!0,t.value&&i.util.isArray(t.value))for(var o=0,c=0;a&&c0&&(n+="\n");for(var a="",o=0;o1?n+="0x"+i.util.bytesToHex(e.value.slice(1)):n+="(none)",e.value.length>0){var f=e.value.charCodeAt(0);1==f?n+=" (1 unused bit shown)":f>1&&(n+=" ("+f+" unused bits shown)")}}else e.type===s.Type.OCTETSTRING?(c.test(e.value)||(n+="("+e.value+") "),n+="0x"+i.util.bytesToHex(e.value)):e.type===s.Type.UTF8?n+=i.util.decodeUtf8(e.value):e.type===s.Type.PRINTABLESTRING||e.type===s.Type.IA5String?n+=e.value:c.test(e.value)?n+="0x"+i.util.bytesToHex(e.value):0===e.value.length?n+="[null]":n+=e.value}return n}},function(e,t,r){var n=r(0);e.exports=n.md=n.md||{},n.md.algorithms=n.md.algorithms||{}},function(e,t,r){function n(e,t){var r=function(){return new c.aes.Algorithm(e,t)};c.cipher.registerAlgorithm(e,r)}function a(){d=!0,p=[0,1,2,4,8,16,32,64,128,27,54];for(var e=new Array(256),t=0;t<128;++t)e[t]=t<<1,e[t+128]=t+128<<1^283;u=new Array(256),l=new Array(256),f=new Array(4),h=new Array(4);for(var t=0;t<4;++t)f[t]=new Array(256),h[t]=new Array(256);for(var r,n,a,i,s,o,c,y=0,g=0,t=0;t<256;++t){i=g^g<<1^g<<2^g<<3^g<<4,i=i>>8^255&i^99,u[y]=i,l[i]=y,s=e[i],r=e[y],n=e[r],a=e[n],o=s<<24^i<<16^i<<8^i^s,c=(r^n^a)<<24^(y^a)<<16^(y^n^a)<<8^y^r^a;for(var v=0;v<4;++v)f[v][y]=o,h[v][i]=c,o=o<<24|o>>>8,c=c<<24|c>>>8;0===y?y=g=1:(y=r^e[e[e[r^a]]],g^=e[e[g]])}}function i(e,t){for(var r,n=e.slice(0),a=1,i=n.length,s=i+6+1,o=y*s,c=i;c>>16&255]<<24^u[r>>>8&255]<<16^u[255&r]<<8^u[r>>>24]^p[a]<<24,a++):i>6&&c%i==4&&(r=u[r>>>24]<<24^u[r>>>16&255]<<16^u[r>>>8&255]<<8^u[255&r]),n[c]=n[c-i]^r;if(t){var l,f=h[0],d=h[1],g=h[2],v=h[3],m=n.slice(0);o=n.length;for(var c=0,C=o-y;c>>24]]^d[u[l>>>16&255]]^g[u[l>>>8&255]]^v[u[255&l]];n=m}return n}function s(e,t,r,n){var a,i,s,o,c,p=e.length/4-1;n?(a=h[0],i=h[1],s=h[2],o=h[3],c=l):(a=f[0],i=f[1],s=f[2],o=f[3],c=u);var d,y,g,v,m,C,E;d=t[0]^e[0],y=t[n?3:1]^e[1],g=t[2]^e[2],v=t[n?1:3]^e[3];for(var S=3,T=1;T>>24]^i[y>>>16&255]^s[g>>>8&255]^o[255&v]^e[++S],C=a[y>>>24]^i[g>>>16&255]^s[v>>>8&255]^o[255&d]^e[++S],E=a[g>>>24]^i[v>>>16&255]^s[d>>>8&255]^o[255&y]^e[++S],v=a[v>>>24]^i[d>>>16&255]^s[y>>>8&255]^o[255&g]^e[++S],d=m,y=C,g=E;r[0]=c[d>>>24]<<24^c[y>>>16&255]<<16^c[g>>>8&255]<<8^c[255&v]^e[++S],r[n?3:1]=c[y>>>24]<<24^c[g>>>16&255]<<16^c[v>>>8&255]<<8^c[255&d]^e[++S],r[2]=c[g>>>24]<<24^c[v>>>16&255]<<16^c[d>>>8&255]<<8^c[255&y]^e[++S],r[n?1:3]=c[v>>>24]<<24^c[d>>>16&255]<<16^c[y>>>8&255]<<8^c[255&g]^e[++S]}function o(e){e=e||{};var t,r=(e.mode||"CBC").toUpperCase(),n="AES-"+r;t=e.decrypt?c.cipher.createDecipher(n,e.key):c.cipher.createCipher(n,e.key);var a=t.start;return t.start=function(e,r){var n=null;r instanceof c.util.ByteBuffer&&(n=r,r={}),r=r||{},r.output=n,r.iv=e,a.call(t,r)},t}var c=r(0);r(14),r(21),r(1),e.exports=c.aes=c.aes||{},c.aes.startEncrypting=function(e,t,r,n){var a=o({key:e,output:r,decrypt:!1,mode:n});return a.start(t),a},c.aes.createEncryptionCipher=function(e,t){return o({key:e,output:null,decrypt:!1,mode:t})},c.aes.startDecrypting=function(e,t,r,n){var a=o({key:e,output:r,decrypt:!0,mode:n});return a.start(t),a},c.aes.createDecryptionCipher=function(e,t){return o({key:e,output:null,decrypt:!0,mode:t})},c.aes.Algorithm=function(e,t){d||a();var r=this;r.name=e,r.mode=new t({blockSize:16,cipher:{encrypt:function(e,t){return s(r._w,e,t,!1)},decrypt:function(e,t){return s(r._w,e,t,!0)}}}),r._init=!1},c.aes.Algorithm.prototype.initialize=function(e){if(!this._init){var t,r=e.key;if("string"!=typeof r||16!==r.length&&24!==r.length&&32!==r.length){if(c.util.isArray(r)&&(16===r.length||24===r.length||32===r.length)){t=r,r=c.util.createBuffer();for(var n=0;n>>=2;for(var n=0;n65&&-1!==s){var o=t[s];","===o?(++s,t=t.substr(0,s)+"\r\n "+t.substr(s)):t=t.substr(0,s)+"\r\n"+o+t.substr(s+1),i=a-s-1,s=-1,++a}else" "!==t[a]&&"\t"!==t[a]&&","!==t[a]||(s=a);return t}function a(e){return e.replace(/^\s+/,"")}var i=r(0);r(1);var s=e.exports=i.pem=i.pem||{};s.encode=function(e,t){t=t||{};var r,a="-----BEGIN "+e.type+"-----\r\n";if(e.procType&&(r={name:"Proc-Type",values:[String(e.procType.version),e.procType.type]},a+=n(r)),e.contentDomain&&(r={name:"Content-Domain",values:[e.contentDomain]},a+=n(r)),e.dekInfo&&(r={name:"DEK-Info",values:[e.dekInfo.algorithm]},e.dekInfo.parameters&&r.values.push(e.dekInfo.parameters),a+=n(r)),e.headers)for(var s=0;st.blockLength&&(t.start(),t.update(s.bytes()),s=t.digest()),r=n.util.createBuffer(),a=n.util.createBuffer(),u=s.length();for(var c=0;c=64;){for(a=e.h0,i=e.h1,s=e.h2,o=e.h3,c=e.h4,l=0;l<16;++l)n=r.getInt32(),t[l]=n,u=o^i&(s^o),n=(a<<5|a>>>27)+u+c+1518500249+n,c=o,o=s,s=(i<<30|i>>>2)>>>0,i=a,a=n;for(;l<20;++l)n=t[l-3]^t[l-8]^t[l-14]^t[l-16],n=n<<1|n>>>31,t[l]=n,u=o^i&(s^o),n=(a<<5|a>>>27)+u+c+1518500249+n,c=o,o=s,s=(i<<30|i>>>2)>>>0,i=a,a=n;for(;l<32;++l)n=t[l-3]^t[l-8]^t[l-14]^t[l-16],n=n<<1|n>>>31,t[l]=n,u=i^s^o,n=(a<<5|a>>>27)+u+c+1859775393+n,c=o,o=s,s=(i<<30|i>>>2)>>>0,i=a,a=n;for(;l<40;++l)n=t[l-6]^t[l-16]^t[l-28]^t[l-32],n=n<<2|n>>>30,t[l]=n,u=i^s^o,n=(a<<5|a>>>27)+u+c+1859775393+n,c=o,o=s,s=(i<<30|i>>>2)>>>0,i=a,a=n;for(;l<60;++l)n=t[l-6]^t[l-16]^t[l-28]^t[l-32],n=n<<2|n>>>30,t[l]=n,u=i&s|o&(i^s),n=(a<<5|a>>>27)+u+c+2400959708+n,c=o,o=s,s=(i<<30|i>>>2)>>>0,i=a,a=n;for(;l<80;++l)n=t[l-6]^t[l-16]^t[l-28]^t[l-32],n=n<<2|n>>>30,t[l]=n,u=i^s^o,n=(a<<5|a>>>27)+u+c+3395469782+n,c=o,o=s,s=(i<<30|i>>>2)>>>0,i=a,a=n;e.h0=e.h0+a|0,e.h1=e.h1+i|0,e.h2=e.h2+s|0,e.h3=e.h3+o|0,e.h4=e.h4+c|0,p-=64}}var i=r(0);r(4),r(1);var s=e.exports=i.sha1=i.sha1||{};i.md.sha1=i.md.algorithms.sha1=s,s.create=function(){c||n();var e=null,t=i.util.createBuffer(),r=new Array(80),s={algorithm:"sha1",blockLength:64,digestLength:20,messageLength:0,fullMessageLength:null,messageLengthSize:8};return s.start=function(){s.messageLength=0,s.fullMessageLength=s.messageLength64=[];for(var r=s.messageLengthSize/4,n=0;n>>0,c>>>0];for(var u=s.fullMessageLength.length-1;u>=0;--u)s.fullMessageLength[u]+=c[1],c[1]=c[0]+(s.fullMessageLength[u]/4294967296>>>0),s.fullMessageLength[u]=s.fullMessageLength[u]>>>0,c[0]=c[1]/4294967296>>>0;return t.putBytes(n),a(e,r,t),(t.read>2048||0===t.length())&&t.compact(),s},s.digest=function(){var n=i.util.createBuffer();n.putBytes(t.bytes());var c=s.fullMessageLength[s.fullMessageLength.length-1]+s.messageLengthSize,u=c&s.blockLength-1;n.putBytes(o.substr(0,s.blockLength-u));for(var l,p,f=8*s.fullMessageLength[0],h=0;h>>0,f+=p,n.putInt32(f>>>0),f=l>>>0;n.putInt32(f);var d={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4};a(d,r,n);var y=i.util.createBuffer();return y.putInt32(d.h0),y.putInt32(d.h1),y.putInt32(d.h2),y.putInt32(d.h3),y.putInt32(d.h4),y},s};var o=null,c=!1},function(e,t,r){var n=r(0);r(3),r(8),r(15),r(7),r(22),r(2),r(9),r(1);var a=function(e,t,r,a){var i=n.util.createBuffer(),s=e.length>>1,o=s+(1&e.length),c=e.substr(0,o),u=e.substr(s,o),l=n.util.createBuffer(),p=n.hmac.create();r=t+r;var f=Math.ceil(a/16),h=Math.ceil(a/20);p.start("MD5",c);var d=n.util.createBuffer();l.putBytes(r);for(var y=0;y0&&(l.queue(e,l.createAlert(e,{level:l.Alert.Level.warning,description:l.Alert.Description.no_renegotiation})),l.flush(e)),e.process()},l.parseHelloMessage=function(e,t,r){var a=null,i=e.entity===l.ConnectionEnd.client;if(r<38)e.error(e,{message:i?"Invalid ServerHello message. Message too short.":"Invalid ClientHello message. Message too short.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.illegal_parameter}});else{var s=t.fragment,o=s.length();if(a={version:{major:s.getByte(),minor:s.getByte()},random:n.util.createBuffer(s.getBytes(32)),session_id:c(s,1),extensions:[]},i?(a.cipher_suite=s.getBytes(2),a.compression_method=s.getByte()):(a.cipher_suites=c(s,2),a.compression_methods=c(s,1)),(o=r-(o-s.length()))>0){for(var u=c(s,2);u.length()>0;)a.extensions.push({type:[u.getByte(),u.getByte()],data:c(u,2)});if(!i)for(var p=0;p0;){var d=h.getByte();if(0!==d)break;e.session.extensions.server_name.serverNameList.push(c(h,2).getBytes())}}}if(e.session.version&&(a.version.major!==e.session.version.major||a.version.minor!==e.session.version.minor))return e.error(e,{message:"TLS version change is disallowed during renegotiation.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.protocol_version}});if(i)e.session.cipherSuite=l.getCipherSuite(a.cipher_suite);else for(var y=n.util.createBuffer(a.cipher_suites.bytes());y.length()>0&&(e.session.cipherSuite=l.getCipherSuite(y.getBytes(2)),null===e.session.cipherSuite););if(null===e.session.cipherSuite)return e.error(e,{message:"No cipher suites in common.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.handshake_failure},cipherSuite:n.util.bytesToHex(a.cipher_suite)});e.session.compressionMethod=i?a.compression_method:l.CompressionMethod.none}return a},l.createSecurityParameters=function(e,t){var r=e.entity===l.ConnectionEnd.client,n=t.random.bytes(),a=r?e.session.sp.client_random:n,i=r?n:l.createRandom().getBytes();e.session.sp={entity:e.entity,prf_algorithm:l.PRFAlgorithm.tls_prf_sha256,bulk_cipher_algorithm:null,cipher_type:null,enc_key_length:null,block_length:null,fixed_iv_length:null,record_iv_length:null,mac_algorithm:null,mac_length:null,mac_key_length:null,compression_algorithm:e.session.compressionMethod,pre_master_secret:null,master_secret:null,client_random:a,server_random:i}},l.handleServerHello=function(e,t,r){var n=l.parseHelloMessage(e,t,r);if(!e.fail){if(!(n.version.minor<=e.version.minor))return e.error(e,{message:"Incompatible TLS version.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.protocol_version}});e.version.minor=n.version.minor,e.session.version=e.version;var a=n.session_id.bytes();a.length>0&&a===e.session.id?(e.expect=y,e.session.resuming=!0,e.session.sp.server_random=n.random.bytes()):(e.expect=p,e.session.resuming=!1,l.createSecurityParameters(e,n)),e.session.id=a,e.process()}},l.handleClientHello=function(e,t,r){var a=l.parseHelloMessage(e,t,r);if(!e.fail){var i=a.session_id.bytes(),s=null;if(e.sessionCache&&(s=e.sessionCache.getSession(i),null===s?i="":(s.version.major!==a.version.major||s.version.minor>a.version.minor)&&(s=null,i="")),0===i.length&&(i=n.random.getBytes(32)),e.session.id=i,e.session.clientHelloVersion=a.version,e.session.sp={},s)e.version=e.session.version=s.version,e.session.sp=s.sp;else{for(var o,c=1;c0;)a=c(o.certificate_list,3),i=n.asn1.fromDer(a),a=n.pki.certificateFromAsn1(i,!0),u.push(a)}catch(t){return e.error(e,{message:"Could not parse certificate list.",cause:t,send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.bad_certificate}})}var p=e.entity===l.ConnectionEnd.client;!p&&!0!==e.verifyClient||0!==u.length?0===u.length?e.expect=p?f:E:(p?e.session.serverCertificate=u[0]:e.session.clientCertificate=u[0],l.verifyCertificateChain(e,u)&&(e.expect=p?f:E)):e.error(e,{message:p?"No server certificate provided.":"No client certificate provided.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.illegal_parameter}}),e.process()},l.handleServerKeyExchange=function(e,t,r){if(r>0)return e.error(e,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.unsupported_certificate}});e.expect=h,e.process()},l.handleClientKeyExchange=function(e,t,r){if(r<48)return e.error(e,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.unsupported_certificate}});var a=t.fragment,i={enc_pre_master_secret:c(a,2).getBytes()},s=null;if(e.getPrivateKey)try{s=e.getPrivateKey(e,e.session.serverCertificate),s=n.pki.privateKeyFromPem(s)}catch(t){e.error(e,{message:"Could not get private key.",cause:t,send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.internal_error}})}if(null===s)return e.error(e,{message:"No private key set.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.internal_error}});try{var o=e.session.sp;o.pre_master_secret=s.decrypt(i.enc_pre_master_secret);var u=e.session.clientHelloVersion;if(u.major!==o.pre_master_secret.charCodeAt(0)||u.minor!==o.pre_master_secret.charCodeAt(1))throw new Error("TLS version rollback attack detected.")}catch(e){o.pre_master_secret=n.random.getBytes(48)}e.expect=T,null!==e.session.clientCertificate&&(e.expect=S),e.process()},l.handleCertificateRequest=function(e,t,r){if(r<3)return e.error(e,{message:"Invalid CertificateRequest. Message too short.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.illegal_parameter}});var n=t.fragment,a={certificate_types:c(n,1),certificate_authorities:c(n,2)};e.session.certificateRequest=a,e.expect=d,e.process()},l.handleCertificateVerify=function(e,t,r){if(r<2)return e.error(e,{message:"Invalid CertificateVerify. Message too short.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.illegal_parameter}});var a=t.fragment;a.read-=4;var i=a.bytes();a.read+=4;var s={signature:c(a,2).getBytes()},o=n.util.createBuffer();o.putBuffer(e.session.md5.digest()),o.putBuffer(e.session.sha1.digest()),o=o.getBytes();try{if(!e.session.clientCertificate.publicKey.verify(o,s.signature,"NONE"))throw new Error("CertificateVerify signature does not match.");e.session.md5.update(i),e.session.sha1.update(i)}catch(t){return e.error(e,{message:"Bad signature in CertificateVerify.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.handshake_failure}})}e.expect=T,e.process()},l.handleServerHelloDone=function(e,t,r){if(r>0)return e.error(e,{message:"Invalid ServerHelloDone message. Invalid length.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.record_overflow}});if(null===e.serverCertificate){var a={message:"No server certificate provided. Not enough security.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.insufficient_security}},i=e.verify(e,a.alert.description,0,[]);if(!0!==i)return(i||0===i)&&("object"!=typeof i||n.util.isArray(i)?"number"==typeof i&&(a.alert.description=i):(i.message&&(a.message=i.message),i.alert&&(a.alert.description=i.alert))),e.error(e,a)}null!==e.session.certificateRequest&&(t=l.createRecord(e,{type:l.ContentType.handshake,data:l.createCertificate(e)}),l.queue(e,t)),t=l.createRecord(e,{type:l.ContentType.handshake,data:l.createClientKeyExchange(e)}),l.queue(e,t),e.expect=m;var s=function(e,t){null!==e.session.certificateRequest&&null!==e.session.clientCertificate&&l.queue(e,l.createRecord(e,{type:l.ContentType.handshake,data:l.createCertificateVerify(e,t)})),l.queue(e,l.createRecord(e,{type:l.ContentType.change_cipher_spec,data:l.createChangeCipherSpec()})),e.state.pending=l.createConnectionState(e),e.state.current.write=e.state.pending.write,l.queue(e,l.createRecord(e,{type:l.ContentType.handshake,data:l.createFinished(e)})),e.expect=y,l.flush(e),e.process()};if(null===e.session.certificateRequest||null===e.session.clientCertificate)return s(e,null);l.getClientSignature(e,s)},l.handleChangeCipherSpec=function(e,t){if(1!==t.fragment.getByte())return e.error(e,{message:"Invalid ChangeCipherSpec message received.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.illegal_parameter}});var r=e.entity===l.ConnectionEnd.client;(e.session.resuming&&r||!e.session.resuming&&!r)&&(e.state.pending=l.createConnectionState(e)),e.state.current.read=e.state.pending.read,(!e.session.resuming&&r||e.session.resuming&&!r)&&(e.state.pending=null),e.expect=r?g:b,e.process()},l.handleFinished=function(e,t,r){var i=t.fragment;i.read-=4;var s=i.bytes();i.read+=4;var o=t.fragment.getBytes();i=n.util.createBuffer(),i.putBuffer(e.session.md5.digest()),i.putBuffer(e.session.sha1.digest());var c=e.entity===l.ConnectionEnd.client,u=c?"server finished":"client finished",p=e.session.sp;if(i=a(p.master_secret,u,i.getBytes(),12),i.getBytes()!==o)return e.error(e,{message:"Invalid verify_data in Finished message.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.decrypt_error}});e.session.md5.update(s),e.session.sha1.update(s),(e.session.resuming&&c||!e.session.resuming&&!c)&&(l.queue(e,l.createRecord(e,{type:l.ContentType.change_cipher_spec,data:l.createChangeCipherSpec()})),e.state.current.write=e.state.pending.write,e.state.pending=null,l.queue(e,l.createRecord(e,{type:l.ContentType.handshake,data:l.createFinished(e)}))),e.expect=c?v:I,e.handshaking=!1,++e.handshakes,e.peerCertificate=c?e.session.serverCertificate:e.session.clientCertificate,l.flush(e),e.isConnected=!0,e.connected(e),e.process()},l.handleAlert=function(e,t){var r,n=t.fragment,a={level:n.getByte(),description:n.getByte()};switch(a.description){case l.Alert.Description.close_notify:r="Connection closed.";break;case l.Alert.Description.unexpected_message:r="Unexpected message.";break;case l.Alert.Description.bad_record_mac:r="Bad record MAC.";break;case l.Alert.Description.decryption_failed:r="Decryption failed.";break;case l.Alert.Description.record_overflow:r="Record overflow.";break;case l.Alert.Description.decompression_failure:r="Decompression failed.";break;case l.Alert.Description.handshake_failure:r="Handshake failure.";break;case l.Alert.Description.bad_certificate:r="Bad certificate.";break;case l.Alert.Description.unsupported_certificate:r="Unsupported certificate.";break;case l.Alert.Description.certificate_revoked:r="Certificate revoked.";break;case l.Alert.Description.certificate_expired:r="Certificate expired.";break;case l.Alert.Description.certificate_unknown:r="Certificate unknown.";break;case l.Alert.Description.illegal_parameter:r="Illegal parameter.";break;case l.Alert.Description.unknown_ca:r="Unknown certificate authority.";break;case l.Alert.Description.access_denied:r="Access denied.";break;case l.Alert.Description.decode_error:r="Decode error.";break;case l.Alert.Description.decrypt_error:r="Decrypt error.";break;case l.Alert.Description.export_restriction:r="Export restriction.";break;case l.Alert.Description.protocol_version:r="Unsupported protocol version.";break;case l.Alert.Description.insufficient_security:r="Insufficient security.";break;case l.Alert.Description.internal_error:r="Internal error.";break;case l.Alert.Description.user_canceled:r="User canceled.";break;case l.Alert.Description.no_renegotiation:r="Renegotiation not supported.";break;default:r="Unknown error."}if(a.description===l.Alert.Description.close_notify)return e.close();e.error(e,{message:r,send:!1,origin:e.entity===l.ConnectionEnd.client?"server":"client",alert:a}),e.process()},l.handleHandshake=function(e,t){var r=t.fragment,a=r.getByte(),i=r.getInt24();if(i>r.length())return e.fragmented=t,t.fragment=n.util.createBuffer(),r.read-=4,e.process();e.fragmented=null,r.read-=4;var s=r.bytes(i+4);r.read+=4,a in K[e.entity][e.expect]?(e.entity!==l.ConnectionEnd.server||e.open||e.fail||(e.handshaking=!0,e.session={version:null,extensions:{server_name:{serverNameList:[]}},cipherSuite:null,compressionMethod:null,serverCertificate:null,clientCertificate:null,md5:n.md.md5.create(),sha1:n.md.sha1.create()}),a!==l.HandshakeType.hello_request&&a!==l.HandshakeType.certificate_verify&&a!==l.HandshakeType.finished&&(e.session.md5.update(s),e.session.sha1.update(s)),K[e.entity][e.expect][a](e,t,i)):l.handleUnexpected(e,t)},l.handleApplicationData=function(e,t){e.data.putBuffer(t.fragment),e.dataReady(e),e.process()},l.handleHeartbeat=function(e,t){var r=t.fragment,a=r.getByte(),i=r.getInt16(),s=r.getBytes(i);if(a===l.HeartbeatMessageType.heartbeat_request){if(e.handshaking||i>s.length)return e.process();l.queue(e,l.createRecord(e,{type:l.ContentType.heartbeat,data:l.createHeartbeat(l.HeartbeatMessageType.heartbeat_response,s)})),l.flush(e)}else if(a===l.HeartbeatMessageType.heartbeat_response){if(s!==e.expectedHeartbeatPayload)return e.process();e.heartbeatReceived&&e.heartbeatReceived(e,n.util.createBuffer(s))}e.process()};var p=1,f=2,h=3,d=4,y=5,g=6,v=7,m=8,C=1,E=2,S=3,T=4,b=5,I=6,A=l.handleUnexpected,B=l.handleChangeCipherSpec,k=l.handleAlert,N=l.handleHandshake,w=l.handleApplicationData,R=l.handleHeartbeat,L=[];L[l.ConnectionEnd.client]=[[A,k,N,A,R],[A,k,N,A,R],[A,k,N,A,R],[A,k,N,A,R],[A,k,N,A,R],[B,k,A,A,R],[A,k,N,A,R],[A,k,N,w,R],[A,k,N,A,R]],L[l.ConnectionEnd.server]=[[A,k,N,A,R],[A,k,N,A,R],[A,k,N,A,R],[A,k,N,A,R],[B,k,A,A,R],[A,k,N,A,R],[A,k,N,w,R],[A,k,N,A,R]];var _=l.handleHelloRequest,U=l.handleServerHello,D=l.handleCertificate,P=l.handleServerKeyExchange,O=l.handleCertificateRequest,V=l.handleServerHelloDone,x=l.handleFinished,K=[];K[l.ConnectionEnd.client]=[[A,A,U,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A],[_,A,A,A,A,A,A,A,A,A,A,D,P,O,V,A,A,A,A,A,A],[_,A,A,A,A,A,A,A,A,A,A,A,P,O,V,A,A,A,A,A,A],[_,A,A,A,A,A,A,A,A,A,A,A,A,O,V,A,A,A,A,A,A],[_,A,A,A,A,A,A,A,A,A,A,A,A,A,V,A,A,A,A,A,A],[_,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A],[_,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,x],[_,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A],[_,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A]];var M=l.handleClientHello,F=l.handleClientKeyExchange,q=l.handleCertificateVerify;K[l.ConnectionEnd.server]=[[A,M,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A],[A,A,A,A,A,A,A,A,A,A,A,D,A,A,A,A,A,A,A,A,A],[A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,F,A,A,A,A],[A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,q,A,A,A,A,A],[A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A],[A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,x],[A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A],[A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A]],l.generateKeys=function(e,t){var r=a,n=t.client_random+t.server_random;e.session.resuming||(t.master_secret=r(t.pre_master_secret,"master secret",n,48).bytes(),t.pre_master_secret=null),n=t.server_random+t.client_random;var i=2*t.mac_key_length+2*t.enc_key_length,s=e.version.major===l.Versions.TLS_1_0.major&&e.version.minor===l.Versions.TLS_1_0.minor;s&&(i+=2*t.fixed_iv_length);var o=r(t.master_secret,"key expansion",n,i),c={client_write_MAC_key:o.getBytes(t.mac_key_length),server_write_MAC_key:o.getBytes(t.mac_key_length),client_write_key:o.getBytes(t.enc_key_length),server_write_key:o.getBytes(t.enc_key_length)};return s&&(c.client_write_IV=o.getBytes(t.fixed_iv_length),c.server_write_IV=o.getBytes(t.fixed_iv_length)),c},l.createConnectionState=function(e){var t=e.entity===l.ConnectionEnd.client,r=function(){var e={sequenceNumber:[0,0],macKey:null,macLength:0,macFunction:null,cipherState:null,cipherFunction:function(e){return!0},compressionState:null,compressFunction:function(e){return!0},updateSequenceNumber:function(){4294967295===e.sequenceNumber[1]?(e.sequenceNumber[1]=0,++e.sequenceNumber[0]):++e.sequenceNumber[1]}};return e},n={read:r(),write:r()};if(n.read.update=function(e,t){return n.read.cipherFunction(t,n.read)?n.read.compressFunction(e,t,n.read)||e.error(e,{message:"Could not decompress record.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.decompression_failure}}):e.error(e,{message:"Could not decrypt record or bad MAC.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.bad_record_mac}}),!e.fail},n.write.update=function(e,t){return n.write.compressFunction(e,t,n.write)?n.write.cipherFunction(t,n.write)||e.error(e,{message:"Could not encrypt record.",send:!1,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.internal_error}}):e.error(e,{message:"Could not compress record.",send:!1,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.internal_error}}),!e.fail},e.session){var a=e.session.sp;switch(e.session.cipherSuite.initSecurityParameters(a),a.keys=l.generateKeys(e,a),n.read.macKey=t?a.keys.server_write_MAC_key:a.keys.client_write_MAC_key,n.write.macKey=t?a.keys.client_write_MAC_key:a.keys.server_write_MAC_key,e.session.cipherSuite.initConnectionState(n,e,a),a.compression_algorithm){case l.CompressionMethod.none:break;case l.CompressionMethod.deflate:n.read.compressFunction=o,n.write.compressFunction=s;break;default:throw new Error("Unsupported compression algorithm.")}}return n},l.createRandom=function(){var e=new Date,t=+e+6e4*e.getTimezoneOffset(),r=n.util.createBuffer();return r.putInt32(t),r.putBytes(n.random.getBytes(28)),r},l.createRecord=function(e,t){return t.data?{type:t.type,version:{major:e.version.major,minor:e.version.minor},length:t.data.length(),fragment:t.data}:null},l.createAlert=function(e,t){var r=n.util.createBuffer();return r.putByte(t.level),r.putByte(t.description),l.createRecord(e,{type:l.ContentType.alert,data:r})},l.createClientHello=function(e){e.session.clientHelloVersion={major:e.version.major,minor:e.version.minor};for(var t=n.util.createBuffer(),r=0;r0&&(d+=2);var y=e.session.id,g=y.length+1+2+4+28+2+i+1+o+d,v=n.util.createBuffer();return v.putByte(l.HandshakeType.client_hello),v.putInt24(g),v.putByte(e.version.major),v.putByte(e.version.minor),v.putBytes(e.session.sp.client_random),u(v,1,n.util.createBuffer(y)),u(v,2,t),u(v,1,s),d>0&&u(v,2,c),v},l.createServerHello=function(e){var t=e.session.id,r=t.length+1+2+4+28+2+1,a=n.util.createBuffer();return a.putByte(l.HandshakeType.server_hello),a.putInt24(r),a.putByte(e.version.major),a.putByte(e.version.minor),a.putBytes(e.session.sp.server_random),u(a,1,n.util.createBuffer(t)),a.putByte(e.session.cipherSuite.id[0]),a.putByte(e.session.cipherSuite.id[1]),a.putByte(e.session.compressionMethod),a},l.createCertificate=function(e){var t=e.entity===l.ConnectionEnd.client,r=null;if(e.getCertificate){var a;a=t?e.session.certificateRequest:e.session.extensions.server_name.serverNameList,r=e.getCertificate(e,a)}var i=n.util.createBuffer();if(null!==r)try{n.util.isArray(r)||(r=[r]);for(var s=null,o=0;ol.MaxFragment;)a.push(l.createRecord(e,{type:t.type,data:n.util.createBuffer(i.slice(0,l.MaxFragment))})),i=i.slice(l.MaxFragment);i.length>0&&a.push(l.createRecord(e,{type:t.type,data:n.util.createBuffer(i)}))}for(var s=0;s0&&(a=r.order[0]),null!==a&&a in r.cache){t=r.cache[a],delete r.cache[a];for(var i in r.order)if(r.order[i]===a){r.order.splice(i,1);break}}return t},r.setSession=function(e,t){if(r.order.length===r.capacity){var a=r.order.shift();delete r.cache[a]}var a=n.util.bytesToHex(e);r.order.push(a),r.cache[a]=t}}return r},l.createConnection=function(e){var t=null;t=e.caStore?n.util.isArray(e.caStore)?n.pki.createCaStore(e.caStore):e.caStore:n.pki.createCaStore();var r=e.cipherSuites||null;if(null===r){r=[];for(var a in l.CipherSuites)r.push(l.CipherSuites[a])}var i=e.server?l.ConnectionEnd.server:l.ConnectionEnd.client,s=e.sessionCache?l.createSessionCache(e.sessionCache):null,o={version:{major:l.Version.major,minor:l.Version.minor},entity:i,sessionId:e.sessionId,caStore:t,sessionCache:s,cipherSuites:r,connected:e.connected,virtualHost:e.virtualHost||null,verifyClient:e.verifyClient||!1,verify:e.verify||function(e,t,r,n){return t},verifyOptions:e.verifyOptions||{},getCertificate:e.getCertificate||null,getPrivateKey:e.getPrivateKey||null,getSignature:e.getSignature||null,input:n.util.createBuffer(),tlsData:n.util.createBuffer(),data:n.util.createBuffer(),tlsDataReady:e.tlsDataReady,dataReady:e.dataReady,heartbeatReceived:e.heartbeatReceived,closed:e.closed,error:function(t,r){r.origin=r.origin||(t.entity===l.ConnectionEnd.client?"client":"server"),r.send&&(l.queue(t,l.createAlert(t,r.alert)),l.flush(t));var n=!1!==r.fatal;n&&(t.fail=!0),e.error(t,r),n&&t.close(!1)},deflate:e.deflate||null,inflate:e.inflate||null};o.reset=function(e){o.version={major:l.Version.major,minor:l.Version.minor},o.record=null,o.session=null,o.peerCertificate=null,o.state={pending:null,current:null},o.expect=(o.entity,l.ConnectionEnd.client,0),o.fragmented=null,o.records=[],o.open=!1,o.handshakes=0,o.handshaking=!1,o.isConnected=!1,o.fail=!(e||void 0===e),o.input.clear(),o.tlsData.clear(),o.data.clear(),o.state.current=l.createConnectionState(o)},o.reset();var c=function(e,t){var r=t.type-l.ContentType.change_cipher_spec,n=L[e.entity][e.expect];r in n?n[r](e,t):l.handleUnexpected(e,t)},u=function(e){var t=0,r=e.input,a=r.length();if(a<5)t=5-a;else{e.record={type:r.getByte(),version:{major:r.getByte(),minor:r.getByte()},length:r.getInt16(),fragment:n.util.createBuffer(),ready:!1};var i=e.record.version.major===e.version.major;i&&e.session&&e.session.version&&(i=e.record.version.minor===e.version.minor),i||e.error(e,{message:"Incompatible TLS version.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.protocol_version}})}return t},p=function(e){var t=0,r=e.input,n=r.length();if(n0&&(o.sessionCache&&(t=o.sessionCache.getSession(e)),null===t&&(e="")),0===e.length&&o.sessionCache&&null!==(t=o.sessionCache.getSession())&&(e=t.id),o.session={id:e,version:null,cipherSuite:null,compressionMethod:null,serverCertificate:null,certificateRequest:null,clientCertificate:null,sp:{},md5:n.md.md5.create(),sha1:n.md.sha1.create()},t&&(o.version=t.version,o.session.sp=t.sp),o.session.sp.client_random=l.createRandom().getBytes(),o.open=!0,l.queue(o,l.createRecord(o,{type:l.ContentType.handshake,data:l.createClientHello(o)})),l.flush(o)}},o.process=function(e){var t=0;return e&&o.input.putBytes(e),o.fail||(null!==o.record&&o.record.ready&&o.record.fragment.isEmpty()&&(o.record=null),null===o.record&&(t=u(o)),o.fail||null===o.record||o.record.ready||(t=p(o)),!o.fail&&null!==o.record&&o.record.ready&&c(o,o.record)),t},o.prepare=function(e){return l.queue(o,l.createRecord(o,{type:l.ContentType.application_data,data:n.util.createBuffer(e)})),l.flush(o)},o.prepareHeartbeatRequest=function(e,t){return e instanceof n.util.ByteBuffer&&(e=e.bytes()),void 0===t&&(t=e.length),o.expectedHeartbeatPayload=e,l.queue(o,l.createRecord(o,{type:l.ContentType.heartbeat,data:l.createHeartbeat(l.HeartbeatMessageType.heartbeat_request,e,t)})),l.flush(o)},o.close=function(e){if(!o.fail&&o.sessionCache&&o.session){var t={id:o.session.id,version:o.session.version,sp:o.session.sp};t.sp.keys=null,o.sessionCache.setSession(t.id,t)}o.open&&(o.open=!1,o.input.clear(),(o.isConnected||o.handshaking)&&(o.isConnected=o.handshaking=!1,l.queue(o,l.createAlert(o,{level:l.Alert.Level.warning,description:l.Alert.Description.close_notify})),l.flush(o)),o.closed(o)),o.reset(e)},o},e.exports=n.tls=n.tls||{};for(var G in l)"function"!=typeof l[G]&&(n.tls[G]=l[G]);n.tls.prf_tls1=a,n.tls.hmac_sha1=i,n.tls.createSessionCache=l.createSessionCache,n.tls.createConnection=l.createConnection},function(e,t,r){function n(e,t){var r=function(){return new o.des.Algorithm(e,t)};o.cipher.registerAlgorithm(e,r)}function a(e){for(var t,r=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],n=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],a=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],i=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],s=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],o=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],c=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],u=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],l=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],p=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],f=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],h=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],d=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],y=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],g=e.length()>8?3:1,v=[],m=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],C=0,E=0;E>>4^T),T^=t,S^=t<<4,t=65535&(T>>>-16^S),S^=t,T^=t<<-16,t=858993459&(S>>>2^T),T^=t,S^=t<<2,t=65535&(T>>>-16^S),S^=t,T^=t<<-16,t=1431655765&(S>>>1^T),T^=t,S^=t<<1,t=16711935&(T>>>8^S),S^=t,T^=t<<8,t=1431655765&(S>>>1^T),T^=t,S^=t<<1,t=S<<8|T>>>20&240,S=T<<24|T<<8&16711680|T>>>8&65280|T>>>24&240,T=t;for(var b=0;b>>26,T=T<<2|T>>>26):(S=S<<1|S>>>27,T=T<<1|T>>>27),S&=-15,T&=-15;var I=r[S>>>28]|n[S>>>24&15]|a[S>>>20&15]|i[S>>>16&15]|s[S>>>12&15]|o[S>>>8&15]|c[S>>>4&15],A=u[T>>>28]|l[T>>>24&15]|p[T>>>20&15]|f[T>>>16&15]|h[T>>>12&15]|d[T>>>8&15]|y[T>>>4&15];t=65535&(A>>>16^I),v[C++]=I^t,v[C++]=A^t<<16}}return v}function i(e,t,r,n){var a,i=32===e.length?3:9;a=3===i?n?[30,-2,-2]:[0,32,2]:n?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var s,o=t[0],g=t[1];s=252645135&(o>>>4^g),g^=s,o^=s<<4,s=65535&(o>>>16^g),g^=s,o^=s<<16,s=858993459&(g>>>2^o),o^=s,g^=s<<2,s=16711935&(g>>>8^o),o^=s,g^=s<<8,s=1431655765&(o>>>1^g),g^=s,o^=s<<1,o=o<<1|o>>>31,g=g<<1|g>>>31;for(var v=0;v>>4|g<<28)^e[E+1];s=o,o=g,g=s^(u[S>>>24&63]|p[S>>>16&63]|h[S>>>8&63]|y[63&S]|c[T>>>24&63]|l[T>>>16&63]|f[T>>>8&63]|d[63&T])}s=o,o=g,g=s}o=o>>>1|o<<31,g=g>>>1|g<<31,s=1431655765&(o>>>1^g),g^=s,o^=s<<1,s=16711935&(g>>>8^o),o^=s,g^=s<<8,s=858993459&(g>>>2^o),o^=s,g^=s<<2,s=65535&(o>>>16^g),g^=s,o^=s<<16,s=252645135&(o>>>4^g),g^=s,o^=s<<4,r[0]=o,r[1]=g}function s(e){e=e||{};var t,r=(e.mode||"CBC").toUpperCase(),n="DES-"+r;t=e.decrypt?o.cipher.createDecipher(n,e.key):o.cipher.createCipher(n,e.key);var a=t.start;return t.start=function(e,r){var n=null;r instanceof o.util.ByteBuffer&&(n=r,r={}),r=r||{},r.output=n,r.iv=e,a.call(t,r)},t}var o=r(0);r(14),r(21),r(1),e.exports=o.des=o.des||{},o.des.startEncrypting=function(e,t,r,n){var a=s({key:e,output:r,decrypt:!1,mode:n||(null===t?"ECB":"CBC")});return a.start(t),a},o.des.createEncryptionCipher=function(e,t){return s({key:e,output:null,decrypt:!1,mode:t})},o.des.startDecrypting=function(e,t,r,n){var a=s({key:e,output:r,decrypt:!0,mode:n||(null===t?"ECB":"CBC")});return a.start(t),a},o.des.createDecryptionCipher=function(e,t){return s({key:e,output:null,decrypt:!0,mode:t})},o.des.Algorithm=function(e,t){var r=this;r.name=e,r.mode=new t({blockSize:8,cipher:{encrypt:function(e,t){return i(r._keys,e,t,!1)},decrypt:function(e,t){return i(r._keys,e,t,!0)}}}),r._init=!1},o.des.Algorithm.prototype.initialize=function(e){if(!this._init){var t=o.util.createBuffer(e.key);if(0===this.name.indexOf("3DES")&&24!==t.length())throw new Error("Invalid Triple-DES key size: "+8*t.length());this._keys=a(t),this._init=!0}},n("DES-ECB",o.cipher.modes.ecb),n("DES-CBC",o.cipher.modes.cbc),n("DES-CFB",o.cipher.modes.cfb),n("DES-OFB",o.cipher.modes.ofb),n("DES-CTR",o.cipher.modes.ctr),n("3DES-ECB",o.cipher.modes.ecb),n("3DES-CBC",o.cipher.modes.cbc),n("3DES-CFB",o.cipher.modes.cfb),n("3DES-OFB",o.cipher.modes.ofb),n("3DES-CTR",o.cipher.modes.ctr);var c=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],u=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],l=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],p=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],f=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],h=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],d=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],y=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696]},function(e,t,r){function n(e,t,r){var n=f.util.createBuffer(),a=Math.ceil(t.n.bitLength()/8);if(e.length>a-11){var i=new Error("Message is too long for PKCS#1 v1.5 padding.");throw i.length=e.length,i.max=a-11,i}n.putByte(0),n.putByte(r);var s,o=a-3-e.length;if(0===r||1===r){s=0===r?0:255;for(var c=0;c0;){for(var u=0,l=f.random.getBytes(o),c=0;c1;){if(255!==i.getByte()){--i.read;break}++c}else if(2===o)for(c=0;i.length()>1;){if(0===i.getByte()){--i.read;break}++c}if(0!==i.getByte()||c!==a-3-i.length())throw new Error("Encryption block is invalid.");return i.getBytes()}function i(e,t,r){function n(){a(e.pBits,function(t,n){return t?r(t):(e.p=n,null!==e.q?i(t,e.q):void a(e.qBits,i))})}function a(e,t){f.prime.generateProbablePrime(e,s,t)}function i(t,s){if(t)return r(t);if(e.q=s,e.p.compareTo(e.q)<0){var o=e.p;e.p=e.q,e.q=o}if(0!==e.p.subtract(h.ONE).gcd(e.e).compareTo(h.ONE))return e.p=null,void n();if(0!==e.q.subtract(h.ONE).gcd(e.e).compareTo(h.ONE))return e.q=null,void a(e.qBits,i);if(e.p1=e.p.subtract(h.ONE),e.q1=e.q.subtract(h.ONE),e.phi=e.p1.multiply(e.q1),0!==e.phi.gcd(e.e).compareTo(h.ONE))return e.p=e.q=null,void n();if(e.n=e.p.multiply(e.q),e.n.bitLength()!==e.bits)return e.q=null,void a(e.qBits,i);var c=e.e.modInverse(e.phi);e.keys={privateKey:v.rsa.setPrivateKey(e.n,e.e,c,e.p,e.q,c.mod(e.p1),c.mod(e.q1),e.q.modInverse(e.p)),publicKey:v.rsa.setPublicKey(e.n,e.e)},r(null,e.keys)}"function"==typeof t&&(r=t,t={}),t=t||{};var s={algorithm:{name:t.algorithm||"PRIMEINC",options:{workers:t.workers||2,workLoad:t.workLoad||100,workerScript:t.workerScript}}};"prng"in t&&(s.prng=t.prng),n()}function s(e){var t=e.toString(16);t[0]>="8"&&(t="00"+t);var r=f.util.hexToBytes(t);return r.length>1&&(0===r.charCodeAt(0)&&0==(128&r.charCodeAt(1))||255===r.charCodeAt(0)&&128==(128&r.charCodeAt(1)))?r.substr(1):r}function o(e){return e<=100?27:e<=150?18:e<=200?15:e<=250?12:e<=300?9:e<=350?8:e<=400?7:e<=500?6:e<=600?5:e<=800?4:e<=1250?3:2}function c(e){return f.util.isNodejs&&"function"==typeof d[e]}function u(e){return void 0!==g.globalScope&&"object"==typeof g.globalScope.crypto&&"object"==typeof g.globalScope.crypto.subtle&&"function"==typeof g.globalScope.crypto.subtle[e]}function l(e){return void 0!==g.globalScope&&"object"==typeof g.globalScope.msCrypto&&"object"==typeof g.globalScope.msCrypto.subtle&&"function"==typeof g.globalScope.msCrypto.subtle[e]}function p(e){for(var t=f.util.hexToBytes(e.toString(16)),r=new Uint8Array(t.length),n=0;n=0||!n.gcd(t.n).equals(h.ONE));e=e.multiply(n.modPow(t.e,t.n)).mod(t.n);for(var a=e.mod(t.p).modPow(t.dP,t.p),i=e.mod(t.q).modPow(t.dQ,t.q);a.compareTo(i)<0;)a=a.add(t.p);var s=a.subtract(i).multiply(t.qInv).mod(t.p).multiply(t.q).add(i);return s=s.multiply(n.modInverse(t.n)).mod(t.n)};v.rsa.encrypt=function(e,t,r){var a,i=r,s=Math.ceil(t.n.bitLength()/8);!1!==r&&!0!==r?(i=2===r,a=n(e,t,r)):(a=f.util.createBuffer(),a.putBytes(e));for(var o=new h(a.toHex(),16),c=I(o,t,i),u=c.toString(16),l=f.util.createBuffer(),p=s-Math.ceil(u.length/2);p>0;)l.putByte(0),--p;return l.putBytes(f.util.hexToBytes(u)),l.getBytes()},v.rsa.decrypt=function(e,t,r,n){var i=Math.ceil(t.n.bitLength()/8);if(e.length!==i){var s=new Error("Encrypted message length is invalid.");throw s.length=e.length,s.expected=i,s}var o=new h(f.util.createBuffer(e).toHex(),16);if(o.compareTo(t.n)>=0)throw new Error("Encrypted message is invalid.");for(var c=I(o,t,r),u=c.toString(16),l=f.util.createBuffer(),p=i-Math.ceil(u.length/2);p>0;)l.putByte(0),--p;return l.putBytes(f.util.hexToBytes(u)),!1!==n?a(l.getBytes(),t,r):l.getBytes()},v.rsa.createKeyPairGenerationState=function(e,t,r){"string"==typeof e&&(e=parseInt(e,10)),e=e||2048,r=r||{};var n,a=r.prng||f.random,i={nextBytes:function(e){for(var t=a.getBytesSync(e.length),r=0;r>1,pBits:e-(e>>1),pqState:0,num:null,keys:null},n.e.fromInt(n.eInt),n},v.rsa.stepKeyPairGenerationState=function(e,t){"algorithm"in e||(e.algorithm="PRIMEINC");var r=new h(null);r.fromInt(30);for(var n,a=0,i=function(e,t){return e|t},s=+new Date,c=0;null===e.keys&&(t<=0||cu?e.pqState=0:e.num.isProbablePrime(o(e.num.bitLength()))?++e.pqState:e.num.dAddOffset(m[a++%8],0):2===e.pqState?e.pqState=0===e.num.subtract(h.ONE).gcd(e.e).compareTo(h.ONE)?3:0:3===e.pqState&&(e.pqState=0,null===e.p?e.p=e.num:e.q=e.num,null!==e.p&&null!==e.q&&++e.state,e.num=null)}else if(1===e.state)e.p.compareTo(e.q)<0&&(e.num=e.p,e.p=e.q,e.q=e.num),++e.state;else if(2===e.state)e.p1=e.p.subtract(h.ONE),e.q1=e.q.subtract(h.ONE),e.phi=e.p1.multiply(e.q1),++e.state;else if(3===e.state)0===e.phi.gcd(e.e).compareTo(h.ONE)?++e.state:(e.p=null,e.q=null,e.state=0);else if(4===e.state)e.n=e.p.multiply(e.q),e.n.bitLength()===e.bits?++e.state:(e.q=null,e.state=0);else if(5===e.state){var p=e.e.modInverse(e.phi);e.keys={privateKey:v.rsa.setPrivateKey(e.n,e.e,p,e.p,e.q,p.mod(e.p1),p.mod(e.q1),e.q.modInverse(e.p)),publicKey:v.rsa.setPublicKey(e.n,e.e)}}n=+new Date,c+=n-s,s=n}return null!==e.keys},v.rsa.generateKeyPair=function(e,t,r,n){if(1===arguments.length?"object"==typeof e?(r=e,e=void 0):"function"==typeof e&&(n=e,e=void 0):2===arguments.length?"number"==typeof e?"function"==typeof t?(n=t,t=void 0):"number"!=typeof t&&(r=t,t=void 0):(r=e,n=t,e=void 0,t=void 0):3===arguments.length&&("number"==typeof t?"function"==typeof r&&(n=r,r=void 0):(n=r,r=t,t=void 0)),r=r||{},void 0===e&&(e=r.bits||2048),void 0===t&&(t=r.e||65537),!f.options.usePureJavaScript&&!r.prng&&e>=256&&e<=16384&&(65537===t||3===t))if(n){if(c("generateKeyPair"))return d.generateKeyPair("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},function(e,t,r){if(e)return n(e);n(null,{privateKey:v.privateKeyFromPem(r),publicKey:v.publicKeyFromPem(t)})});if(u("generateKey")&&u("exportKey"))return g.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:p(t),hash:{name:"SHA-256"}},!0,["sign","verify"]).then(function(e){return g.globalScope.crypto.subtle.exportKey("pkcs8",e.privateKey)}).then(void 0,function(e){n(e)}).then(function(e){if(e){var t=v.privateKeyFromAsn1(y.fromDer(f.util.createBuffer(e)));n(null,{privateKey:t,publicKey:v.setRsaPublicKey(t.n,t.e)})}});if(l("generateKey")&&l("exportKey")){var a=g.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:p(t),hash:{name:"SHA-256"}},!0,["sign","verify"]);return a.oncomplete=function(e){var t=e.target.result,r=g.globalScope.msCrypto.subtle.exportKey("pkcs8",t.privateKey);r.oncomplete=function(e){var t=e.target.result,r=v.privateKeyFromAsn1(y.fromDer(f.util.createBuffer(t)));n(null,{privateKey:r,publicKey:v.setRsaPublicKey(r.n,r.e)})},r.onerror=function(e){n(e)}},void(a.onerror=function(e){n(e)})}}else if(c("generateKeyPairSync")){var s=d.generateKeyPairSync("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:v.privateKeyFromPem(s.privateKey),publicKey:v.publicKeyFromPem(s.publicKey)}}var o=v.rsa.createKeyPairGenerationState(e,t,r);if(!n)return v.rsa.stepKeyPairGenerationState(o,0),o.keys;i(o,r,n)},v.setRsaPublicKey=v.rsa.setPublicKey=function(e,t){var r={n:e,e:t};return r.encrypt=function(e,t,a){if("string"==typeof t?t=t.toUpperCase():void 0===t&&(t="RSAES-PKCS1-V1_5"),"RSAES-PKCS1-V1_5"===t)t={encode:function(e,t,r){return n(e,t,2).getBytes()}};else if("RSA-OAEP"===t||"RSAES-OAEP"===t)t={encode:function(e,t){return f.pkcs1.encode_rsa_oaep(t,e,a)}};else if(-1!==["RAW","NONE","NULL",null].indexOf(t))t={encode:function(e){return e}};else if("string"==typeof t)throw new Error('Unsupported encryption scheme: "'+t+'".');var i=t.encode(e,r,!0);return v.rsa.encrypt(i,r,!0)},r.verify=function(e,t,n){"string"==typeof n?n=n.toUpperCase():void 0===n&&(n="RSASSA-PKCS1-V1_5"),"RSASSA-PKCS1-V1_5"===n?n={verify:function(e,t){return t=a(t,r,!0),e===y.fromDer(t).value[1].value}}:"NONE"!==n&&"NULL"!==n&&null!==n||(n={verify:function(e,t){return t=a(t,r,!0),e===t}});var i=v.rsa.decrypt(t,r,!0,!1);return n.verify(e,i,r.n.bitLength())},r},v.setRsaPrivateKey=v.rsa.setPrivateKey=function(e,t,r,n,i,s,o,c){var u={n:e,e:t,d:r,p:n,q:i,dP:s,dQ:o,qInv:c};return u.decrypt=function(e,t,r){"string"==typeof t?t=t.toUpperCase():void 0===t&&(t="RSAES-PKCS1-V1_5");var n=v.rsa.decrypt(e,u,!1,!1);if("RSAES-PKCS1-V1_5"===t)t={decode:a};else if("RSA-OAEP"===t||"RSAES-OAEP"===t)t={decode:function(e,t){return f.pkcs1.decode_rsa_oaep(t,e,r)}};else{if(-1===["RAW","NONE","NULL",null].indexOf(t))throw new Error('Unsupported encryption scheme: "'+t+'".');t={decode:function(e){return e}}}return t.decode(n,u,!1)},u.sign=function(e,t){var r=!1;"string"==typeof t&&(t=t.toUpperCase()),void 0===t||"RSASSA-PKCS1-V1_5"===t?(t={encode:b},r=1):"NONE"!==t&&"NULL"!==t&&null!==t||(t={encode:function(){return e}},r=1);var n=t.encode(e,u.n.bitLength());return v.rsa.encrypt(n,u,r)},u},v.wrapRsaPrivateKey=function(e){return y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,y.integerToDer(0).getBytes()),y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[y.create(y.Class.UNIVERSAL,y.Type.OID,!1,y.oidToDer(v.oids.rsaEncryption).getBytes()),y.create(y.Class.UNIVERSAL,y.Type.NULL,!1,"")]),y.create(y.Class.UNIVERSAL,y.Type.OCTETSTRING,!1,y.toDer(e).getBytes())])},v.privateKeyFromAsn1=function(e){var t={},r=[];if(y.validate(e,C,t,r)&&(e=y.fromDer(f.util.createBuffer(t.privateKey))),t={},r=[],!y.validate(e,E,t,r)){var n=new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw n.errors=r,n}var a,i,s,o,c,u,l,p;return a=f.util.createBuffer(t.privateKeyModulus).toHex(),i=f.util.createBuffer(t.privateKeyPublicExponent).toHex(),s=f.util.createBuffer(t.privateKeyPrivateExponent).toHex(),o=f.util.createBuffer(t.privateKeyPrime1).toHex(),c=f.util.createBuffer(t.privateKeyPrime2).toHex(),u=f.util.createBuffer(t.privateKeyExponent1).toHex(),l=f.util.createBuffer(t.privateKeyExponent2).toHex(),p=f.util.createBuffer(t.privateKeyCoefficient).toHex(),v.setRsaPrivateKey(new h(a,16),new h(i,16),new h(s,16),new h(o,16),new h(c,16),new h(u,16),new h(l,16),new h(p,16))},v.privateKeyToAsn1=v.privateKeyToRSAPrivateKey=function(e){return y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,y.integerToDer(0).getBytes()),y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,s(e.n)),y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,s(e.e)),y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,s(e.d)),y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,s(e.p)),y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,s(e.q)),y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,s(e.dP)),y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,s(e.dQ)),y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,s(e.qInv))])},v.publicKeyFromAsn1=function(e){var t={},r=[];if(y.validate(e,T,t,r)){var n=y.derToOid(t.publicKeyOid);if(n!==v.oids.rsaEncryption){var a=new Error("Cannot read public key. Unknown OID.");throw a.oid=n,a}e=t.rsaPublicKey}if(r=[],!y.validate(e,S,t,r)){var a=new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.");throw a.errors=r,a}var i=f.util.createBuffer(t.publicKeyModulus).toHex(),s=f.util.createBuffer(t.publicKeyExponent).toHex();return v.setRsaPublicKey(new h(i,16),new h(s,16))},v.publicKeyToAsn1=v.publicKeyToSubjectPublicKeyInfo=function(e){return y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[y.create(y.Class.UNIVERSAL,y.Type.OID,!1,y.oidToDer(v.oids.rsaEncryption).getBytes()),y.create(y.Class.UNIVERSAL,y.Type.NULL,!1,"")]),y.create(y.Class.UNIVERSAL,y.Type.BITSTRING,!1,[v.publicKeyToRSAPublicKey(e)])])},v.publicKeyToRSAPublicKey=function(e){return y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,s(e.n)),y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,s(e.e))])}},function(e,t,r){function n(e,t,r){this.data=[],null!=e&&("number"==typeof e?this.fromNumber(e,t,r):null==t&&"string"!=typeof e?this.fromString(e,256):this.fromString(e,t))}function a(){return new n(null)}function i(e,t,r,n,a,i){for(;--i>=0;){var s=t*this.data[e++]+r.data[n]+a;a=Math.floor(s/67108864),r.data[n++]=67108863&s}return a}function s(e,t,r,n,a,i){for(var s=32767&t,o=t>>15;--i>=0;){var c=32767&this.data[e],u=this.data[e++]>>15,l=o*c+u*s;c=s*c+((32767&l)<<15)+r.data[n]+(1073741823&a),a=(c>>>30)+(l>>>15)+o*u+(a>>>30),r.data[n++]=1073741823&c}return a}function o(e,t,r,n,a,i){for(var s=16383&t,o=t>>14;--i>=0;){var c=16383&this.data[e],u=this.data[e++]>>14,l=o*c+u*s;c=s*c+((16383&l)<<14)+r.data[n]+a,a=(c>>28)+(l>>14)+o*u,r.data[n++]=268435455&c}return a}function c(e){return it.charAt(e)}function u(e,t){var r=st[e.charCodeAt(t)];return null==r?-1:r}function l(e){for(var t=this.t-1;t>=0;--t)e.data[t]=this.data[t];e.t=this.t,e.s=this.s}function p(e){this.t=1,this.s=e<0?-1:0,e>0?this.data[0]=e:e<-1?this.data[0]=e+this.DV:this.t=0}function f(e){var t=a();return t.fromInt(e),t}function h(e,t){var r;if(16==t)r=4;else if(8==t)r=3;else if(256==t)r=8;else if(2==t)r=1;else if(32==t)r=5;else{if(4!=t)return void this.fromRadix(e,t);r=2}this.t=0,this.s=0;for(var a=e.length,i=!1,s=0;--a>=0;){var o=8==r?255&e[a]:u(e,a);o<0?"-"==e.charAt(a)&&(i=!0):(i=!1,0==s?this.data[this.t++]=o:s+r>this.DB?(this.data[this.t-1]|=(o&(1<>this.DB-s):this.data[this.t-1]|=o<=this.DB&&(s-=this.DB))}8==r&&0!=(128&e[0])&&(this.s=-1,s>0&&(this.data[this.t-1]|=(1<0&&this.data[this.t-1]==e;)--this.t}function y(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(16==e)t=4;else if(8==e)t=3;else if(2==e)t=1;else if(32==e)t=5;else{if(4!=e)return this.toRadix(e);t=2}var r,n=(1<0)for(o>o)>0&&(a=!0,i=c(r));s>=0;)o>(o+=this.DB-t)):(r=this.data[s]>>(o-=t)&n,o<=0&&(o+=this.DB,--s)),r>0&&(a=!0),a&&(i+=c(r));return a?i:"0"}function g(){var e=a();return n.ZERO.subTo(this,e),e}function v(){return this.s<0?this.negate():this}function m(e){var t=this.s-e.s;if(0!=t)return t;var r=this.t;if(0!=(t=r-e.t))return this.s<0?-t:t;for(;--r>=0;)if(0!=(t=this.data[r]-e.data[r]))return t;return 0}function C(e){var t,r=1;return 0!=(t=e>>>16)&&(e=t,r+=16),0!=(t=e>>8)&&(e=t,r+=8),0!=(t=e>>4)&&(e=t,r+=4),0!=(t=e>>2)&&(e=t,r+=2),0!=(t=e>>1)&&(e=t,r+=1),r}function E(){return this.t<=0?0:this.DB*(this.t-1)+C(this.data[this.t-1]^this.s&this.DM)}function S(e,t){var r;for(r=this.t-1;r>=0;--r)t.data[r+e]=this.data[r];for(r=e-1;r>=0;--r)t.data[r]=0;t.t=this.t+e,t.s=this.s}function T(e,t){for(var r=e;r=0;--r)t.data[r+s+1]=this.data[r]>>a|o,o=(this.data[r]&i)<=0;--r)t.data[r]=0;t.data[s]=o,t.t=this.t+s+1,t.s=this.s,t.clamp()}function I(e,t){t.s=this.s;var r=Math.floor(e/this.DB);if(r>=this.t)return void(t.t=0);var n=e%this.DB,a=this.DB-n,i=(1<>n;for(var s=r+1;s>n;n>0&&(t.data[this.t-r-1]|=(this.s&i)<>=this.DB;if(e.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=this.DB;n-=e.s}t.s=n<0?-1:0,n<-1?t.data[r++]=this.DV+n:n>0&&(t.data[r++]=n),t.t=r,t.clamp()}function B(e,t){var r=this.abs(),a=e.abs(),i=r.t;for(t.t=i+a.t;--i>=0;)t.data[i]=0;for(i=0;i=0;)e.data[r]=0;for(r=0;r=t.DV&&(e.data[r+t.t]-=t.DV,e.data[r+t.t+1]=1)}e.t>0&&(e.data[e.t-1]+=t.am(r,t.data[r],e,2*r,0,1)),e.s=0,e.clamp()}function N(e,t,r){var i=e.abs();if(!(i.t<=0)){var s=this.abs();if(s.t0?(i.lShiftTo(l,o),s.lShiftTo(l,r)):(i.copyTo(o),s.copyTo(r));var p=o.t,f=o.data[p-1];if(0!=f){var h=f*(1<1?o.data[p-2]>>this.F2:0),d=this.FV/h,y=(1<=0&&(r.data[r.t++]=1,r.subTo(E,r)),n.ONE.dlShiftTo(p,E),E.subTo(o,o);o.t=0;){var S=r.data[--v]==f?this.DM:Math.floor(r.data[v]*d+(r.data[v-1]+g)*y);if((r.data[v]+=o.am(0,S,r,m,0,p))0&&r.rShiftTo(l,r),c<0&&n.ZERO.subTo(r,r)}}}function w(e){var t=a();return this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(n.ZERO)>0&&e.subTo(t,t),t}function R(e){this.m=e}function L(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e}function _(e){return e}function U(e){e.divRemTo(this.m,null,e)}function D(e,t,r){e.multiplyTo(t,r),this.reduce(r)}function P(e,t){e.squareTo(t),this.reduce(t)}function O(){if(this.t<1)return 0;var e=this.data[0];if(0==(1&e))return 0;var t=3&e;return t=t*(2-(15&e)*t)&15,t=t*(2-(255&e)*t)&255,t=t*(2-((65535&e)*t&65535))&65535,t=t*(2-e*t%this.DV)%this.DV,t>0?this.DV-t:-t}function V(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<0&&this.m.subTo(t,t),t}function K(e){var t=a();return e.copyTo(t),this.reduce(t),t}function M(e){for(;e.t<=this.mt2;)e.data[e.t++]=0;for(var t=0;t>15)*this.mpl&this.um)<<15)&e.DM;for(r=t+this.m.t,e.data[r]+=this.m.am(0,n,e,t,0,this.m.t);e.data[r]>=e.DV;)e.data[r]-=e.DV,e.data[++r]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)}function F(e,t){e.squareTo(t),this.reduce(t)}function q(e,t,r){e.multiplyTo(t,r),this.reduce(r)}function H(){return 0==(this.t>0?1&this.data[0]:this.s)}function j(e,t){if(e>4294967295||e<1)return n.ONE;var r=a(),i=a(),s=t.convert(this),o=C(e)-1;for(s.copyTo(r);--o>=0;)if(t.sqrTo(r,i),(e&1<0)t.mulTo(i,s,r);else{var c=r;r=i,i=c}return t.revert(r)}function G(e,t){var r;return r=e<256||t.isEven()?new R(t):new V(t),this.exp(e,r)}function Q(){var e=a();return this.copyTo(e),e}function z(){if(this.s<0){if(1==this.t)return this.data[0]-this.DV;if(0==this.t)return-1}else{if(1==this.t)return this.data[0];if(0==this.t)return 0}return(this.data[1]&(1<<32-this.DB)-1)<>24}function X(){return 0==this.t?this.s:this.data[0]<<16>>16}function Y(e){return Math.floor(Math.LN2*this.DB/Math.log(e))}function Z(){return this.s<0?-1:this.t<=0||1==this.t&&this.data[0]<=0?0:1}function J(e){if(null==e&&(e=10),0==this.signum()||e<2||e>36)return"0";var t=this.chunkSize(e),r=Math.pow(e,t),n=f(r),i=a(),s=a(),o="";for(this.divRemTo(n,i,s);i.signum()>0;)o=(r+s.intValue()).toString(e).substr(1)+o,i.divRemTo(n,i,s);return s.intValue().toString(e)+o}function $(e,t){this.fromInt(0),null==t&&(t=10);for(var r=this.chunkSize(t),a=Math.pow(t,r),i=!1,s=0,o=0,c=0;c=r&&(this.dMultiply(a),this.dAddOffset(o,0),s=0,o=0))}s>0&&(this.dMultiply(Math.pow(t,s)),this.dAddOffset(o,0)),i&&n.ZERO.subTo(this,this)}function ee(e,t,r){if("number"==typeof t)if(e<2)this.fromInt(1);else for(this.fromNumber(e,r),this.testBit(e-1)||this.bitwiseTo(n.ONE.shiftLeft(e-1),ce,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(t);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(n.ONE.shiftLeft(e-1),this);else{var a=new Array,i=7&e;a.length=1+(e>>3),t.nextBytes(a),i>0?a[0]&=(1<0)for(n>n)!=(this.s&this.DM)>>n&&(t[a++]=r|this.s<=0;)n<8?(r=(this.data[e]&(1<>(n+=this.DB-8)):(r=this.data[e]>>(n-=8)&255,n<=0&&(n+=this.DB,--e)),0!=(128&r)&&(r|=-256),0==a&&(128&this.s)!=(128&r)&&++a,(a>0||r!=this.s)&&(t[a++]=r);return t}function re(e){return 0==this.compareTo(e)}function ne(e){return this.compareTo(e)<0?this:e}function ae(e){return this.compareTo(e)>0?this:e}function ie(e,t,r){var n,a,i=Math.min(e.t,this.t);for(n=0;n>=16,t+=16),0==(255&e)&&(e>>=8,t+=8),0==(15&e)&&(e>>=4,t+=4),0==(3&e)&&(e>>=2,t+=2),0==(1&e)&&++t,t}function me(){for(var e=0;e=this.t?0!=this.s:0!=(this.data[t]&1<>=this.DB;if(e.t>=this.DB;n+=this.s}else{for(n+=this.s;r>=this.DB;n+=e.s}t.s=n<0?-1:0,n>0?t.data[r++]=n:n<-1&&(t.data[r++]=this.DV+n),t.t=r,t.clamp()}function ke(e){var t=a();return this.addTo(e,t),t}function Ne(e){var t=a();return this.subTo(e,t),t}function we(e){var t=a();return this.multiplyTo(e,t),t}function Re(e){var t=a();return this.divRemTo(e,t,null),t}function Le(e){var t=a();return this.divRemTo(e,null,t),t}function _e(e){var t=a(),r=a();return this.divRemTo(e,t,r),new Array(t,r)}function Ue(e){this.data[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()}function De(e,t){if(0!=e){for(;this.t<=t;)this.data[this.t++]=0;for(this.data[t]+=e;this.data[t]>=this.DV;)this.data[t]-=this.DV,++t>=this.t&&(this.data[this.t++]=0),++this.data[t]}}function Pe(){}function Oe(e){return e}function Ve(e,t,r){e.multiplyTo(t,r)}function xe(e,t){e.squareTo(t)}function Ke(e){return this.exp(e,new Pe)}function Me(e,t,r){var n=Math.min(this.t+e.t,t);for(r.s=0,r.t=n;n>0;)r.data[--n]=0;var a;for(a=r.t-this.t;n=0;)r.data[n]=0;for(n=Math.max(t-this.t,0);n2*this.m.t)return e.mod(this.m);if(e.compareTo(this.m)<0)return e;var t=a();return e.copyTo(t),this.reduce(t),t}function je(e){return e}function Ge(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)}function Qe(e,t){e.squareTo(t),this.reduce(t)}function ze(e,t,r){e.multiplyTo(t,r),this.reduce(r)}function We(e,t){var r,n,i=e.bitLength(),s=f(1);if(i<=0)return s;r=i<18?1:i<48?3:i<144?4:i<768?5:6,n=i<8?new R(t):t.isEven()?new qe(t):new V(t);var o=new Array,c=3,u=r-1,l=(1<1){var p=a();for(n.sqrTo(o[1],p);c<=l;)o[c]=a(),n.mulTo(p,o[c-2],o[c]),c+=2}var h,d,y=e.t-1,g=!0,v=a();for(i=C(e.data[y])-1;y>=0;){for(i>=u?h=e.data[y]>>i-u&l:(h=(e.data[y]&(1<0&&(h|=e.data[y-1]>>this.DB+i-u)),c=r;0==(1&h);)h>>=1,--c;if((i-=c)<0&&(i+=this.DB,--y),g)o[h].copyTo(s),g=!1;else{for(;c>1;)n.sqrTo(s,v),n.sqrTo(v,s),c-=2;c>0?n.sqrTo(s,v):(d=s,s=v,v=d),n.mulTo(v,o[h],s)}for(;y>=0&&0==(e.data[y]&1<0&&(t.rShiftTo(i,t),r.rShiftTo(i,r));t.signum()>0;)(a=t.getLowestSetBit())>0&&t.rShiftTo(a,t),(a=r.getLowestSetBit())>0&&r.rShiftTo(a,r),t.compareTo(r)>=0?(t.subTo(r,t),t.rShiftTo(1,t)):(r.subTo(t,r),r.rShiftTo(1,r));return i>0&&r.lShiftTo(i,r),r}function Ye(e){if(e<=0)return 0;var t=this.DV%e,r=this.s<0?e-1:0;if(this.t>0)if(0==t)r=this.data[0]%e;else for(var n=this.t-1;n>=0;--n)r=(t*r+this.data[n])%e;return r}function Ze(e){var t=e.isEven();if(this.isEven()&&t||0==e.signum())return n.ZERO;for(var r=e.clone(),a=this.clone(),i=f(1),s=f(0),o=f(0),c=f(1);0!=r.signum();){for(;r.isEven();)r.rShiftTo(1,r),t?(i.isEven()&&s.isEven()||(i.addTo(this,i),s.subTo(e,s)),i.rShiftTo(1,i)):s.isEven()||s.subTo(e,s),s.rShiftTo(1,s);for(;a.isEven();)a.rShiftTo(1,a),t?(o.isEven()&&c.isEven()||(o.addTo(this,o),c.subTo(e,c)),o.rShiftTo(1,o)):c.isEven()||c.subTo(e,c),c.rShiftTo(1,c);r.compareTo(a)>=0?(r.subTo(a,r),t&&i.subTo(o,i),s.subTo(c,s)):(a.subTo(r,a),t&&o.subTo(i,o),c.subTo(s,c))}return 0!=a.compareTo(n.ONE)?n.ZERO:c.compareTo(e)>=0?c.subtract(e):c.signum()<0?(c.addTo(e,c),c.signum()<0?c.add(e):c):c}function Je(e){var t,r=this.abs();if(1==r.t&&r.data[0]<=ot[ot.length-1]){for(t=0;t=0);var c=a.modPow(i,this);if(0!=c.compareTo(n.ONE)&&0!=c.compareTo(t)){for(var u=1;u++=64;){for(a=e.h0,i=e.h1,s=e.h2,o=e.h3,h=0;h<16;++h)t[h]=r.getInt32Le(),p=o^i&(s^o),n=a+p+l[h]+t[h],f=u[h],a=o,o=s,s=i,i+=n<>>32-f;for(;h<32;++h)p=s^o&(i^s),n=a+p+l[h]+t[c[h]],f=u[h],a=o,o=s,s=i,i+=n<>>32-f;for(;h<48;++h)p=i^s^o,n=a+p+l[h]+t[c[h]],f=u[h],a=o,o=s,s=i,i+=n<>>32-f;for(;h<64;++h)p=s^(i|~o),n=a+p+l[h]+t[c[h]],f=u[h],a=o,o=s,s=i,i+=n<>>32-f;e.h0=e.h0+a|0,e.h1=e.h1+i|0,e.h2=e.h2+s|0,e.h3=e.h3+o|0,d-=64}}var i=r(0);r(4),r(1);var s=e.exports=i.md5=i.md5||{};i.md.md5=i.md.algorithms.md5=s,s.create=function(){p||n();var e=null,t=i.util.createBuffer(),r=new Array(16),s={algorithm:"md5",blockLength:64,digestLength:16,messageLength:0,fullMessageLength:null,messageLengthSize:8};return s.start=function(){s.messageLength=0,s.fullMessageLength=s.messageLength64=[];for(var r=s.messageLengthSize/4,n=0;n>>0,c>>>0];for(var u=s.fullMessageLength.length-1;u>=0;--u)s.fullMessageLength[u]+=c[1],c[1]=c[0]+(s.fullMessageLength[u]/4294967296>>>0),s.fullMessageLength[u]=s.fullMessageLength[u]>>>0,c[0]=c[1]/4294967296>>>0;return t.putBytes(n),a(e,r,t),(t.read>2048||0===t.length())&&t.compact(),s},s.digest=function(){var n=i.util.createBuffer();n.putBytes(t.bytes());var c=s.fullMessageLength[s.fullMessageLength.length-1]+s.messageLengthSize,u=c&s.blockLength-1;n.putBytes(o.substr(0,s.blockLength-u));for(var l,p=0,f=s.fullMessageLength.length-1;f>=0;--f)l=8*s.fullMessageLength[f]+p,p=l/4294967296>>>0,n.putInt32Le(l>>>0);var h={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3};a(h,r,n);var d=i.util.createBuffer();return d.putInt32Le(h.h0),d.putInt32Le(h.h1),d.putInt32Le(h.h2),d.putInt32Le(h.h3),d},s};var o=null,c=null,u=null,l=null,p=!1},function(e,t,r){var n=r(0);r(8),r(4),r(1);var a,i=n.pkcs5=n.pkcs5||{};n.util.isNodejs&&!n.options.usePureJavaScript&&(a=r(17)),e.exports=n.pbkdf2=i.pbkdf2=function(e,t,r,i,s,o){function c(){if(C>f)return o(null,m);d.start(null,null),d.update(t),d.update(n.util.int32ToBytes(C)),y=v=d.digest().getBytes(),E=2,u()}function u(){if(E<=r)return d.start(null,null),d.update(v),g=d.digest().getBytes(),y=n.util.xorBytes(y,g,l),v=g,++E,n.util.setImmediate(u);m+=C4||!s||"sha1"===s))return"string"!=typeof s&&(s="sha1"),e=Buffer.from(e,"binary"),t=Buffer.from(t,"binary"),o?4===a.pbkdf2Sync.length?a.pbkdf2(e,t,r,i,function(e,t){if(e)return o(e);o(null,t.toString("binary"))}):a.pbkdf2(e,t,r,i,s,function(e,t){if(e)return o(e);o(null,t.toString("binary"))}):4===a.pbkdf2Sync.length?a.pbkdf2Sync(e,t,r,i).toString("binary"):a.pbkdf2Sync(e,t,r,i,s).toString("binary");if(void 0!==s&&null!==s||(s="sha1"),"string"==typeof s){if(!(s in n.md.algorithms))throw new Error("Unknown hash algorithm: "+s);s=n.md[s].create()}var l=s.digestLength;if(i>4294967295*l){var p=new Error("Derived key is too long.");if(o)return o(p);throw p}var f=Math.ceil(i/l),h=i-(f-1)*l,d=n.hmac.create();d.start(s,e);var y,g,v,m="";if(!o){for(var C=1;C<=f;++C){d.start(null,null),d.update(t),d.update(n.util.int32ToBytes(C)),y=v=d.digest().getBytes();for(var E=2;E<=r;++E)d.start(null,null),d.update(v),g=d.digest().getBytes(),y=n.util.xorBytes(y,g,l),v=g;m+=C128)throw new Error('Invalid "nsComment" content.');e.value=p.create(p.Class.UNIVERSAL,p.Type.IA5STRING,!1,e.comment)}else if("subjectKeyIdentifier"===e.name&&t.cert){var g=t.cert.generateSubjectKeyIdentifier();e.subjectKeyIdentifier=g.toHex(),e.value=p.create(p.Class.UNIVERSAL,p.Type.OCTETSTRING,!1,g.getBytes())}else if("authorityKeyIdentifier"===e.name&&t.cert){e.value=p.create(p.Class.UNIVERSAL,p.Type.SEQUENCE,!0,[]);var c=e.value.value;if(e.keyIdentifier){var v=!0===e.keyIdentifier?t.cert.generateSubjectKeyIdentifier().getBytes():e.keyIdentifier;c.push(p.create(p.Class.CONTEXT_SPECIFIC,0,!1,v))}if(e.authorityCertIssuer){var m=[p.create(p.Class.CONTEXT_SPECIFIC,4,!0,[a(!0===e.authorityCertIssuer?t.cert.issuer:e.authorityCertIssuer)])];c.push(p.create(p.Class.CONTEXT_SPECIFIC,1,!0,m))}if(e.serialNumber){var C=l.util.hexToBytes(!0===e.serialNumber?t.cert.serialNumber:e.serialNumber);c.push(p.create(p.Class.CONTEXT_SPECIFIC,2,!1,C))}}else if("cRLDistributionPoints"===e.name){e.value=p.create(p.Class.UNIVERSAL,p.Type.SEQUENCE,!0,[]);for(var d,c=e.value.value,E=p.create(p.Class.UNIVERSAL,p.Type.SEQUENCE,!0,[]),S=p.create(p.Class.CONTEXT_SPECIFIC,0,!0,[]),y=0;y=S&&e2)throw new Error("Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate.");if(d.length<2)throw new Error("Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime.");if(c.validity.notBefore=d[0],c.validity.notAfter=d[1],c.tbsCertificate=r.tbsCertificate,t){if(c.md=null,c.signatureOid in h){var o=h[c.signatureOid];switch(o){case"sha1WithRSAEncryption":c.md=l.md.sha1.create();break;case"md5WithRSAEncryption":c.md=l.md.md5.create();break;case"sha256WithRSAEncryption":c.md=l.md.sha256.create();break;case"sha384WithRSAEncryption":c.md=l.md.sha384.create();break;case"sha512WithRSAEncryption":c.md=l.md.sha512.create();break;case"RSASSA-PSS":c.md=l.md.sha256.create()}}if(null===c.md){var s=new Error("Could not compute certificate digest. Unknown signature OID.");throw s.signatureOid=c.signatureOid,s}var y=p.toDer(c.tbsCertificate);c.md.update(y.getBytes())}var v=l.md.sha1.create();c.issuer.getField=function(e){return n(c.issuer,e)},c.issuer.addField=function(e){i([e]),c.issuer.attributes.push(e)},c.issuer.attributes=f.RDNAttributesAsArray(r.certIssuer,v),r.certIssuerUniqueId&&(c.issuer.uniqueId=r.certIssuerUniqueId),c.issuer.hash=v.digest().toHex();var m=l.md.sha1.create();return c.subject.getField=function(e){return n(c.subject,e)},c.subject.addField=function(e){i([e]),c.subject.attributes.push(e)},c.subject.attributes=f.RDNAttributesAsArray(r.certSubject,m),r.certSubjectUniqueId&&(c.subject.uniqueId=r.certSubjectUniqueId),c.subject.hash=m.digest().toHex(),r.certExtensions?c.extensions=f.certificateExtensionsFromAsn1(r.certExtensions):c.extensions=[],c.publicKey=f.publicKeyFromAsn1(r.subjectPublicKeyInfo),c},f.certificateExtensionsFromAsn1=function(e){for(var t=[],r=0;r1&&(n=r.value.charCodeAt(1),a=r.value.length>2?r.value.charCodeAt(2):0),t.digitalSignature=128==(128&n),t.nonRepudiation=64==(64&n),t.keyEncipherment=32==(32&n),t.dataEncipherment=16==(16&n),t.keyAgreement=8==(8&n),t.keyCertSign=4==(4&n),t.cRLSign=2==(2&n),t.encipherOnly=1==(1&n),t.decipherOnly=128==(128&a)}else if("basicConstraints"===t.name){var r=p.fromDer(t.value);r.value.length>0&&r.value[0].type===p.Type.BOOLEAN?t.cA=0!==r.value[0].value.charCodeAt(0):t.cA=!1;var i=null;r.value.length>0&&r.value[0].type===p.Type.INTEGER?i=r.value[0].value:r.value.length>1&&(i=r.value[1].value),null!==i&&(t.pathLenConstraint=p.derToInteger(i))}else if("extKeyUsage"===t.name)for(var r=p.fromDer(t.value),s=0;s1&&(n=r.value.charCodeAt(1)),t.client=128==(128&n),t.server=64==(64&n),t.email=32==(32&n),t.objsign=16==(16&n),t.reserved=8==(8&n),t.sslCA=4==(4&n),t.emailCA=2==(2&n),t.objCA=1==(1&n)}else if("subjectAltName"===t.name||"issuerAltName"===t.name){t.altNames=[];for(var c,r=p.fromDer(t.value),u=0;u0&&n.value.push(f.certificateExtensionsToAsn1(e.extensions)),n},f.getCertificationRequestInfo=function(e){return p.create(p.Class.UNIVERSAL,p.Type.SEQUENCE,!0,[p.create(p.Class.UNIVERSAL,p.Type.INTEGER,!1,p.integerToDer(e.version).getBytes()),a(e.subject),f.publicKeyToAsn1(e.publicKey),c(e)])},f.distinguishedNameToAsn1=function(e){return a(e)},f.certificateToAsn1=function(e){var t=e.tbsCertificate||f.getTBSCertificate(e);return p.create(p.Class.UNIVERSAL,p.Type.SEQUENCE,!0,[t,p.create(p.Class.UNIVERSAL,p.Type.SEQUENCE,!0,[p.create(p.Class.UNIVERSAL,p.Type.OID,!1,p.oidToDer(e.signatureOid).getBytes()),o(e.signatureOid,e.signatureParameters)]),p.create(p.Class.UNIVERSAL,p.Type.BITSTRING,!1,String.fromCharCode(0)+e.signature)])},f.certificateExtensionsToAsn1=function(e){var t=p.create(p.Class.CONTEXT_SPECIFIC,3,!0,[]),r=p.create(p.Class.UNIVERSAL,p.Type.SEQUENCE,!0,[]);t.value.push(r);for(var n=0;nc.validity.notAfter)&&(s={message:"Certificate is not valid yet or has expired.",error:f.certificateError.certificate_expired,notBefore:c.validity.notBefore,notAfter:c.validity.notAfter,now:a}),null===s){if(u=t[0]||e.getIssuer(c),null===u&&c.isIssuer(c)&&(p=!0,u=c),u){var h=u;l.util.isArray(h)||(h=[h]);for(var d=!1;!d&&h.length>0;){u=h.shift();try{d=u.verify(c)}catch(e){}}d||(s={message:"Certificate signature is invalid.",error:f.certificateError.bad_certificate})}null!==s||u&&!p||e.hasCertificate(c)||(s={message:"Certificate is not trusted.",error:f.certificateError.unknown_ca})}if(null===s&&u&&!c.isIssuer(u)&&(s={message:"Certificate issuer is invalid.",error:f.certificateError.bad_certificate}),null===s)for(var y={keyUsage:!0,basicConstraints:!0},g=0;null===s&&gm.pathLenConstraint&&(s={message:"Certificate basicConstraints pathLenConstraint violated.",error:f.certificateError.bad_certificate})}}var E=null===s||s.error,S=r.verify?r.verify(E,o,n):E;if(!0!==S)throw!0===E&&(s={message:"The application rejected the certificate.",error:f.certificateError.bad_certificate}),(S||0===S)&&("object"!=typeof S||l.util.isArray(S)?"string"==typeof S&&(s.error=S):(S.message&&(s.message=S.message),S.error&&(s.error=S.error))),s;s=null,i=!1,++o}while(t.length>0);return!0}},function(e,t,r){var n=r(0);r(2),r(1),(e.exports=n.pss=n.pss||{}).create=function(e){3===arguments.length&&(e={md:arguments[0],mgf:arguments[1],saltLength:arguments[2]});var t=e.md,r=e.mgf,a=t.digestLength,i=e.salt||null;"string"==typeof i&&(i=n.util.createBuffer(i));var s;if("saltLength"in e)s=e.saltLength;else{if(null===i)throw new Error("Salt length not specified or specific salt not given.");s=i.length()}if(null!==i&&i.length()!==s)throw new Error("Given salt length does not match length of given salt.");var o=e.prng||n.random,c={};return c.encode=function(e,c){var u,l=c-1,p=Math.ceil(l/8),f=e.digest().getBytes();if(p>8*p-l&255;return(E=String.fromCharCode(E.charCodeAt(0)&~S)+E.substr(1))+y+String.fromCharCode(188)},c.verify=function(e,i,o){var c,u=o-1,l=Math.ceil(u/8);if(i=i.substr(-l),l>8*l-u&255;if(0!=(f.charCodeAt(0)&d))throw new Error("Bits beyond keysize not zero as expected.");var y=r.generate(h,p),g="";for(c=0;c4){var r=e;e=s.util.createBuffer();for(var n=0;n0))return!0;for(var n=0;n0))return!0;for(var n=0;n0)return!1;var r=e.length(),n=e.at(r-1);return!(n>this.blockSize<<2)&&(e.truncate(n),!0)},o.cbc=function(e){e=e||{},this.name="CBC",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)},o.cbc.prototype.start=function(e){if(null===e.iv){if(!this._prev)throw new Error("Invalid IV parameter.");this._iv=this._prev.slice(0)}else{if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=n(e.iv,this.blockSize),this._prev=this._iv.slice(0)}},o.cbc.prototype.encrypt=function(e,t,r){if(e.length()0))return!0;for(var n=0;n0))return!0;for(var n=0;n0)return!1;var r=e.length(),n=e.at(r-1);return!(n>this.blockSize<<2)&&(e.truncate(n),!0)},o.cfb=function(e){e=e||{},this.name="CFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialBlock=new Array(this._ints),this._partialOutput=s.util.createBuffer(),this._partialBytes=0},o.cfb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=n(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},o.cfb.prototype.encrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize)for(var a=0;a0&&(i=this.blockSize-i),this._partialOutput.clear();for(var a=0;a0)e.read-=this.blockSize;else for(var a=0;a0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}},o.cfb.prototype.decrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize)for(var a=0;a0&&(i=this.blockSize-i),this._partialOutput.clear();for(var a=0;a0)e.read-=this.blockSize;else for(var a=0;a0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}},o.ofb=function(e){e=e||{},this.name="OFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=s.util.createBuffer(),this._partialBytes=0},o.ofb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=n(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},o.ofb.prototype.encrypt=function(e,t,r){var n=e.length();if(0===e.length())return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize)for(var a=0;a0&&(i=this.blockSize-i),this._partialOutput.clear();for(var a=0;a0)e.read-=this.blockSize;else for(var a=0;a0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}},o.ofb.prototype.decrypt=o.ofb.prototype.encrypt,o.ctr=function(e){e=e||{},this.name="CTR",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=s.util.createBuffer(),this._partialBytes=0},o.ctr.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=n(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},o.ctr.prototype.encrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize)for(var i=0;i0&&(s=this.blockSize-s),this._partialOutput.clear();for(var i=0;i0&&(e.read-=this.blockSize),this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!r)return t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}a(this._inBlock)},o.ctr.prototype.decrypt=o.ctr.prototype.encrypt,o.gcm=function(e){e=e||{},this.name="GCM",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints),this._partialOutput=s.util.createBuffer(),this._partialBytes=0,this._R=3774873600},o.gcm.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");var t=s.util.createBuffer(e.iv);this._cipherLength=0;var r;if(r="additionalData"in e?s.util.createBuffer(e.additionalData):s.util.createBuffer(),this._tagLength="tagLength"in e?e.tagLength:128,this._tag=null,e.decrypt&&(this._tag=s.util.createBuffer(e.tag).getBytes(),this._tag.length!==this._tagLength/8))throw new Error("Authentication tag does not match tag length.");this._hashBlock=new Array(this._ints),this.tag=null,this._hashSubkey=new Array(this._ints),this.cipher.encrypt([0,0,0,0],this._hashSubkey),this.componentBits=4,this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var n=t.length();if(12===n)this._j0=[t.getInt32(),t.getInt32(),t.getInt32(),1];else{for(this._j0=[0,0,0,0];t.length()>0;)this._j0=this.ghash(this._hashSubkey,this._j0,[t.getInt32(),t.getInt32(),t.getInt32(),t.getInt32()]);this._j0=this.ghash(this._hashSubkey,this._j0,[0,0].concat(i(8*n)))}this._inBlock=this._j0.slice(0),a(this._inBlock),this._partialBytes=0,r=s.util.createBuffer(r),this._aDataLength=i(8*r.length());var o=r.length()%this.blockSize;for(o&&r.fillWithByte(0,this.blockSize-o),this._s=[0,0,0,0];r.length()>0;)this._s=this.ghash(this._hashSubkey,this._s,[r.getInt32(),r.getInt32(),r.getInt32(),r.getInt32()])},o.gcm.prototype.encrypt=function(e,t,r){var n=e.length();if(0===n)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&n>=this.blockSize){for(var i=0;i0&&(s=this.blockSize-s),this._partialOutput.clear();for(var i=0;i0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!r)return e.read-=this.blockSize,t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(n-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),a(this._inBlock)},o.gcm.prototype.decrypt=function(e,t,r){var n=e.length();if(n0))return!0;this.cipher.encrypt(this._inBlock,this._outBlock),a(this._inBlock),this._hashBlock[0]=e.getInt32(),this._hashBlock[1]=e.getInt32(),this._hashBlock[2]=e.getInt32(),this._hashBlock[3]=e.getInt32(),this._s=this.ghash(this._hashSubkey,this._s,this._hashBlock);for(var i=0;i0;--n)t[n]=e[n]>>>1|(1&e[n-1])<<31;t[0]=e[0]>>>1,r&&(t[0]^=this._R)},o.gcm.prototype.tableMultiply=function(e){for(var t=[0,0,0,0],r=0;r<32;++r){var n=r/8|0,a=e[n]>>>4*(7-r%8)&15,i=this._m[r][a];t[0]^=i[0],t[1]^=i[1],t[2]^=i[2],t[3]^=i[3]}return t},o.gcm.prototype.ghash=function(e,t,r){return t[0]^=r[0],t[1]^=r[1],t[2]^=r[2],t[3]^=r[3],this.tableMultiply(t)},o.gcm.prototype.generateHashTable=function(e,t){for(var r=8/t,n=4*r,a=16*r,i=new Array(a),s=0;s>>1,a=new Array(r);a[n]=e.slice(0);for(var i=n>>>1;i>0;)this.pow(a[2*i],a[i]=[]),i>>=1;for(i=2;i=0;c--)w>>=8,w+=A.at(c)+N.at(c),N.setAt(c,255&w);k.putBuffer(N)}E=k,p.putBuffer(b)}return p.truncate(p.length()-a),p},l.pbe.getCipher=function(e,t,r){switch(e){case l.oids.pkcs5PBES2:return l.pbe.getCipherForPBES2(e,t,r);case l.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case l.oids["pbewithSHAAnd40BitRC2-CBC"]:return l.pbe.getCipherForPKCS12PBE(e,t,r);default:var n=new Error("Cannot read encrypted PBE data block. Unsupported OID.");throw n.oid=e,n.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"],n}},l.pbe.getCipherForPBES2=function(e,t,r){var n={},i=[];if(!u.validate(t,h,n,i)){var s=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw s.errors=i,s}if((e=u.derToOid(n.kdfOid))!==l.oids.pkcs5PBKDF2){var s=new Error("Cannot read encrypted private key. Unsupported key derivation function OID.");throw s.oid=e,s.supportedOids=["pkcs5PBKDF2"],s}if((e=u.derToOid(n.encOid))!==l.oids["aes128-CBC"]&&e!==l.oids["aes192-CBC"]&&e!==l.oids["aes256-CBC"]&&e!==l.oids["des-EDE3-CBC"]&&e!==l.oids.desCBC){var s=new Error("Cannot read encrypted private key. Unsupported encryption scheme OID.");throw s.oid=e,s.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],s}var c=n.kdfSalt,p=o.util.createBuffer(n.kdfIterationCount);p=p.getInt(p.length()<<3);var f,d;switch(l.oids[e]){case"aes128-CBC":f=16,d=o.aes.createDecryptionCipher;break;case"aes192-CBC":f=24,d=o.aes.createDecryptionCipher;break;case"aes256-CBC":f=32,d=o.aes.createDecryptionCipher;break;case"des-EDE3-CBC":f=24,d=o.des.createDecryptionCipher;break;case"desCBC":f=8,d=o.des.createDecryptionCipher}var y=a(n.prfOid),g=o.pkcs5.pbkdf2(r,c,p,f,y),v=n.encIv,m=d(g);return m.start(v),m},l.pbe.getCipherForPKCS12PBE=function(e,t,r){var n={},i=[];if(!u.validate(t,d,n,i)){var s=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw s.errors=i,s}var c=o.util.createBuffer(n.salt),p=o.util.createBuffer(n.iterations);p=p.getInt(p.length()<<3);var f,h,y;switch(e){case l.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:f=24,h=8,y=o.des.startDecrypting;break;case l.oids["pbewithSHAAnd40BitRC2-CBC"]:f=5,h=8,y=function(e,t){var r=o.rc2.createDecryptionCipher(e,40);return r.start(t,null),r};break;default:var s=new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.");throw s.oid=e,s}var g=a(n.prfOid),v=l.pbe.generatePkcs12Key(r,c,1,p,f,g);return g.start(),y(v,l.pbe.generatePkcs12Key(r,c,2,p,h,g))},l.pbe.opensslDeriveBytes=function(e,t,r,a){if(void 0===a||null===a){if(!("md5"in o.md))throw new Error('"md5" hash algorithm unavailable.');a=o.md.md5.create()}null===t&&(t="");for(var i=[n(a,e+t)],s=16,c=1;s=64;){for(l=0;l<16;++l)t[l]=r.getInt32();for(;l<64;++l)n=t[l-2],n=(n>>>17|n<<15)^(n>>>19|n<<13)^n>>>10,a=t[l-15],a=(a>>>7|a<<25)^(a>>>18|a<<14)^a>>>3,t[l]=n+t[l-7]+a+t[l-16]|0;for(p=e.h0,f=e.h1,h=e.h2,d=e.h3,y=e.h4,g=e.h5,v=e.h6,m=e.h7,l=0;l<64;++l)s=(y>>>6|y<<26)^(y>>>11|y<<21)^(y>>>25|y<<7),o=v^y&(g^v),i=(p>>>2|p<<30)^(p>>>13|p<<19)^(p>>>22|p<<10),c=p&f|h&(p^f),n=m+s+o+u[l]+t[l],a=i+c,m=v,v=g,g=y,y=d+n>>>0,d=h,h=f,f=p,p=n+a>>>0;e.h0=e.h0+p|0,e.h1=e.h1+f|0,e.h2=e.h2+h|0,e.h3=e.h3+d|0,e.h4=e.h4+y|0,e.h5=e.h5+g|0,e.h6=e.h6+v|0,e.h7=e.h7+m|0,C-=64}}var i=r(0);r(4),r(1);var s=e.exports=i.sha256=i.sha256||{};i.md.sha256=i.md.algorithms.sha256=s,s.create=function(){c||n();var e=null,t=i.util.createBuffer(),r=new Array(64),s={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8};return s.start=function(){s.messageLength=0,s.fullMessageLength=s.messageLength64=[];for(var r=s.messageLengthSize/4,n=0;n>>0,c>>>0];for(var u=s.fullMessageLength.length-1;u>=0;--u)s.fullMessageLength[u]+=c[1],c[1]=c[0]+(s.fullMessageLength[u]/4294967296>>>0),s.fullMessageLength[u]=s.fullMessageLength[u]>>>0,c[0]=c[1]/4294967296>>>0;return t.putBytes(n),a(e,r,t),(t.read>2048||0===t.length())&&t.compact(),s},s.digest=function(){var n=i.util.createBuffer();n.putBytes(t.bytes());var c=s.fullMessageLength[s.fullMessageLength.length-1]+s.messageLengthSize,u=c&s.blockLength-1;n.putBytes(o.substr(0,s.blockLength-u));for(var l,p,f=8*s.fullMessageLength[0],h=0;h>>0,f+=p,n.putInt32(f>>>0),f=l>>>0;n.putInt32(f);var d={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4,h5:e.h5,h6:e.h6,h7:e.h7};a(d,r,n);var y=i.util.createBuffer();return y.putInt32(d.h0),y.putInt32(d.h1),y.putInt32(d.h2),y.putInt32(d.h3),y.putInt32(d.h4),y.putInt32(d.h5),y.putInt32(d.h6),y.putInt32(d.h7),y},s};var o=null,c=!1,u=null},function(e,t,r){var n=r(0);r(1);var a=null;!n.util.isNodejs||n.options.usePureJavaScript||process.versions["node-webkit"]||(a=r(17)),(e.exports=n.prng=n.prng||{}).create=function(e){function t(e){if(o.pools[0].messageLength>=32)return i(),e();var t=32-o.pools[0].messageLength<<5;o.seedFile(t,function(t,r){if(t)return e(t);o.collect(r),i(),e()})}function r(){if(o.pools[0].messageLength>=32)return i();var e=32-o.pools[0].messageLength<<5;o.collect(o.seedFileSync(e)),i()}function i(){o.reseeds=4294967295===o.reseeds?0:o.reseeds+1;var e=o.plugin.md.create();e.update(o.keyBytes);for(var t=1,r=0;r<32;++r)o.reseeds%t==0&&(e.update(o.pools[r].digest().getBytes()),o.pools[r].start()),t<<=1;o.keyBytes=e.digest().getBytes(),e.start(),e.update(o.keyBytes);var n=e.digest().getBytes();o.key=o.plugin.formatKey(o.keyBytes),o.seed=o.plugin.formatSeed(n),o.generated=0}function s(e){var t=null,r=n.util.globalScope,a=r.crypto||r.msCrypto;a&&a.getRandomValues&&(t=function(e){return a.getRandomValues(e)});var i=n.util.createBuffer();if(t)for(;i.length()>16),l+=(32767&u)<<16,l+=u>>15,l=(2147483647&l)+(l>>31),f=4294967295&l;for(var c=0;c<3;++c)p=f>>>(c<<3),p^=Math.floor(256*Math.random()),i.putByte(String.fromCharCode(255&p))}return i.getBytes(e)}for(var o={plugin:e,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},c=e.md,u=new Array(32),l=0;l<32;++l)u[l]=c.create();return o.pools=u,o.pool=0,o.generate=function(e,r){function a(p){if(p)return r(p);if(l.length()>=e)return r(null,l.getBytes(e));if(o.generated>1048575&&(o.key=null),null===o.key)return n.util.nextTick(function(){t(a)});var f=i(o.key,o.seed);o.generated+=f.length,l.putBytes(f),o.key=c(i(o.key,s(o.seed))),o.seed=u(i(o.key,o.seed)),n.util.setImmediate(a)}if(!r)return o.generateSync(e);var i=o.plugin.cipher,s=o.plugin.increment,c=o.plugin.formatKey,u=o.plugin.formatSeed,l=n.util.createBuffer();o.key=null,a()},o.generateSync=function(e){var t=o.plugin.cipher,a=o.plugin.increment,i=o.plugin.formatKey,s=o.plugin.formatSeed;o.key=null;for(var c=n.util.createBuffer();c.length()1048575&&(o.key=null),null===o.key&&r();var u=t(o.key,o.seed);o.generated+=u.length,c.putBytes(u),o.key=i(t(o.key,a(o.seed))),o.seed=s(t(o.key,o.seed))}return c.getBytes(e)},a?(o.seedFile=function(e,t){a.randomBytes(e,function(e,r){if(e)return t(e);t(null,r.toString())})},o.seedFileSync=function(e){return a.randomBytes(e).toString()}):(o.seedFile=function(e,t){try{t(null,s(e))}catch(e){t(e)}},o.seedFileSync=s),o.collect=function(e){for(var t=e.length,r=0;r>n&255);o.collect(r)},o.registerWorker=function(e){if(e===self)o.seedFile=function(e,t){function r(e){var n=e.data;n.forge&&n.forge.prng&&(self.removeEventListener("message",r),t(n.forge.prng.err,n.forge.prng.bytes))}self.addEventListener("message",r),self.postMessage({forge:{prng:{needed:e}}})};else{var t=function(t){var r=t.data;r.forge&&r.forge.prng&&o.seedFile(r.forge.prng.needed,function(t,r){e.postMessage({forge:{prng:{err:t,bytes:r}}})})};e.addEventListener("message",t)}},o}},function(e,t,r){var n=r(0);r(1);var a=[217,120,249,196,25,221,181,237,40,233,253,121,74,160,216,157,198,126,55,131,43,118,83,142,98,76,100,136,68,139,251,162,23,154,89,245,135,179,79,19,97,69,109,141,9,129,125,50,189,143,64,235,134,183,123,11,240,149,33,34,92,107,78,130,84,214,101,147,206,96,178,28,115,86,192,20,167,140,241,220,18,117,202,31,59,190,228,209,66,61,212,48,163,60,182,38,111,191,14,218,70,105,7,87,39,242,29,155,188,148,67,3,248,17,199,246,144,239,62,231,6,195,213,47,200,102,30,215,8,232,234,222,128,82,238,247,132,170,114,172,53,77,106,42,150,26,210,113,90,21,73,116,75,159,208,94,4,24,164,236,194,224,65,110,15,81,203,204,36,145,175,80,161,244,112,57,153,124,58,133,35,184,180,122,252,2,54,91,37,85,151,49,45,93,250,152,227,138,146,174,5,223,41,16,103,108,186,201,211,0,230,207,225,158,168,44,99,22,1,63,88,226,137,169,13,56,52,27,171,51,255,176,187,72,12,95,185,177,205,46,197,243,219,71,229,165,156,119,10,166,32,104,254,127,193,173],i=[1,2,3,5],s=function(e,t){return e<>16-t},o=function(e,t){return(65535&e)>>t|e<<16-t&65535};e.exports=n.rc2=n.rc2||{},n.rc2.expandKey=function(e,t){"string"==typeof e&&(e=n.util.createBuffer(e)),t=t||128;var r,i=e,s=e.length(),o=t,c=Math.ceil(o/8),u=255>>(7&o);for(r=s;r<128;r++)i.putByte(a[i.at(r-1)+i.at(r-s)&255]);for(i.setAt(128-c,a[i.at(128-c)&u]),r=127-c;r>=0;r--)i.setAt(r,a[i.at(r+1)^i.at(r+c)]);return i};var c=function(e,t,r){var a,c,u,l,p=!1,f=null,h=null,d=null,y=[];for(e=n.rc2.expandKey(e,t),u=0;u<64;u++)y.push(e.getInt16Le());r?(a=function(e){for(u=0;u<4;u++)e[u]+=y[l]+(e[(u+3)%4]&e[(u+2)%4])+(~e[(u+3)%4]&e[(u+1)%4]),e[u]=s(e[u],i[u]),l++},c=function(e){for(u=0;u<4;u++)e[u]+=y[63&e[(u+3)%4]]}):(a=function(e){for(u=3;u>=0;u--)e[u]=o(e[u],i[u]),e[u]-=y[l]+(e[(u+3)%4]&e[(u+2)%4])+(~e[(u+3)%4]&e[(u+1)%4]),l--},c=function(e){for(u=3;u>=0;u--)e[u]-=y[63&e[(u+3)%4]]});var g=function(e){var t=[];for(u=0;u<4;u++){var n=f.getInt16Le();null!==d&&(r?n^=d.getInt16Le():d.putInt16Le(n)),t.push(65535&n)}l=r?0:63;for(var a=0;a=8;)g([[5,a],[1,c],[6,a],[1,c],[5,a]])},finish:function(e){var t=!0;if(r)if(e)t=e(8,f,!r);else{var n=8===f.length()?8:8-f.length();f.fillWithByte(n,n)}if(t&&(p=!0,v.update()),!r&&(t=0===f.length()))if(e)t=e(8,h,!r);else{var a=h.length(),i=h.at(a-1);i>a?t=!1:h.truncate(i)}return t}}};n.rc2.startEncrypting=function(e,t,r){var a=n.rc2.createEncryptionCipher(e,128);return a.start(t,r),a},n.rc2.createEncryptionCipher=function(e,t){return c(e,t,!0)},n.rc2.startDecrypting=function(e,t,r){var a=n.rc2.createDecryptionCipher(e,128);return a.start(t,r),a},n.rc2.createDecryptionCipher=function(e,t){return c(e,t,!1)}},function(e,t,r){function n(e,t,r){r||(r=a.md.sha1.create());for(var n="",i=Math.ceil(t/r.digestLength),s=0;s>24&255,s>>16&255,s>>8&255,255&s);r.start(),r.update(e+o),n+=r.digest().getBytes()}return n.substring(0,t)}var a=r(0);r(1),r(2),r(9);var i=e.exports=a.pkcs1=a.pkcs1||{};i.encode_rsa_oaep=function(e,t,r){var i,s,o,c;"string"==typeof r?(i=r,s=arguments[3]||void 0,o=arguments[4]||void 0):r&&(i=r.label||void 0,s=r.seed||void 0,o=r.md||void 0,r.mgf1&&r.mgf1.md&&(c=r.mgf1.md)),o?o.start():o=a.md.sha1.create(),c||(c=o);var u=Math.ceil(e.n.bitLength()/8),l=u-2*o.digestLength-2;if(t.length>l){var p=new Error("RSAES-OAEP input message length is too long.");throw p.length=t.length,p.maxLength=l,p}i||(i=""),o.update(i,"raw");for(var f=o.digest(),h="",d=l-t.length,y=0;yt&&(e=s(t,r)),e.isProbablePrime(o))return u(null,e);e.dAddOffset(l[i++%8],0)}while(c<0||+new Date-pe&&(c=s(e,t));var h=c.toString(16);r.target.postMessage({hex:h,workLoad:p}),c.dAddOffset(f,0)}}l=Math.max(1,l);for(var n=[],a=0;a=0&&a.push(o):a.push(o))}return a}function a(e){if(e.composed||e.constructed){for(var t=u.util.createBuffer(),r=0;r0&&(a=l.create(l.Class.UNIVERSAL,l.Type.SET,!0,c));var h=[],d=[];null!==t&&(d=u.util.isArray(t)?t:[t]);for(var y=[],g=0;g0){var E=l.create(l.Class.UNIVERSAL,l.Type.SEQUENCE,!0,y),S=l.create(l.Class.UNIVERSAL,l.Type.SEQUENCE,!0,[l.create(l.Class.UNIVERSAL,l.Type.OID,!1,l.oidToDer(p.oids.data).getBytes()),l.create(l.Class.CONTEXT_SPECIFIC,0,!0,[l.create(l.Class.UNIVERSAL,l.Type.OCTETSTRING,!1,l.toDer(E).getBytes())])]);h.push(S)}var T=null;if(null!==e){var b=p.wrapRsaPrivateKey(p.privateKeyToAsn1(e));T=null===r?l.create(l.Class.UNIVERSAL,l.Type.SEQUENCE,!0,[l.create(l.Class.UNIVERSAL,l.Type.OID,!1,l.oidToDer(p.oids.keyBag).getBytes()),l.create(l.Class.CONTEXT_SPECIFIC,0,!0,[b]),a]):l.create(l.Class.UNIVERSAL,l.Type.SEQUENCE,!0,[l.create(l.Class.UNIVERSAL,l.Type.OID,!1,l.oidToDer(p.oids.pkcs8ShroudedKeyBag).getBytes()),l.create(l.Class.CONTEXT_SPECIFIC,0,!0,[p.encryptPrivateKeyInfo(b,r,n)]),a]);var I=l.create(l.Class.UNIVERSAL,l.Type.SEQUENCE,!0,[T]),A=l.create(l.Class.UNIVERSAL,l.Type.SEQUENCE,!0,[l.create(l.Class.UNIVERSAL,l.Type.OID,!1,l.oidToDer(p.oids.data).getBytes()),l.create(l.Class.CONTEXT_SPECIFIC,0,!0,[l.create(l.Class.UNIVERSAL,l.Type.OCTETSTRING,!1,l.toDer(I).getBytes())])]);h.push(A)}var B,k=l.create(l.Class.UNIVERSAL,l.Type.SEQUENCE,!0,h);if(n.useMac){var o=u.md.sha1.create(),N=new u.util.ByteBuffer(u.random.getBytes(n.saltSize)),w=n.count,e=f.generateKey(r,N,3,w,20),R=u.hmac.create();R.start(o,e),R.update(l.toDer(k).getBytes());var L=R.getMac();B=l.create(l.Class.UNIVERSAL,l.Type.SEQUENCE,!0,[l.create(l.Class.UNIVERSAL,l.Type.SEQUENCE,!0,[l.create(l.Class.UNIVERSAL,l.Type.SEQUENCE,!0,[l.create(l.Class.UNIVERSAL,l.Type.OID,!1,l.oidToDer(p.oids.sha1).getBytes()),l.create(l.Class.UNIVERSAL,l.Type.NULL,!1,"")]),l.create(l.Class.UNIVERSAL,l.Type.OCTETSTRING,!1,L.getBytes())]),l.create(l.Class.UNIVERSAL,l.Type.OCTETSTRING,!1,N.getBytes()),l.create(l.Class.UNIVERSAL,l.Type.INTEGER,!1,l.integerToDer(w).getBytes())])}return l.create(l.Class.UNIVERSAL,l.Type.SEQUENCE,!0,[l.create(l.Class.UNIVERSAL,l.Type.INTEGER,!1,l.integerToDer(3).getBytes()),l.create(l.Class.UNIVERSAL,l.Type.SEQUENCE,!0,[l.create(l.Class.UNIVERSAL,l.Type.OID,!1,l.oidToDer(p.oids.data).getBytes()),l.create(l.Class.CONTEXT_SPECIFIC,0,!0,[l.create(l.Class.UNIVERSAL,l.Type.OCTETSTRING,!1,l.toDer(k).getBytes())])]),B])},f.generateKey=u.pbe.generatePkcs12Key},function(e,t,r){var n=r(0);r(3),r(1);var a=n.asn1,i=e.exports=n.pkcs7asn1=n.pkcs7asn1||{};n.pkcs7=n.pkcs7||{},n.pkcs7.asn1=i;var s={name:"ContentInfo",tagClass:a.Class.UNIVERSAL,type:a.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.ContentType",tagClass:a.Class.UNIVERSAL,type:a.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:a.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,captureAsn1:"content"}]};i.contentInfoValidator=s;var o={name:"EncryptedContentInfo",tagClass:a.Class.UNIVERSAL,type:a.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentType",tagClass:a.Class.UNIVERSAL,type:a.Type.OID,constructed:!1,capture:"contentType"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm",tagClass:a.Class.UNIVERSAL,type:a.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentEncryptionAlgorithm.algorithm",tagClass:a.Class.UNIVERSAL,type:a.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm.parameter",tagClass:a.Class.UNIVERSAL,captureAsn1:"encParameter"}]},{name:"EncryptedContentInfo.encryptedContent",tagClass:a.Class.CONTEXT_SPECIFIC,type:0,capture:"encryptedContent",captureAsn1:"encryptedContentAsn1"}]};i.envelopedDataValidator={name:"EnvelopedData",tagClass:a.Class.UNIVERSAL,type:a.Type.SEQUENCE,constructed:!0,value:[{name:"EnvelopedData.Version",tagClass:a.Class.UNIVERSAL,type:a.Type.INTEGER,constructed:!1,capture:"version"},{name:"EnvelopedData.RecipientInfos",tagClass:a.Class.UNIVERSAL,type:a.Type.SET,constructed:!0,captureAsn1:"recipientInfos"}].concat(o)},i.encryptedDataValidator={name:"EncryptedData",tagClass:a.Class.UNIVERSAL,type:a.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedData.Version",tagClass:a.Class.UNIVERSAL,type:a.Type.INTEGER,constructed:!1,capture:"version"}].concat(o)};var c={name:"SignerInfo",tagClass:a.Class.UNIVERSAL,type:a.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.version",tagClass:a.Class.UNIVERSAL,type:a.Type.INTEGER,constructed:!1},{name:"SignerInfo.issuerAndSerialNumber",tagClass:a.Class.UNIVERSAL,type:a.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.issuerAndSerialNumber.issuer",tagClass:a.Class.UNIVERSAL,type:a.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"SignerInfo.issuerAndSerialNumber.serialNumber",tagClass:a.Class.UNIVERSAL,type:a.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"SignerInfo.digestAlgorithm",tagClass:a.Class.UNIVERSAL,type:a.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.digestAlgorithm.algorithm",tagClass:a.Class.UNIVERSAL,type:a.Type.OID,constructed:!1,capture:"digestAlgorithm"},{name:"SignerInfo.digestAlgorithm.parameter",tagClass:a.Class.UNIVERSAL,constructed:!1,captureAsn1:"digestParameter",optional:!0}]},{name:"SignerInfo.authenticatedAttributes",tagClass:a.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"authenticatedAttributes"},{name:"SignerInfo.digestEncryptionAlgorithm",tagClass:a.Class.UNIVERSAL,type:a.Type.SEQUENCE,constructed:!0,capture:"signatureAlgorithm"},{name:"SignerInfo.encryptedDigest",tagClass:a.Class.UNIVERSAL,type:a.Type.OCTETSTRING,constructed:!1,capture:"signature"},{name:"SignerInfo.unauthenticatedAttributes",tagClass:a.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,capture:"unauthenticatedAttributes"}]};i.signedDataValidator={name:"SignedData",tagClass:a.Class.UNIVERSAL,type:a.Type.SEQUENCE,constructed:!0,value:[{name:"SignedData.Version",tagClass:a.Class.UNIVERSAL,type:a.Type.INTEGER,constructed:!1,capture:"version"},{name:"SignedData.DigestAlgorithms",tagClass:a.Class.UNIVERSAL,type:a.Type.SET,constructed:!0,captureAsn1:"digestAlgorithms"},s,{name:"SignedData.Certificates",tagClass:a.Class.CONTEXT_SPECIFIC,type:0,optional:!0,captureAsn1:"certificates"},{name:"SignedData.CertificateRevocationLists",tagClass:a.Class.CONTEXT_SPECIFIC,type:1,optional:!0,captureAsn1:"crls"},{name:"SignedData.SignerInfos",tagClass:a.Class.UNIVERSAL,type:a.Type.SET,capture:"signerInfos",optional:!0,value:[c]}]},i.recipientInfoValidator={name:"RecipientInfo",tagClass:a.Class.UNIVERSAL,type:a.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.version",tagClass:a.Class.UNIVERSAL,type:a.Type.INTEGER,constructed:!1,capture:"version"},{name:"RecipientInfo.issuerAndSerial",tagClass:a.Class.UNIVERSAL,type:a.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.issuerAndSerial.issuer",tagClass:a.Class.UNIVERSAL,type:a.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"RecipientInfo.issuerAndSerial.serialNumber",tagClass:a.Class.UNIVERSAL,type:a.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"RecipientInfo.keyEncryptionAlgorithm",tagClass:a.Class.UNIVERSAL,type:a.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.keyEncryptionAlgorithm.algorithm",tagClass:a.Class.UNIVERSAL,type:a.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"RecipientInfo.keyEncryptionAlgorithm.parameter",tagClass:a.Class.UNIVERSAL,constructed:!1,captureAsn1:"encParameter"}]},{name:"RecipientInfo.encryptedKey",tagClass:a.Class.UNIVERSAL,type:a.Type.OCTETSTRING,constructed:!1,capture:"encKey"}]}},function(e,t,r){var n=r(0);r(1),n.mgf=n.mgf||{},(e.exports=n.mgf.mgf1=n.mgf1=n.mgf1||{}).create=function(e){return{generate:function(t,r){for(var a=new n.util.ByteBuffer,i=Math.ceil(r/e.digestLength),s=0;s=128;){for(_=0;_<16;++_)t[_][0]=r.getInt32()>>>0,t[_][1]=r.getInt32()>>>0;for(;_<80;++_)P=t[_-2],U=P[0],D=P[1],n=((U>>>19|D<<13)^(D>>>29|U<<3)^U>>>6)>>>0,a=((U<<13|D>>>19)^(D<<3|U>>>29)^(U<<26|D>>>6))>>>0,V=t[_-15],U=V[0],D=V[1],i=((U>>>1|D<<31)^(U>>>8|D<<24)^U>>>7)>>>0,s=((U<<31|D>>>1)^(U<<24|D>>>8)^(U<<25|D>>>7))>>>0,O=t[_-7],x=t[_-16],D=a+O[1]+s+x[1],t[_][0]=n+O[0]+i+x[0]+(D/4294967296>>>0)>>>0,t[_][1]=D>>>0;for(g=e[0][0],v=e[0][1],m=e[1][0],C=e[1][1],E=e[2][0],S=e[2][1],T=e[3][0],b=e[3][1],I=e[4][0],A=e[4][1],B=e[5][0],k=e[5][1],N=e[6][0],w=e[6][1],R=e[7][0],L=e[7][1],_=0;_<80;++_)u=((I>>>14|A<<18)^(I>>>18|A<<14)^(A>>>9|I<<23))>>>0,p=((I<<18|A>>>14)^(I<<14|A>>>18)^(A<<23|I>>>9))>>>0,f=(N^I&(B^N))>>>0,h=(w^A&(k^w))>>>0,o=((g>>>28|v<<4)^(v>>>2|g<<30)^(v>>>7|g<<25))>>>0,c=((g<<4|v>>>28)^(v<<30|g>>>2)^(v<<25|g>>>7))>>>0,d=(g&m|E&(g^m))>>>0,y=(v&C|S&(v^C))>>>0,D=L+p+h+l[_][1]+t[_][1],n=R+u+f+l[_][0]+t[_][0]+(D/4294967296>>>0)>>>0,a=D>>>0,D=c+y,i=o+d+(D/4294967296>>>0)>>>0,s=D>>>0,R=N,L=w,N=B,w=k,B=I,k=A,D=b+a,I=T+n+(D/4294967296>>>0)>>>0,A=D>>>0,T=E,b=S,E=m,S=C,m=g,C=v,D=a+s,g=n+i+(D/4294967296>>>0)>>>0,v=D>>>0;D=e[0][1]+v,e[0][0]=e[0][0]+g+(D/4294967296>>>0)>>>0,e[0][1]=D>>>0,D=e[1][1]+C,e[1][0]=e[1][0]+m+(D/4294967296>>>0)>>>0,e[1][1]=D>>>0,D=e[2][1]+S,e[2][0]=e[2][0]+E+(D/4294967296>>>0)>>>0,e[2][1]=D>>>0,D=e[3][1]+b,e[3][0]=e[3][0]+T+(D/4294967296>>>0)>>>0,e[3][1]=D>>>0,D=e[4][1]+A,e[4][0]=e[4][0]+I+(D/4294967296>>>0)>>>0,e[4][1]=D>>>0,D=e[5][1]+k,e[5][0]=e[5][0]+B+(D/4294967296>>>0)>>>0,e[5][1]=D>>>0,D=e[6][1]+w,e[6][0]=e[6][0]+N+(D/4294967296>>>0)>>>0,e[6][1]=D>>>0,D=e[7][1]+L,e[7][0]=e[7][0]+R+(D/4294967296>>>0)>>>0,e[7][1]=D>>>0,K-=128}}var i=r(0);r(4),r(1);var s=e.exports=i.sha512=i.sha512||{};i.md.sha512=i.md.algorithms.sha512=s;var o=i.sha384=i.sha512.sha384=i.sha512.sha384||{};o.create=function(){return s.create("SHA-384")},i.md.sha384=i.md.algorithms.sha384=o,i.sha512.sha256=i.sha512.sha256||{create:function(){return s.create("SHA-512/256")}},i.md["sha512/256"]=i.md.algorithms["sha512/256"]=i.sha512.sha256,i.sha512.sha224=i.sha512.sha224||{create:function(){return s.create("SHA-512/224")}},i.md["sha512/224"]=i.md.algorithms["sha512/224"]=i.sha512.sha224,s.create=function(e){if(u||n(),void 0===e&&(e="SHA-512"),!(e in p))throw new Error("Invalid SHA-512 algorithm: "+e);for(var t=p[e],r=null,s=i.util.createBuffer(),o=new Array(80),l=0;l<80;++l)o[l]=new Array(2);var f=64;switch(e){case"SHA-384":f=48;break;case"SHA-512/256":f=32;break;case"SHA-512/224":f=28}var h={algorithm:e.replace("-","").toLowerCase(),blockLength:128,digestLength:f,messageLength:0,fullMessageLength:null,messageLengthSize:16};return h.start=function(){h.messageLength=0,h.fullMessageLength=h.messageLength128=[];for(var e=h.messageLengthSize/4,n=0;n>>0,n>>>0];for(var c=h.fullMessageLength.length-1;c>=0;--c)h.fullMessageLength[c]+=n[1],n[1]=n[0]+(h.fullMessageLength[c]/4294967296>>>0),h.fullMessageLength[c]=h.fullMessageLength[c]>>>0,n[0]=n[1]/4294967296>>>0;return s.putBytes(e),a(r,o,s),(s.read>2048||0===s.length())&&s.compact(),h},h.digest=function(){var t=i.util.createBuffer();t.putBytes(s.bytes());var n=h.fullMessageLength[h.fullMessageLength.length-1]+h.messageLengthSize,u=n&h.blockLength-1;t.putBytes(c.substr(0,h.blockLength-u));for(var l,p,f=8*h.fullMessageLength[0],d=0;d>>0,f+=p,t.putInt32(f>>>0),f=l>>>0;t.putInt32(f);for(var y=new Array(r.length),d=0;d0;)r=e.requests.shift(),r.request.aborted&&(r=null);null===r?(null!==t.options&&(t.options=null),e.idle.push(t)):(t.retries=1,t.options=r,l(e,t))},f=function(e,t,r){t.options=null,t.connected=function(r){if(null===t.options)p(e,t);else{var n=t.options.request;if(n.connectTime=+new Date-n.connectTime,r.socket=t,t.options.connected(r),n.aborted)t.close();else{var a=n.toString();n.body&&(a+=n.body),n.time=+new Date,t.send(a),n.time=+new Date-n.time,t.options.response.time=+new Date,t.sending=!0}}},t.closed=function(r){if(t.sending)t.sending=!1,t.retries>0?(--t.retries,l(e,t)):t.error({id:t.id,type:"ioError",message:"Connection closed during send. Broken pipe.",bytesAvailable:0});else{var n=t.options.response;n.readBodyUntilClose&&(n.time=+new Date-n.time,n.bodyReceived=!0,t.options.bodyReady({request:t.options.request,response:n,socket:t})),t.options.closed(r),p(e,t)}},t.data=function(r){if(t.sending=!1,t.options.request.aborted)t.close();else{var n=t.options.response,a=t.receive(r.bytesAvailable);null!==a&&(t.buffer.putBytes(a),n.headerReceived||(n.readHeader(t.buffer),n.headerReceived&&t.options.headerReady({request:t.options.request,response:n,socket:t})),n.headerReceived&&!n.bodyReceived&&n.readBody(t.buffer),n.bodyReceived)&&(t.options.bodyReady({request:t.options.request,response:n,socket:t}),-1!=(n.getField("Connection")||"").indexOf("close")||"HTTP/1.0"===n.version&&null===n.getField("Keep-Alive")?t.close():p(e,t))}},t.error=function(e){t.options.error({type:e.type,message:e.message,request:t.options.request,response:t.options.response,socket:t}),t.close()},r?(t=n.tls.wrapSocket({sessionId:null,sessionCache:{},caStore:r.caStore,cipherSuites:r.cipherSuites,socket:t,virtualHost:r.virtualHost,verify:r.verify,getCertificate:r.getCertificate,getPrivateKey:r.getPrivateKey,getSignature:r.getSignature,deflate:r.deflate||null,inflate:r.inflate||null}),t.options=null,t.buffer=n.util.createBuffer(),e.sockets.push(t),r.prime?t.connect({host:e.url.host,port:e.url.port,policyPort:e.policyPort,policyUrl:e.policyUrl}):e.idle.push(t)):(t.buffer=n.util.createBuffer(),e.sockets.push(t),e.idle.push(t))},h=function(e){var t=!1;if(-1!==e.maxAge){var r=m(new Date);e.created+e.maxAge<=r&&(t=!0)}return t},d=function(e,t){var r=[],n=(e.url,e.cookies);for(var a in n){var i=n[a];for(var s in i){var o=i[s];h(o)?r.push(o):0===t.path.indexOf(o.path)&&t.addCookie(o)}}for(var c=0;c100?(t.body=n.util.deflate(t.flashApi,t.body),t.bodyDeflated=!0,t.setField("Content-Encoding","deflate"),t.setField("Content-Length",t.body.length)):null!==t.body&&t.setField("Content-Length",t.body.length);var e=t.method.toUpperCase()+" "+t.path+" "+t.version+"\r\n";for(var r in t.fields)for(var a=t.fields[r],i=0;i=3)){var o=new Error("Invalid http response header.");throw o.details={line:r},o}a.version=n[0],a.code=parseInt(n[1],10),a.message=n.slice(2).join(" ")}else 0===r.length?a.headerReceived=!0:s(r);return a.headerReceived};var o=function(e){for(var n="";null!==n&&e.length()>0;)if(t>0){if(t+2>e.length())break;a.body+=e.getBytes(t),e.getBytes(2),t=0}else if(r)for(n=i(e);null!==n;)n.length>0?(s(n),n=i(e)):(a.bodyReceived=!0,n=null);else null!==(n=i(e))&&(t=parseInt(n.split(";",1)[0],16),r=0===t);return a.bodyReceived};return a.readBody=function(e){var t=a.getField("Content-Length"),r=a.getField("Transfer-Encoding");if(null!==t&&(t=parseInt(t)),null!==t&&t>=0)a.body=a.body||"",a.body+=e.getBytes(t),a.bodyReceived=a.body.length===t;else if(null!==r){if(-1==r.indexOf("chunked")){var i=new Error("Unknown Transfer-Encoding.");throw i.details={transferEncoding:r},i}a.body=a.body||"",o(e)}else null!==t&&t<0||null===t&&null!==a.getField("Content-Type")?(a.body=a.body||"",a.body+=e.getBytes(),a.readBodyUntilClose=!0):(a.body=null,a.bodyReceived=!0);return a.bodyReceived&&(a.time=+new Date-a.time),null!==a.flashApi&&a.bodyReceived&&null!==a.body&&"deflate"===a.getField("Content-Encoding")&&(a.body=n.util.inflate(a.flashApi,a.body)),a.bodyReceived},a.getCookies=function(){var e=[];if("Set-Cookie"in a.fields)for(var t=a.fields["Set-Cookie"],r=+new Date/1e3,n=/\s*([^=]*)=?([^;]*)(;|$)/g,i=0;i0;)i.push(o%n),o=o/n|0}var c="";for(r=0;0===e.at(r)&&r=0;--r)c+=t[i[r]];return c}var n={};e.exports=n;var a={};n.encode=function(e,t,n){if("string"!=typeof t)throw new TypeError('"alphabet" must be a string.');if(void 0!==n&&"number"!=typeof n)throw new TypeError('"maxline" must be a number.');var a="";if(e instanceof Uint8Array){var i=0,s=t.length,o=t.charAt(0),c=[0];for(i=0;i0;)c.push(l%s),l=l/s|0}for(i=0;0===e[i]&&i=0;--i)a+=t[c[i]]}else a=r(e,t);if(n){var p=new RegExp(".{1,"+n+"}","g");a=a.match(p).join("\r\n")}return a},n.decode=function(e,t){if("string"!=typeof e)throw new TypeError('"input" must be a string.');if("string"!=typeof t)throw new TypeError('"alphabet" must be a string.');var r=a[t];if(!r){r=a[t]=[];for(var n=0;n>=8;for(;l>0;)o.push(255&l),l>>=8}for(var p=0;e[p]===s&&p=l.Versions.TLS_1_1.minor&&s.output.putBytes(a),s.update(e.fragment),s.finish(i)&&(e.fragment=s.output,e.length=e.fragment.length(),r=!0),r}function i(e,t,r){if(!r){var n=e-t.length()%e;t.fillWithByte(n-1,n)}return!0}function s(e,t,r){var n=!0;if(r){for(var a=t.length(),i=t.last(),s=a-1-i;s=i?(e.fragment=a.output.getBytes(p-i),o=a.output.getBytes(i)):e.fragment=a.output.getBytes(),e.fragment=u.util.createBuffer(e.fragment),e.length=e.fragment.length();var f=t.macFunction(t.macKey,t.sequenceNumber,e);return t.updateSequenceNumber(),n=c(t.macKey,o,f)&&n}function c(e,t,r){var n=u.hmac.create();return n.start("SHA1",e),n.update(t),t=n.digest().getBytes(),n.start(null,null),n.update(r),r=n.digest().getBytes(),t===r}var u=r(0);r(5),r(10);var l=e.exports=u.tls;l.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA={id:[0,47],name:"TLS_RSA_WITH_AES_128_CBC_SHA",initSecurityParameters:function(e){e.bulk_cipher_algorithm=l.BulkCipherAlgorithm.aes,e.cipher_type=l.CipherType.block,e.enc_key_length=16,e.block_length=16,e.fixed_iv_length=16,e.record_iv_length=16,e.mac_algorithm=l.MACAlgorithm.hmac_sha1,e.mac_length=20,e.mac_key_length=20},initConnectionState:n},l.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA={id:[0,53],name:"TLS_RSA_WITH_AES_256_CBC_SHA",initSecurityParameters:function(e){e.bulk_cipher_algorithm=l.BulkCipherAlgorithm.aes,e.cipher_type=l.CipherType.block,e.enc_key_length=32,e.block_length=16,e.fixed_iv_length=16,e.record_iv_length=16,e.mac_algorithm=l.MACAlgorithm.hmac_sha1,e.mac_length=20,e.mac_key_length=20},initConnectionState:n}},function(e,t,r){var n=r(0);r(31),e.exports=n.mgf=n.mgf||{},n.mgf.mgf1=n.mgf1},function(e,t,r){function n(e){var t=e.message;if(t instanceof Uint8Array||t instanceof x)return t;var r=e.encoding;if(void 0===t){if(!e.md)throw new TypeError('"options.message" or "options.md" not specified.');t=e.md.digest().getBytes(),r="binary"}if("string"==typeof t&&!r)throw new TypeError('"options.encoding" must be "binary" or "utf8".');if("string"==typeof t){if("undefined"!=typeof Buffer)return Buffer.from(t,r);t=new V(t,r)}else if(!(t instanceof V))throw new TypeError('"options.message" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a string with "options.encoding" specifying its encoding.');for(var n=new x(t.length()),a=0;a=32;--n){for(r=0,a=n-32,i=n-12;a>8,t[a]-=256*r;t[a]+=r,t[n]=0}for(r=0,a=0;a<32;++a)t[a]+=r-(t[31]>>4)*Q[a],r=t[a]>>8,t[a]&=255;for(a=0;a<32;++a)t[a]-=r*Q[a];for(n=0;n<32;++n)t[n+1]+=t[n]>>8,e[n]=255&t[n]}function u(e){for(var t=new Float64Array(64),r=0;r<64;++r)t[r]=e[r],e[r]=0;c(e,t)}function l(e,t){var r=k(),n=k(),a=k(),i=k(),s=k(),o=k(),c=k(),u=k(),l=k();w(r,e[1],e[0]),w(l,t[1],t[0]),L(r,r,l),N(n,e[0],e[1]),N(l,t[0],t[1]),L(n,n,l),L(a,e[3],t[3]),L(a,a,H),L(i,e[2],t[2]),N(i,i,i),w(s,n,r),w(o,i,a),N(c,i,a),N(u,n,r),L(e[0],s,o),L(e[1],u,c),L(e[2],c,o),L(e[3],s,u)}function p(e,t,r){for(var n=0;n<4;++n)B(e[n],t[n],r)}function f(e,t){var r=k(),n=k(),a=k();I(a,t[2]),L(r,t[0],a),L(n,t[1],a),h(e,n),e[31]^=E(r)<<7}function h(e,t){var r,n,a,i=k(),s=k();for(r=0;r<16;++r)s[r]=t[r];for(A(s),A(s),A(s),n=0;n<2;++n){for(i[0]=s[0]-65517,r=1;r<15;++r)i[r]=s[r]-65535-(i[r-1]>>16&1),i[r-1]&=65535;i[15]=s[15]-32767-(i[14]>>16&1),a=i[15]>>16&1,i[14]&=65535,B(s,i,1-a)}for(r=0;r<16;r++)e[2*r]=255&s[r],e[2*r+1]=s[r]>>8}function d(e,t){var r=k(),n=k(),a=k(),i=k(),s=k(),o=k(),c=k();return b(e[2],F),y(e[1],t),R(a,e[1]),L(i,a,q),w(a,a,e[2]),N(i,e[2],i),R(s,i),R(o,s),L(c,o,s),L(r,c,a),L(r,r,i),g(r,r),L(r,r,a),L(r,r,i),L(r,r,i),L(e[0],r,i),R(n,e[0]),L(n,n,i),v(n,a)&&L(e[0],e[0],z),R(n,e[0]),L(n,n,i),v(n,a)?-1:(E(e[0])===t[31]>>7&&w(e[0],M,e[0]),L(e[3],e[0],e[1]),0)}function y(e,t){var r;for(r=0;r<16;++r)e[r]=t[2*r]+(t[2*r+1]<<8);e[15]&=32767}function g(e,t){var r,n=k();for(r=0;r<16;++r)n[r]=t[r];for(r=250;r>=0;--r)R(n,n),1!==r&&L(n,n,t);for(r=0;r<16;++r)e[r]=n[r]}function v(e,t){var r=new x(32),n=new x(32);return h(r,e),h(n,t),m(r,0,n,0)}function m(e,t,r,n){return C(e,t,r,n,32)}function C(e,t,r,n,a){var i,s=0;for(i=0;i>>8)-1}function E(e){var t=new x(32);return h(t,e),1&t[0]}function S(e,t,r){var n,a;for(b(e[0],M),b(e[1],F),b(e[2],F),b(e[3],M),a=255;a>=0;--a)n=r[a/8|0]>>(7&a)&1,p(e,t,n),l(t,e),l(e,e),p(e,t,n)}function T(e,t){var r=[k(),k(),k(),k()];b(r[0],j),b(r[1],G),b(r[2],F),L(r[3],j,G),S(e,r,t)}function b(e,t){var r;for(r=0;r<16;r++)e[r]=0|t[r]}function I(e,t){var r,n=k();for(r=0;r<16;++r)n[r]=t[r];for(r=253;r>=0;--r)R(n,n),2!==r&&4!==r&&L(n,n,t);for(r=0;r<16;++r)e[r]=n[r]}function A(e){var t,r,n=1;for(t=0;t<16;++t)r=e[t]+n+65535,n=Math.floor(r/65536),e[t]=r-65536*n;e[0]+=n-1+37*(n-1)}function B(e,t,r){for(var n,a=~(r-1),i=0;i<16;++i)n=a&(e[i]^t[i]),e[i]^=n,t[i]^=n}function k(e){var t,r=new Float64Array(16);if(e)for(t=0;t=0};var M=k(),F=k([1]),q=k([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),H=k([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),j=k([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),G=k([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),Q=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]),z=k([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139])},function(e,t,r){var n=r(0);r(3);var a=n.asn1;t.privateKeyValidator={name:"PrivateKeyInfo",tagClass:a.Class.UNIVERSAL,type:a.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:a.Class.UNIVERSAL,type:a.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:a.Class.UNIVERSAL,type:a.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:a.Class.UNIVERSAL,type:a.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:a.Class.UNIVERSAL,type:a.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},t.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:a.Class.UNIVERSAL,type:a.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:a.Class.UNIVERSAL,type:a.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:a.Class.UNIVERSAL,type:a.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{tagClass:a.Class.UNIVERSAL,type:a.Type.BITSTRING,constructed:!1,composed:!0,captureBitStringValue:"ed25519PublicKey"}]}},function(e,t,r){function n(e,t,r,n){e.generate=function(e,i){for(var s=new a.util.ByteBuffer,o=Math.ceil(i/n)+r,c=new a.util.ByteBuffer,u=r;u0&&(s=a.util.fillString(String.fromCharCode(0),c)+s),{encapsulation:t.encrypt(s,"NONE"),key:e.generate(s,n)}},n.decrypt=function(t,r,n){var a=t.decrypt(r,"NONE");return e.generate(a,n)},n},a.kem.kdf1=function(e,t){n(this,e,0,t||e.digestLength)},a.kem.kdf2=function(e,t){n(this,e,1,t||e.digestLength)}},function(e,t,r){e.exports=r(4),r(15),r(9),r(24),r(32)},function(e,t,r){function n(e){var t={},r=[];if(!d.validate(e,y.asn1.recipientInfoValidator,t,r)){var n=new Error("Cannot read PKCS#7 RecipientInfo. ASN.1 object is not an PKCS#7 RecipientInfo.");throw n.errors=r,n}return{version:t.version.charCodeAt(0),issuer:h.pki.RDNAttributesAsArray(t.issuer),serialNumber:h.util.createBuffer(t.serial).toHex(),encryptedContent:{algorithm:d.derToOid(t.encAlgorithm),parameter:t.encParameter.value,content:t.encKey}}}function a(e){return d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[d.create(d.Class.UNIVERSAL,d.Type.INTEGER,!1,d.integerToDer(e.version).getBytes()),d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[h.pki.distinguishedNameToAsn1({attributes:e.issuer}),d.create(d.Class.UNIVERSAL,d.Type.INTEGER,!1,h.util.hexToBytes(e.serialNumber))]),d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[d.create(d.Class.UNIVERSAL,d.Type.OID,!1,d.oidToDer(e.encryptedContent.algorithm).getBytes()),d.create(d.Class.UNIVERSAL,d.Type.NULL,!1,"")]),d.create(d.Class.UNIVERSAL,d.Type.OCTETSTRING,!1,e.encryptedContent.content)])}function i(e){for(var t=[],r=0;r0){for(var r=d.create(d.Class.CONTEXT_SPECIFIC,1,!0,[]),n=0;n=r&&a0&&a.value[0].value.push(d.create(d.Class.CONTEXT_SPECIFIC,0,!0,e)),n.length>0&&a.value[0].value.push(d.create(d.Class.CONTEXT_SPECIFIC,1,!0,n)),a.value[0].value.push(d.create(d.Class.UNIVERSAL,d.Type.SET,!0,r.signerInfos)),d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[d.create(d.Class.UNIVERSAL,d.Type.OID,!1,d.oidToDer(r.type).getBytes()),a])},addSigner:function(e){var t=e.issuer,n=e.serialNumber;if(e.certificate){var a=e.certificate;"string"==typeof a&&(a=h.pki.certificateFromPem(a)),t=a.issuer.attributes,n=a.serialNumber}var i=e.key;if(!i)throw new Error("Could not add PKCS#7 signer; no private key specified.");"string"==typeof i&&(i=h.pki.privateKeyFromPem(i));var s=e.digestAlgorithm||h.pki.oids.sha1;switch(s){case h.pki.oids.sha1:case h.pki.oids.sha256:case h.pki.oids.sha384:case h.pki.oids.sha512:case h.pki.oids.md5:break;default:throw new Error("Could not add PKCS#7 signer; unknown message digest algorithm: "+s)}var o=e.authenticatedAttributes||[];if(o.length>0){for(var c=!1,u=!1,l=0;l="8"&&(r="00"+r);var n=s.util.hexToBytes(r);e.putInt32(n.length),e.putBytes(n)}function a(e,t){e.putInt32(t.length),e.putString(t)}function i(){for(var e=s.md.sha1.create(),t=arguments.length,r=0;r0&&(this.state=g[this.state].block)},v.prototype.unblock=function(e){return e=void 0===e?1:e,this.blocks-=e,0===this.blocks&&this.state!==f&&(this.state=u,C(this,0)),this.blocks},v.prototype.sleep=function(e){e=void 0===e?0:e,this.state=g[this.state].sleep;var t=this;this.timeoutId=setTimeout(function(){t.timeoutId=null,t.state=u,C(t,0)},e)},v.prototype.wait=function(e){e.wait(this)},v.prototype.wakeup=function(){this.state===p&&(cancelTimeout(this.timeoutId),this.timeoutId=null,this.state=u,C(this,0))},v.prototype.cancel=function(){this.state=g[this.state].cancel,this.permitsNeeded=0,null!==this.timeoutId&&(cancelTimeout(this.timeoutId),this.timeoutId=null),this.subtasks=[]},v.prototype.fail=function(e){if(this.error=!0,E(this,!0),e)e.error=this.error,e.swapTime=this.swapTime,e.userData=this.userData,C(e,0);else{if(null!==this.parent){for(var t=this.parent;null!==t.parent;)t.error=this.error,t.swapTime=this.swapTime,t.userData=this.userData,t=t.parent;E(t,!0)}this.failureCallback&&this.failureCallback(this)}};var m=function(e){e.error=!1,e.state=g[e.state][y],setTimeout(function(){e.state===u&&(e.swapTime=+new Date,e.run(e),C(e,0))},0)},C=function(e,t){var r=t>30||+new Date-e.swapTime>20,n=function(t){if(t++,e.state===u)if(r&&(e.swapTime=+new Date),e.subtasks.length>0){var n=e.subtasks.shift();n.error=e.error,n.swapTime=e.swapTime,n.userData=e.userData,n.run(n),n.error||C(n,t)}else E(e),e.error||null!==e.parent&&(e.parent.error=e.error,e.parent.swapTime=e.swapTime,e.parent.userData=e.userData,C(e.parent,t))};r?setTimeout(n,0):n(t)},E=function(e,t){e.state=f,delete i[e.id],null===e.parent&&(e.type in o?0===o[e.type].length?n.log.error(a,"[%s][%s] task queue empty [%s]",e.id,e.name,e.type):o[e.type][0]!==e?n.log.error(a,"[%s][%s] task not first in queue [%s]",e.id,e.name,e.type):(o[e.type].shift(),0===o[e.type].length?delete o[e.type]:o[e.type][0].start()):n.log.error(a,"[%s][%s] task queue missing [%s]",e.id,e.name,e.type),t||(e.error&&e.failureCallback?e.failureCallback(e):!e.error&&e.successCallback&&e.successCallback(e)))};e.exports=n.task=n.task||{},n.task.start=function(e){var t=new v({run:e.run,name:e.name||"?"});t.type=e.type,t.successCallback=e.success||null,t.failureCallback=e.failure||null,t.type in o?o[e.type].push(t):(o[t.type]=[t],m(t))},n.task.cancel=function(e){e in o&&(o[e]=[o[e][0]])},n.task.createCondition=function(){var e={tasks:{}};return e.wait=function(t){t.id in e.tasks||(t.block(),e.tasks[t.id]=t)},e.notify=function(){var t=e.tasks;e.tasks={};for(var r in t)t[r].unblock()},e}},function(e,t,r){var n=r(0),a=e.exports=n.form=n.form||{};!function(e){var t=/([^\[]*?)\[(.*?)\]/g,r=function(e){for(var r,n=[];r=t.exec(e);)r[1].length>0&&n.push(r[1]),r.length>=2&&n.push(r[2]);return 0===n.length&&n.push(e),n},n=function(t,n,a,i){for(var s=[],o=0;o0;t[s]=c?[]:{}}t=t[s]}})};a.serialize=function(t,r,a){var i={};return r=r||".",e.each(t.serializeArray(),function(){n(i,this.name.split(r),this.value||"",a)}),i}}(jQuery)},function(e,t,r){var n=r(0);r(10),n.tls.wrapSocket=function(e){var t=e.socket,r={id:t.id,connected:t.connected||function(e){},closed:t.closed||function(e){},data:t.data||function(e){},error:t.error||function(e){}},a=n.tls.createConnection({server:!1,sessionId:e.sessionId||null,caStore:e.caStore||[],sessionCache:e.sessionCache||null,cipherSuites:e.cipherSuites||null,virtualHost:e.virtualHost,verify:e.verify,getCertificate:e.getCertificate,getPrivateKey:e.getPrivateKey,getSignature:e.getSignature,deflate:e.deflate,inflate:e.inflate,connected:function(e){1===e.handshakes&&r.connected({id:t.id,type:"connect",bytesAvailable:e.data.length()})},tlsDataReady:function(e){return t.send(e.tlsData.getBytes())},dataReady:function(e){r.data({id:t.id,type:"socketData",bytesAvailable:e.data.length()})},closed:function(e){t.close()},error:function(e,n){r.error({id:t.id,type:"tlsError",message:n.message,bytesAvailable:0,error:n}),t.close()}});t.connected=function(t){a.handshake(e.sessionId)},t.closed=function(e){a.open&&a.handshaking&&r.error({id:t.id,type:"ioError",message:"Connection closed during handshake.",bytesAvailable:0}),a.close(),r.closed({id:t.id,type:"close",bytesAvailable:0})},t.error=function(e){r.error({id:t.id,type:e.type,message:e.message,bytesAvailable:0}),a.close()};var i=0;return t.data=function(e){if(a.open){if(e.bytesAvailable>=i){var r=Math.max(e.bytesAvailable,i),n=t.receive(r);null!==n&&(i=a.process(n))}}else t.receive(e.bytesAvailable)},r.destroy=function(){t.destroy()},r.setSessionCache=function(e){a.sessionCache=tls.createSessionCache(e)},r.connect=function(e){t.connect(e)},r.close=function(){a.close()},r.isConnected=function(){return a.isConnected&&t.isConnected()},r.send=function(e){return a.prepare(e)},r.receive=function(e){return a.data.getBytes(e)},r.bytesAvailable=function(){return a.data.length()},r}},function(e,t,r){var n=r(0);r(34),r(35);var a=e.exports=n.xhr=n.xhr||{};!function(e){var t="forge.xhr",r=null,i=0,s=null,o=null,c={},u=10,l=n.net,p=n.http;a.init=function(e){n.log.debug(t,"initializing",e),i=e.policyPort||i,s=e.policyUrl||s,u=e.connections||u,r=l.createSocketPool({flashId:e.flashId,policyPort:i,policyUrl:s,msie:e.msie||!1}),o=p.createClient({url:e.url||window.location.protocol+"//"+window.location.host,socketPool:r,policyPort:i,policyUrl:s,connections:e.connections||u,caCerts:e.caCerts,cipherSuites:e.cipherSuites,persistCookies:e.persistCookies||!0,primeTlsSockets:e.primeTlsSockets||!1,verify:e.verify,getCertificate:e.getCertificate,getPrivateKey:e.getPrivateKey,getSignature:e.getSignature}),c[o.url.full]=o,n.log.debug(t,"ready")},a.cleanup=function(){for(var e in c)c[e].destroy();c={},o=null,r.destroy(),r=null},a.setCookie=function(e){if(e.maxAge=e.maxAge||-1,e.domain)for(var t in c){var r=c[t];p.withinCookieDomain(r.url,e)&&r.secure===e.secure&&r.setCookie(e)}else o.setCookie(e)},a.getCookie=function(e,t,r){var a=null;if(r)for(var i in c){var s=c[i];if(p.withinCookieDomain(s.url,r)){var u=s.getCookie(e,t);null!==u&&(null===a?a=u:n.util.isArray(a)?a.push(u):a=[a,u])}}else a=o.getCookie(e,t);return a},a.removeCookie=function(e,t,r){var n=!1;if(r)for(var a in c){var i=c[a];p.withinCookieDomain(i.url,r)&&i.removeCookie(e,t)&&(n=!0)}else n=o.removeCookie(e,t);return n},a.create=function(a){a=e.extend({logWarningOnError:!0,verbose:!1,logError:function(){},logWarning:function(){},logDebug:function(){},logVerbose:function(){},url:null},a||{});var l={client:null,request:null,response:null,asynchronous:!0,sendFlag:!1,errorFlag:!1},f={error:a.logError||n.log.error,warning:a.logWarning||n.log.warning,debug:a.logDebug||n.log.debug,verbose:a.logVerbose||n.log.verbose},h={onreadystatechange:null,readyState:0,responseText:"",responseXML:null,status:0,statusText:""};if(null===a.url)l.client=o;else{var d=p.parseUrl(a.url);if(!d){new Error("Invalid url.").details={url:a.url}}d.full in c?l.client=c[d.full]:(l.client=p.createClient({url:a.url,socketPool:r,policyPort:a.policyPort||i,policyUrl:a.policyUrl||s,connections:a.connections||u,caCerts:a.caCerts,cipherSuites:a.cipherSuites,persistCookies:a.persistCookies||!0,primeTlsSockets:a.primeTlsSockets||!1,verify:a.verify,getCertificate:a.getCertificate,getPrivateKey:a.getPrivateKey,getSignature:a.getSignature}),c[d.full]=l.client)}return h.open=function(e,t,r,n,a){switch(e){case"DELETE":case"GET":case"HEAD":case"OPTIONS":case"PATCH":case"POST":case"PUT":break;case"CONNECT":case"TRACE":case"TRACK":throw new Error("CONNECT, TRACE and TRACK methods are disallowed");default:throw new Error("Invalid method: "+e)}l.sendFlag=!1,h.responseText="",h.responseXML=null,h.status=0,h.statusText="",l.request=p.createRequest({method:e,path:t}),h.readyState=1,h.onreadystatechange&&h.onreadystatechange()},h.setRequestHeader=function(e,t){if(1!=h.readyState||l.sendFlag)throw new Error("XHR not open or sending");l.request.setField(e,t)},h.send=function(e){if(1!=h.readyState||l.sendFlag)throw new Error("XHR not open or sending");if(e&&"GET"!==l.request.method&&"HEAD"!==l.request.method)if("undefined"!=typeof XMLSerializer)if(e instanceof Document){var r=new XMLSerializer;l.request.body=r.serializeToString(e)}else l.request.body=e;else void 0!==e.xml?l.request.body=e.xml:l.request.body=e;l.errorFlag=!1,l.sendFlag=!0,h.onreadystatechange&&h.onreadystatechange();var n={};n.request=l.request,n.headerReady=function(e){h.cookies=l.client.cookies,h.readyState=2,h.status=e.response.code,h.statusText=e.response.message,l.response=e.response,h.onreadystatechange&&h.onreadystatechange(),l.response.aborted||(h.readyState=3,h.onreadystatechange&&h.onreadystatechange())},n.bodyReady=function(e){h.readyState=4;var r=e.response.getField("Content-Type");if(r&&(0===r.indexOf("text/xml")||0===r.indexOf("application/xml")||-1!==r.indexOf("+xml")))try{var a=new ActiveXObject("MicrosoftXMLDOM");a.async=!1,a.loadXML(e.response.body),h.responseXML=a}catch(e){var i=new DOMParser;h.responseXML=i.parseFromString(e.body,"text/xml")}var s=0;null!==e.response.body&&(h.responseText=e.response.body,s=e.response.body.length);var o=l.request,c=o.method+" "+o.path+" "+h.status+" "+h.statusText+" "+s+"B "+(e.request.connectTime+e.request.time+e.response.time)+"ms";n.verbose?(h.status>=400&&n.logWarningOnError?f.warning:f.verbose)(t,c,e,e.response.body?"\n"+e.response.body:"\nNo content"):(h.status>=400&&n.logWarningOnError?f.warning:f.debug)(t,c),h.onreadystatechange&&h.onreadystatechange()},n.error=function(e){var r=l.request;f.error(t,r.method+" "+r.path,e),h.responseText="",h.responseXML=null,l.errorFlag=!0,h.status=0,h.statusText="",h.readyState=4,h.onreadystatechange&&h.onreadystatechange()},l.client.send(n)},h.abort=function(){l.request.abort(),h.responseText="",h.responseXML=null,l.errorFlag=!0,h.status=0,h.statusText="",l.request=null,l.response=null,4===h.readyState||0===h.readyState||1===h.readyState&&!l.sendFlag?h.readyState=0:(h.readyState=4,l.sendFlag=!1,h.onreadystatechange&&h.onreadystatechange(),h.readyState=0)},h.getAllResponseHeaders=function(){var t="";if(null!==l.response){var r=l.response.fields;e.each(r,function(r,n){e.each(n,function(e,n){t+=r+": "+n+"\r\n"})})}return t},h.getResponseHeader=function(e){var t=null;return null!==l.response&&e in l.response.fields&&(t=l.response.fields[e],n.util.isArray(t)&&(t=t.join())),t},h}}(jQuery)}])}); +//# sourceMappingURL=forge.all.min.js.map \ No newline at end of file diff --git a/node_modules/node-forge/dist/forge.all.min.js.map b/node_modules/node-forge/dist/forge.all.min.js.map new file mode 100644 index 0000000..5d80865 --- /dev/null +++ b/node_modules/node-forge/dist/forge.all.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"forge.all.min.js","sources":["webpack:///forge.all.min.js"],"mappings":"AAAA","sourceRoot":""} \ No newline at end of file diff --git a/node_modules/node-forge/dist/forge.min.js b/node_modules/node-forge/dist/forge.min.js new file mode 100644 index 0000000..deca475 --- /dev/null +++ b/node_modules/node-forge/dist/forge.min.js @@ -0,0 +1,2 @@ +!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.forge=t():e.forge=t()}("undefined"!=typeof self?self:this,function(){return function(e){function t(a){if(r[a])return r[a].exports;var n=r[a]={i:a,l:!1,exports:{}};return e[a].call(n.exports,n,n.exports,t),n.l=!0,n.exports}var r={};return t.m=e,t.c=r,t.d=function(e,r,a){t.o(e,r)||Object.defineProperty(e,r,{configurable:!1,enumerable:!0,get:a})},t.n=function(e){var r=e&&e.__esModule?function(){return e.default}:function(){return e};return t.d(r,"a",r),r},t.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},t.p="",t(t.s=34)}([function(e,t){e.exports={options:{usePureJavaScript:!1}}},function(e,t,r){(function(t){function a(e){if(8!==e&&16!==e&&24!==e&&32!==e)throw new Error("Only 8, 16, 24, or 32 bits supported: "+e)}function n(e){if(this.data="",this.read=0,"string"==typeof e)this.data=e;else if(c.isArrayBuffer(e)||c.isArrayBufferView(e))if("undefined"!=typeof Buffer&&e instanceof Buffer)this.data=e.toString("binary");else{var t=new Uint8Array(e);try{this.data=String.fromCharCode.apply(null,t)}catch(e){for(var r=0;r15?(a=Date.now(),s(e)):(r.push(e),1===r.length&&i.setAttribute("a",n=!n))}}c.nextTick=c.setImmediate}(),c.isNodejs="undefined"!=typeof process&&process.versions&&process.versions.node,c.globalScope=function(){return c.isNodejs?t:"undefined"==typeof self?window:self}(),c.isArray=Array.isArray||function(e){return"[object Array]"===Object.prototype.toString.call(e)},c.isArrayBuffer=function(e){return"undefined"!=typeof ArrayBuffer&&e instanceof ArrayBuffer},c.isArrayBufferView=function(e){return e&&c.isArrayBuffer(e.buffer)&&void 0!==e.byteLength},c.ByteBuffer=n,c.ByteStringBuffer=n;c.ByteStringBuffer.prototype._optimizeConstructedString=function(e){this._constructedStringLength+=e,this._constructedStringLength>4096&&(this.data.substr(0,1),this._constructedStringLength=0)},c.ByteStringBuffer.prototype.length=function(){return this.data.length-this.read},c.ByteStringBuffer.prototype.isEmpty=function(){return this.length()<=0},c.ByteStringBuffer.prototype.putByte=function(e){return this.putBytes(String.fromCharCode(e))},c.ByteStringBuffer.prototype.fillWithByte=function(e,t){e=String.fromCharCode(e);for(var r=this.data;t>0;)1&t&&(r+=e),(t>>>=1)>0&&(e+=e);return this.data=r,this._optimizeConstructedString(t),this},c.ByteStringBuffer.prototype.putBytes=function(e){return this.data+=e,this._optimizeConstructedString(e.length),this},c.ByteStringBuffer.prototype.putString=function(e){return this.putBytes(c.encodeUtf8(e))},c.ByteStringBuffer.prototype.putInt16=function(e){return this.putBytes(String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},c.ByteStringBuffer.prototype.putInt24=function(e){return this.putBytes(String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},c.ByteStringBuffer.prototype.putInt32=function(e){return this.putBytes(String.fromCharCode(e>>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e))},c.ByteStringBuffer.prototype.putInt16Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255))},c.ByteStringBuffer.prototype.putInt24Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255))},c.ByteStringBuffer.prototype.putInt32Le=function(e){return this.putBytes(String.fromCharCode(255&e)+String.fromCharCode(e>>8&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>24&255))},c.ByteStringBuffer.prototype.putInt=function(e,t){a(t);var r="";do{t-=8,r+=String.fromCharCode(e>>t&255)}while(t>0);return this.putBytes(r)},c.ByteStringBuffer.prototype.putSignedInt=function(e,t){return e<0&&(e+=2<0);return t},c.ByteStringBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<=r&&(t-=r<<1),t},c.ByteStringBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):0===e?t="":(t=0===this.read?this.data:this.data.slice(this.read),this.clear()),t},c.ByteStringBuffer.prototype.bytes=function(e){return void 0===e?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},c.ByteStringBuffer.prototype.at=function(e){return this.data.charCodeAt(this.read+e)},c.ByteStringBuffer.prototype.setAt=function(e,t){return this.data=this.data.substr(0,this.read+e)+String.fromCharCode(t)+this.data.substr(this.read+e+1),this},c.ByteStringBuffer.prototype.last=function(){return this.data.charCodeAt(this.data.length-1)},c.ByteStringBuffer.prototype.copy=function(){var e=c.createBuffer(this.data);return e.read=this.read,e},c.ByteStringBuffer.prototype.compact=function(){return this.read>0&&(this.data=this.data.slice(this.read),this.read=0),this},c.ByteStringBuffer.prototype.clear=function(){return this.data="",this.read=0,this},c.ByteStringBuffer.prototype.truncate=function(e){var t=Math.max(0,this.length()-e);return this.data=this.data.substr(this.read,t),this.read=0,this},c.ByteStringBuffer.prototype.toHex=function(){for(var e="",t=this.read;t=e)return this;t=Math.max(t||this.growSize,e);var r=new Uint8Array(this.data.buffer,this.data.byteOffset,this.data.byteLength),a=new Uint8Array(this.length()+t);return a.set(r),this.data=new DataView(a.buffer),this},c.DataBuffer.prototype.putByte=function(e){return this.accommodate(1),this.data.setUint8(this.write++,e),this},c.DataBuffer.prototype.fillWithByte=function(e,t){this.accommodate(t);for(var r=0;r>8&65535),this.data.setInt8(this.write,e>>16&255),this.write+=3,this},c.DataBuffer.prototype.putInt32=function(e){return this.accommodate(4),this.data.setInt32(this.write,e),this.write+=4,this},c.DataBuffer.prototype.putInt16Le=function(e){return this.accommodate(2),this.data.setInt16(this.write,e,!0),this.write+=2,this},c.DataBuffer.prototype.putInt24Le=function(e){return this.accommodate(3),this.data.setInt8(this.write,e>>16&255),this.data.setInt16(this.write,e>>8&65535,!0),this.write+=3,this},c.DataBuffer.prototype.putInt32Le=function(e){return this.accommodate(4),this.data.setInt32(this.write,e,!0),this.write+=4,this},c.DataBuffer.prototype.putInt=function(e,t){a(t),this.accommodate(t/8);do{t-=8,this.data.setInt8(this.write++,e>>t&255)}while(t>0);return this},c.DataBuffer.prototype.putSignedInt=function(e,t){return a(t),this.accommodate(t/8),e<0&&(e+=2<0);return t},c.DataBuffer.prototype.getSignedInt=function(e){var t=this.getInt(e),r=2<=r&&(t-=r<<1),t},c.DataBuffer.prototype.getBytes=function(e){var t;return e?(e=Math.min(this.length(),e),t=this.data.slice(this.read,this.read+e),this.read+=e):0===e?t="":(t=0===this.read?this.data:this.data.slice(this.read),this.clear()),t},c.DataBuffer.prototype.bytes=function(e){return void 0===e?this.data.slice(this.read):this.data.slice(this.read,this.read+e)},c.DataBuffer.prototype.at=function(e){return this.data.getUint8(this.read+e)},c.DataBuffer.prototype.setAt=function(e,t){return this.data.setUint8(e,t),this},c.DataBuffer.prototype.last=function(){return this.data.getUint8(this.write-1)},c.DataBuffer.prototype.copy=function(){return new c.DataBuffer(this)},c.DataBuffer.prototype.compact=function(){if(this.read>0){var e=new Uint8Array(this.data.buffer,this.read),t=new Uint8Array(e.byteLength);t.set(e),this.data=new DataView(t),this.write-=this.read,this.read=0}return this},c.DataBuffer.prototype.clear=function(){return this.data=new DataView(new ArrayBuffer(0)),this.read=this.write=0,this},c.DataBuffer.prototype.truncate=function(e){return this.write=Math.max(0,this.length()-e),this.read=Math.min(this.read,this.write),this},c.DataBuffer.prototype.toHex=function(){for(var e="",t=this.read;t0;)1&t&&(r+=e),(t>>>=1)>0&&(e+=e);return r},c.xorBytes=function(e,t,r){for(var a="",n="",i="",s=0,o=0;r>0;--r,++s)n=e.charCodeAt(s)^t.charCodeAt(s),o>=10&&(a+=i,i="",o=0),i+=String.fromCharCode(n),++o;return a+=i},c.hexToBytes=function(e){var t="",r=0;for(!0&e.length&&(r=1,t+=String.fromCharCode(parseInt(e[0],16)));r>24&255)+String.fromCharCode(e>>16&255)+String.fromCharCode(e>>8&255)+String.fromCharCode(255&e)};var u="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",l=[62,-1,-1,-1,63,52,53,54,55,56,57,58,59,60,61,-1,-1,-1,64,-1,-1,-1,0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,-1,-1,-1,-1,-1,-1,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51],p="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";c.encode64=function(e,t){for(var r,a,n,i="",s="",o=0;o>2),i+=u.charAt((3&r)<<4|a>>4),isNaN(a)?i+="==":(i+=u.charAt((15&a)<<2|n>>6),i+=isNaN(n)?"=":u.charAt(63&n)),t&&i.length>t&&(s+=i.substr(0,t)+"\r\n",i=i.substr(t));return s+=i},c.decode64=function(e){e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");for(var t,r,a,n,i="",s=0;s>4),64!==a&&(i+=String.fromCharCode((15&r)<<4|a>>2),64!==n&&(i+=String.fromCharCode((3&a)<<6|n)));return i},c.encodeUtf8=function(e){return unescape(encodeURIComponent(e))},c.decodeUtf8=function(e){return decodeURIComponent(escape(e))},c.binary={raw:{},hex:{},base64:{},base58:{},baseN:{encode:o.encode,decode:o.decode}},c.binary.raw.encode=function(e){return String.fromCharCode.apply(null,e)},c.binary.raw.decode=function(e,t,r){var a=t;a||(a=new Uint8Array(e.length)),r=r||0;for(var n=r,i=0;i>2),i+=u.charAt((3&r)<<4|a>>4),isNaN(a)?i+="==":(i+=u.charAt((15&a)<<2|n>>6),i+=isNaN(n)?"=":u.charAt(63&n)),t&&i.length>t&&(s+=i.substr(0,t)+"\r\n",i=i.substr(t));return s+=i},c.binary.base64.decode=function(e,t,r){var a=t;a||(a=new Uint8Array(3*Math.ceil(e.length/4))),e=e.replace(/[^A-Za-z0-9\+\/\=]/g,""),r=r||0;for(var n,i,s,o,c=0,u=r;c>4,64!==s&&(a[u++]=(15&i)<<4|s>>2,64!==o&&(a[u++]=(3&s)<<6|o));return t?u-r:a.subarray(0,u)},c.binary.base58.encode=function(e,t){return c.binary.baseN.encode(e,p,t)},c.binary.base58.decode=function(e,t){return c.binary.baseN.decode(e,p,t)},c.text={utf8:{},utf16:{}},c.text.utf8.encode=function(e,t,r){e=c.encodeUtf8(e);var a=t;a||(a=new Uint8Array(e.length)),r=r||0;for(var n=r,i=0;i0?(n=r[a].substring(0,s),i=r[a].substring(s+1)):(n=r[a],i=null),n in t||(t[n]=[]),n in Object.prototype||null===i||t[n].push(unescape(i))}return t};return void 0===e?(null===C&&(C="undefined"!=typeof window&&window.location&&window.location.search?r(window.location.search.substring(1)):{}),t=C):t=r(e),t},c.parseFragment=function(e){var t=e,r="",a=e.indexOf("?");a>0&&(t=e.substring(0,a),r=e.substring(a+1));var n=t.split("/");return n.length>0&&""===n[0]&&n.shift(),{pathString:t,queryString:r,path:n,query:""===r?{}:c.getQueryVariables(r)}},c.makeRequest=function(e){var t=c.parseFragment(e),r={path:t.pathString,query:t.queryString,getPath:function(e){return void 0===e?t.path:t.path[e]},getQuery:function(e,r){var a;return void 0===e?a=t.query:(a=t.query[e])&&void 0!==r&&(a=a[r]),a},getQueryLast:function(e,t){var a=r.getQuery(e);return a?a[a.length-1]:t}};return r},c.makeLink=function(e,t,r){e=jQuery.isArray(e)?e.join("/"):e;var a=jQuery.param(t||{});return r=r||"",e+(a.length>0?"?"+a:"")+(r.length>0?"#"+r:"")},c.setPath=function(e,t,r){if("object"==typeof e&&null!==e)for(var a=0,n=t.length;a0&&i.push(r),s=a.lastIndex;var o=t[0][1];switch(o){case"s":case"o":n");break;case"%":i.push("%");break;default:i.push("<%"+o+"?>")}}return i.push(e.substring(s)),i.join("")},c.formatNumber=function(e,t,r,a){var n=e,i=isNaN(t=Math.abs(t))?2:t,s=void 0===r?",":r,o=void 0===a?".":a,c=n<0?"-":"",u=parseInt(n=Math.abs(+n||0).toFixed(i),10)+"",l=u.length>3?u.length%3:0;return c+(l?u.substr(0,l)+o:"")+u.substr(l).replace(/(\d{3})(?=\d)/g,"$1"+o)+(i?s+Math.abs(n-u).toFixed(i).slice(2):"")},c.formatSize=function(e){return e=e>=1073741824?c.formatNumber(e/1073741824,2,".","")+" GiB":e>=1048576?c.formatNumber(e/1048576,2,".","")+" MiB":e>=1024?c.formatNumber(e/1024,0)+" KiB":c.formatNumber(e,0)+" bytes"},c.bytesFromIP=function(e){return-1!==e.indexOf(".")?c.bytesFromIPv4(e):-1!==e.indexOf(":")?c.bytesFromIPv6(e):null},c.bytesFromIPv4=function(e){if(e=e.split("."),4!==e.length)return null;for(var t=c.createBuffer(),r=0;rr[a].end-r[a].start&&(a=r.length-1)):r.push({start:o,end:o})}t.push(i)}if(r.length>0){var u=r[a];u.end-u.start>0&&(t.splice(u.start,u.end-u.start+1,""),0===u.start&&t.unshift(""),7===u.end&&t.push(""))}return t.join(":")},c.estimateCores=function(e,t){function r(e,s,o){if(0===s){var u=Math.floor(e.reduce(function(e,t){return e+t},0)/e.length);return c.cores=Math.max(1,u),URL.revokeObjectURL(i),t(null,c.cores)}a(o,function(t,a){e.push(n(o,a)),r(e,s-1,o)})}function a(e,t){for(var r=[],a=[],n=0;no.st&&n.stn.st&&o.st0)return c.cores=navigator.hardwareConcurrency,t(null,c.cores);if("undefined"==typeof Worker)return c.cores=1,t(null,c.cores);if("undefined"==typeof Blob)return c.cores=2,t(null,c.cores);var i=URL.createObjectURL(new Blob(["(",function(){self.addEventListener("message",function(e){for(var t=Date.now(),r=t+4;Date.now()t){var a=new Error("Too few bytes to parse DER.");throw a.available=e.length(),a.remaining=t,a.requested=r,a}}function n(e,t,r,i){var c;a(e,t,2);var u=e.getByte();t--;var l=192&u,p=31&u;c=e.length();var f=o(e,t);if(t-=c-e.length(),void 0!==f&&f>t){if(i.strict){var h=new Error("Too few bytes to read ASN.1 value.");throw h.available=e.length(),h.remaining=t,h.requested=f,h}f=t}var d,y,g=32==(32&u);if(g)if(d=[],void 0===f)for(;;){if(a(e,t,2),e.bytes(2)===String.fromCharCode(0,0)){e.getBytes(2),t-=2;break}c=e.length(),d.push(n(e,t,r+1,i)),t-=c-e.length()}else for(;f>0;)c=e.length(),d.push(n(e,f,r+1,i)),t-=c-e.length(),f-=c-e.length();if(void 0===d&&l===s.Class.UNIVERSAL&&p===s.Type.BITSTRING&&(y=e.bytes(f)),void 0===d&&i.decodeBitStrings&&l===s.Class.UNIVERSAL&&p===s.Type.BITSTRING&&f>1){var v=e.read,m=t,C=0;if(p===s.Type.BITSTRING&&(a(e,t,1),C=e.getByte(),t--),0===C)try{c=e.length();var E={verbose:i.verbose,strict:!0,decodeBitStrings:!0},S=n(e,t,r+1,E),T=c-e.length();t-=T,p==s.Type.BITSTRING&&T++;var I=S.tagClass;T!==f||I!==s.Class.UNIVERSAL&&I!==s.Class.CONTEXT_SPECIFIC||(d=[S])}catch(e){}void 0===d&&(e.read=v,t=m)}if(void 0===d){if(void 0===f){if(i.strict)throw new Error("Non-constructed ASN.1 object of indefinite length.");f=t}if(p===s.Type.BMPSTRING)for(d="";f>0;f-=2)a(e,t,2),d+=String.fromCharCode(e.getInt16()),t-=2;else d=e.getBytes(f)}var b=void 0===y?null:{bitStringContents:y};return s.create(l,p,g,d,b)}var i=r(0);r(1),r(6);var s=e.exports=i.asn1=i.asn1||{};s.Class={UNIVERSAL:0,APPLICATION:64,CONTEXT_SPECIFIC:128,PRIVATE:192},s.Type={NONE:0,BOOLEAN:1,INTEGER:2,BITSTRING:3,OCTETSTRING:4,NULL:5,OID:6,ODESC:7,EXTERNAL:8,REAL:9,ENUMERATED:10,EMBEDDED:11,UTF8:12,ROID:13,SEQUENCE:16,SET:17,PRINTABLESTRING:19,IA5STRING:22,UTCTIME:23,GENERALIZEDTIME:24,BMPSTRING:30},s.create=function(e,t,r,a,n){if(i.util.isArray(a)){for(var o=[],c=0;c1&&(0===e.value.charCodeAt(0)&&0==(128&e.value.charCodeAt(1))||255===e.value.charCodeAt(0)&&128==(128&e.value.charCodeAt(1)))?a.putBytes(e.value.substr(1)):a.putBytes(e.value);if(t.putByte(r),a.length()<=127)t.putByte(127&a.length());else{var c=a.length(),u="";do{u+=String.fromCharCode(255&c),c>>>=8}while(c>0);t.putByte(128|u.length);for(var o=u.length-1;o>=0;--o)t.putByte(u.charCodeAt(o))}return t.putBuffer(a),t},s.oidToDer=function(e){var t=e.split("."),r=i.util.createBuffer();r.putByte(40*parseInt(t[0],10)+parseInt(t[1],10));for(var a,n,s,o,c=2;c>>=7,a||(o|=128),n.push(o),a=!1}while(s>0);for(var u=n.length-1;u>=0;--u)r.putByte(n[u])}return r},s.derToOid=function(e){var t;"string"==typeof e&&(e=i.util.createBuffer(e));var r=e.getByte();t=Math.floor(r/40)+"."+r%40;for(var a=0;e.length()>0;)r=e.getByte(),a<<=7,128&r?a+=127&r:(t+="."+(a+r),a=0);return t},s.utcTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,2),10);r=r>=50?1900+r:2e3+r;var a=parseInt(e.substr(2,2),10)-1,n=parseInt(e.substr(4,2),10),i=parseInt(e.substr(6,2),10),s=parseInt(e.substr(8,2),10),o=0;if(e.length>11){var c=e.charAt(10),u=10;"+"!==c&&"-"!==c&&(o=parseInt(e.substr(10,2),10),u+=2)}if(t.setUTCFullYear(r,a,n),t.setUTCHours(i,s,o,0),u&&("+"===(c=e.charAt(u))||"-"===c)){var l=parseInt(e.substr(u+1,2),10),p=parseInt(e.substr(u+4,2),10),f=60*l+p;f*=6e4,"+"===c?t.setTime(+t-f):t.setTime(+t+f)}return t},s.generalizedTimeToDate=function(e){var t=new Date,r=parseInt(e.substr(0,4),10),a=parseInt(e.substr(4,2),10)-1,n=parseInt(e.substr(6,2),10),i=parseInt(e.substr(8,2),10),s=parseInt(e.substr(10,2),10),o=parseInt(e.substr(12,2),10),c=0,u=0,l=!1;"Z"===e.charAt(e.length-1)&&(l=!0);var p=e.length-5,f=e.charAt(p);if("+"===f||"-"===f){u=60*parseInt(e.substr(p+1,2),10)+parseInt(e.substr(p+4,2),10),u*=6e4,"+"===f&&(u*=-1),l=!0}return"."===e.charAt(14)&&(c=1e3*parseFloat(e.substr(14),10)),l?(t.setUTCFullYear(r,a,n),t.setUTCHours(i,s,o,c),t.setTime(+t+u)):(t.setFullYear(r,a,n),t.setHours(i,s,o,c)),t},s.dateToUtcTime=function(e){if("string"==typeof e)return e;var t="",r=[];r.push((""+e.getUTCFullYear()).substr(2)),r.push(""+(e.getUTCMonth()+1)),r.push(""+e.getUTCDate()),r.push(""+e.getUTCHours()),r.push(""+e.getUTCMinutes()),r.push(""+e.getUTCSeconds());for(var a=0;a=-128&&e<128)return t.putSignedInt(e,8);if(e>=-32768&&e<32768)return t.putSignedInt(e,16);if(e>=-8388608&&e<8388608)return t.putSignedInt(e,24);if(e>=-2147483648&&e<2147483648)return t.putSignedInt(e,32);var r=new Error("Integer too large; max is 32-bits.");throw r.integer=e,r},s.derToInteger=function(e){"string"==typeof e&&(e=i.util.createBuffer(e));var t=8*e.length();if(t>32)throw new Error("Integer too large; max is 32-bits.");return e.getSignedInt(t)},s.validate=function(e,t,r,a){var n=!1;if(e.tagClass!==t.tagClass&&void 0!==t.tagClass||e.type!==t.type&&void 0!==t.type)a&&(e.tagClass!==t.tagClass&&a.push("["+t.name+'] Expected tag class "'+t.tagClass+'", got "'+e.tagClass+'"'),e.type!==t.type&&a.push("["+t.name+'] Expected type "'+t.type+'", got "'+e.type+'"'));else if(e.constructed===t.constructed||void 0===t.constructed){if(n=!0,t.value&&i.util.isArray(t.value))for(var o=0,c=0;n&&c0&&(a+="\n");for(var n="",o=0;o1?a+="0x"+i.util.bytesToHex(e.value.slice(1)):a+="(none)",e.value.length>0){var f=e.value.charCodeAt(0);1==f?a+=" (1 unused bit shown)":f>1&&(a+=" ("+f+" unused bits shown)")}}else e.type===s.Type.OCTETSTRING?(c.test(e.value)||(a+="("+e.value+") "),a+="0x"+i.util.bytesToHex(e.value)):e.type===s.Type.UTF8?a+=i.util.decodeUtf8(e.value):e.type===s.Type.PRINTABLESTRING||e.type===s.Type.IA5String?a+=e.value:c.test(e.value)?a+="0x"+i.util.bytesToHex(e.value):0===e.value.length?a+="[null]":a+=e.value}return a}},function(e,t,r){var a=r(0);e.exports=a.md=a.md||{},a.md.algorithms=a.md.algorithms||{}},function(e,t,r){function a(e,t){var r=function(){return new c.aes.Algorithm(e,t)};c.cipher.registerAlgorithm(e,r)}function n(){d=!0,p=[0,1,2,4,8,16,32,64,128,27,54];for(var e=new Array(256),t=0;t<128;++t)e[t]=t<<1,e[t+128]=t+128<<1^283;u=new Array(256),l=new Array(256),f=new Array(4),h=new Array(4);for(var t=0;t<4;++t)f[t]=new Array(256),h[t]=new Array(256);for(var r,a,n,i,s,o,c,y=0,g=0,t=0;t<256;++t){i=g^g<<1^g<<2^g<<3^g<<4,i=i>>8^255&i^99,u[y]=i,l[i]=y,s=e[i],r=e[y],a=e[r],n=e[a],o=s<<24^i<<16^i<<8^i^s,c=(r^a^n)<<24^(y^n)<<16^(y^a^n)<<8^y^r^n;for(var v=0;v<4;++v)f[v][y]=o,h[v][i]=c,o=o<<24|o>>>8,c=c<<24|c>>>8;0===y?y=g=1:(y=r^e[e[e[r^n]]],g^=e[e[g]])}}function i(e,t){for(var r,a=e.slice(0),n=1,i=a.length,s=i+6+1,o=y*s,c=i;c>>16&255]<<24^u[r>>>8&255]<<16^u[255&r]<<8^u[r>>>24]^p[n]<<24,n++):i>6&&c%i==4&&(r=u[r>>>24]<<24^u[r>>>16&255]<<16^u[r>>>8&255]<<8^u[255&r]),a[c]=a[c-i]^r;if(t){var l,f=h[0],d=h[1],g=h[2],v=h[3],m=a.slice(0);o=a.length;for(var c=0,C=o-y;c>>24]]^d[u[l>>>16&255]]^g[u[l>>>8&255]]^v[u[255&l]];a=m}return a}function s(e,t,r,a){var n,i,s,o,c,p=e.length/4-1;a?(n=h[0],i=h[1],s=h[2],o=h[3],c=l):(n=f[0],i=f[1],s=f[2],o=f[3],c=u);var d,y,g,v,m,C,E;d=t[0]^e[0],y=t[a?3:1]^e[1],g=t[2]^e[2],v=t[a?1:3]^e[3];for(var S=3,T=1;T>>24]^i[y>>>16&255]^s[g>>>8&255]^o[255&v]^e[++S],C=n[y>>>24]^i[g>>>16&255]^s[v>>>8&255]^o[255&d]^e[++S],E=n[g>>>24]^i[v>>>16&255]^s[d>>>8&255]^o[255&y]^e[++S],v=n[v>>>24]^i[d>>>16&255]^s[y>>>8&255]^o[255&g]^e[++S],d=m,y=C,g=E;r[0]=c[d>>>24]<<24^c[y>>>16&255]<<16^c[g>>>8&255]<<8^c[255&v]^e[++S],r[a?3:1]=c[y>>>24]<<24^c[g>>>16&255]<<16^c[v>>>8&255]<<8^c[255&d]^e[++S],r[2]=c[g>>>24]<<24^c[v>>>16&255]<<16^c[d>>>8&255]<<8^c[255&y]^e[++S],r[a?1:3]=c[v>>>24]<<24^c[d>>>16&255]<<16^c[y>>>8&255]<<8^c[255&g]^e[++S]}function o(e){e=e||{};var t,r=(e.mode||"CBC").toUpperCase(),a="AES-"+r;t=e.decrypt?c.cipher.createDecipher(a,e.key):c.cipher.createCipher(a,e.key);var n=t.start;return t.start=function(e,r){var a=null;r instanceof c.util.ByteBuffer&&(a=r,r={}),r=r||{},r.output=a,r.iv=e,n.call(t,r)},t}var c=r(0);r(13),r(19),r(1),e.exports=c.aes=c.aes||{},c.aes.startEncrypting=function(e,t,r,a){var n=o({key:e,output:r,decrypt:!1,mode:a});return n.start(t),n},c.aes.createEncryptionCipher=function(e,t){return o({key:e,output:null,decrypt:!1,mode:t})},c.aes.startDecrypting=function(e,t,r,a){var n=o({key:e,output:r,decrypt:!0,mode:a});return n.start(t),n},c.aes.createDecryptionCipher=function(e,t){return o({key:e,output:null,decrypt:!0,mode:t})},c.aes.Algorithm=function(e,t){d||n();var r=this;r.name=e,r.mode=new t({blockSize:16,cipher:{encrypt:function(e,t){return s(r._w,e,t,!1)},decrypt:function(e,t){return s(r._w,e,t,!0)}}}),r._init=!1},c.aes.Algorithm.prototype.initialize=function(e){if(!this._init){var t,r=e.key;if("string"!=typeof r||16!==r.length&&24!==r.length&&32!==r.length){if(c.util.isArray(r)&&(16===r.length||24===r.length||32===r.length)){t=r,r=c.util.createBuffer();for(var a=0;a>>=2;for(var a=0;a65&&-1!==s){var o=t[s];","===o?(++s,t=t.substr(0,s)+"\r\n "+t.substr(s)):t=t.substr(0,s)+"\r\n"+o+t.substr(s+1),i=n-s-1,s=-1,++n}else" "!==t[n]&&"\t"!==t[n]&&","!==t[n]||(s=n);return t}function n(e){return e.replace(/^\s+/,"")}var i=r(0);r(1);var s=e.exports=i.pem=i.pem||{};s.encode=function(e,t){t=t||{};var r,n="-----BEGIN "+e.type+"-----\r\n";if(e.procType&&(r={name:"Proc-Type",values:[String(e.procType.version),e.procType.type]},n+=a(r)),e.contentDomain&&(r={name:"Content-Domain",values:[e.contentDomain]},n+=a(r)),e.dekInfo&&(r={name:"DEK-Info",values:[e.dekInfo.algorithm]},e.dekInfo.parameters&&r.values.push(e.dekInfo.parameters),n+=a(r)),e.headers)for(var s=0;st.blockLength&&(t.start(),t.update(s.bytes()),s=t.digest()),r=a.util.createBuffer(),n=a.util.createBuffer(),u=s.length();for(var c=0;c=64;){for(n=e.h0,i=e.h1,s=e.h2,o=e.h3,c=e.h4,l=0;l<16;++l)a=r.getInt32(),t[l]=a,u=o^i&(s^o),a=(n<<5|n>>>27)+u+c+1518500249+a,c=o,o=s,s=(i<<30|i>>>2)>>>0,i=n,n=a;for(;l<20;++l)a=t[l-3]^t[l-8]^t[l-14]^t[l-16],a=a<<1|a>>>31,t[l]=a,u=o^i&(s^o),a=(n<<5|n>>>27)+u+c+1518500249+a,c=o,o=s,s=(i<<30|i>>>2)>>>0,i=n,n=a;for(;l<32;++l)a=t[l-3]^t[l-8]^t[l-14]^t[l-16],a=a<<1|a>>>31,t[l]=a,u=i^s^o,a=(n<<5|n>>>27)+u+c+1859775393+a,c=o,o=s,s=(i<<30|i>>>2)>>>0,i=n,n=a;for(;l<40;++l)a=t[l-6]^t[l-16]^t[l-28]^t[l-32],a=a<<2|a>>>30,t[l]=a,u=i^s^o,a=(n<<5|n>>>27)+u+c+1859775393+a,c=o,o=s,s=(i<<30|i>>>2)>>>0,i=n,n=a;for(;l<60;++l)a=t[l-6]^t[l-16]^t[l-28]^t[l-32],a=a<<2|a>>>30,t[l]=a,u=i&s|o&(i^s),a=(n<<5|n>>>27)+u+c+2400959708+a,c=o,o=s,s=(i<<30|i>>>2)>>>0,i=n,n=a;for(;l<80;++l)a=t[l-6]^t[l-16]^t[l-28]^t[l-32],a=a<<2|a>>>30,t[l]=a,u=i^s^o,a=(n<<5|n>>>27)+u+c+3395469782+a,c=o,o=s,s=(i<<30|i>>>2)>>>0,i=n,n=a;e.h0=e.h0+n|0,e.h1=e.h1+i|0,e.h2=e.h2+s|0,e.h3=e.h3+o|0,e.h4=e.h4+c|0,p-=64}}var i=r(0);r(4),r(1);var s=e.exports=i.sha1=i.sha1||{};i.md.sha1=i.md.algorithms.sha1=s,s.create=function(){c||a();var e=null,t=i.util.createBuffer(),r=new Array(80),s={algorithm:"sha1",blockLength:64,digestLength:20,messageLength:0,fullMessageLength:null,messageLengthSize:8};return s.start=function(){s.messageLength=0,s.fullMessageLength=s.messageLength64=[];for(var r=s.messageLengthSize/4,a=0;a>>0,c>>>0];for(var u=s.fullMessageLength.length-1;u>=0;--u)s.fullMessageLength[u]+=c[1],c[1]=c[0]+(s.fullMessageLength[u]/4294967296>>>0),s.fullMessageLength[u]=s.fullMessageLength[u]>>>0,c[0]=c[1]/4294967296>>>0;return t.putBytes(a),n(e,r,t),(t.read>2048||0===t.length())&&t.compact(),s},s.digest=function(){var a=i.util.createBuffer();a.putBytes(t.bytes());var c=s.fullMessageLength[s.fullMessageLength.length-1]+s.messageLengthSize,u=c&s.blockLength-1;a.putBytes(o.substr(0,s.blockLength-u));for(var l,p,f=8*s.fullMessageLength[0],h=0;h>>0,f+=p,a.putInt32(f>>>0),f=l>>>0;a.putInt32(f);var d={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4};n(d,r,a);var y=i.util.createBuffer();return y.putInt32(d.h0),y.putInt32(d.h1),y.putInt32(d.h2),y.putInt32(d.h3),y.putInt32(d.h4),y},s};var o=null,c=!1},function(e,t,r){function a(e,t){var r=function(){return new o.des.Algorithm(e,t)};o.cipher.registerAlgorithm(e,r)}function n(e){for(var t,r=[0,4,536870912,536870916,65536,65540,536936448,536936452,512,516,536871424,536871428,66048,66052,536936960,536936964],a=[0,1,1048576,1048577,67108864,67108865,68157440,68157441,256,257,1048832,1048833,67109120,67109121,68157696,68157697],n=[0,8,2048,2056,16777216,16777224,16779264,16779272,0,8,2048,2056,16777216,16777224,16779264,16779272],i=[0,2097152,134217728,136314880,8192,2105344,134225920,136323072,131072,2228224,134348800,136445952,139264,2236416,134356992,136454144],s=[0,262144,16,262160,0,262144,16,262160,4096,266240,4112,266256,4096,266240,4112,266256],o=[0,1024,32,1056,0,1024,32,1056,33554432,33555456,33554464,33555488,33554432,33555456,33554464,33555488],c=[0,268435456,524288,268959744,2,268435458,524290,268959746,0,268435456,524288,268959744,2,268435458,524290,268959746],u=[0,65536,2048,67584,536870912,536936448,536872960,536938496,131072,196608,133120,198656,537001984,537067520,537004032,537069568],l=[0,262144,0,262144,2,262146,2,262146,33554432,33816576,33554432,33816576,33554434,33816578,33554434,33816578],p=[0,268435456,8,268435464,0,268435456,8,268435464,1024,268436480,1032,268436488,1024,268436480,1032,268436488],f=[0,32,0,32,1048576,1048608,1048576,1048608,8192,8224,8192,8224,1056768,1056800,1056768,1056800],h=[0,16777216,512,16777728,2097152,18874368,2097664,18874880,67108864,83886080,67109376,83886592,69206016,85983232,69206528,85983744],d=[0,4096,134217728,134221824,524288,528384,134742016,134746112,16,4112,134217744,134221840,524304,528400,134742032,134746128],y=[0,4,256,260,0,4,256,260,1,5,257,261,1,5,257,261],g=e.length()>8?3:1,v=[],m=[0,0,1,1,1,1,1,1,0,1,1,1,1,1,1,0],C=0,E=0;E>>4^T),T^=t,S^=t<<4,t=65535&(T>>>-16^S),S^=t,T^=t<<-16,t=858993459&(S>>>2^T),T^=t,S^=t<<2,t=65535&(T>>>-16^S),S^=t,T^=t<<-16,t=1431655765&(S>>>1^T),T^=t,S^=t<<1,t=16711935&(T>>>8^S),S^=t,T^=t<<8,t=1431655765&(S>>>1^T),T^=t,S^=t<<1,t=S<<8|T>>>20&240,S=T<<24|T<<8&16711680|T>>>8&65280|T>>>24&240,T=t;for(var I=0;I>>26,T=T<<2|T>>>26):(S=S<<1|S>>>27,T=T<<1|T>>>27),S&=-15,T&=-15;var b=r[S>>>28]|a[S>>>24&15]|n[S>>>20&15]|i[S>>>16&15]|s[S>>>12&15]|o[S>>>8&15]|c[S>>>4&15],A=u[T>>>28]|l[T>>>24&15]|p[T>>>20&15]|f[T>>>16&15]|h[T>>>12&15]|d[T>>>8&15]|y[T>>>4&15];t=65535&(A>>>16^b),v[C++]=b^t,v[C++]=A^t<<16}}return v}function i(e,t,r,a){var n,i=32===e.length?3:9;n=3===i?a?[30,-2,-2]:[0,32,2]:a?[94,62,-2,32,64,2,30,-2,-2]:[0,32,2,62,30,-2,64,96,2];var s,o=t[0],g=t[1];s=252645135&(o>>>4^g),g^=s,o^=s<<4,s=65535&(o>>>16^g),g^=s,o^=s<<16,s=858993459&(g>>>2^o),o^=s,g^=s<<2,s=16711935&(g>>>8^o),o^=s,g^=s<<8,s=1431655765&(o>>>1^g),g^=s,o^=s<<1,o=o<<1|o>>>31,g=g<<1|g>>>31;for(var v=0;v>>4|g<<28)^e[E+1];s=o,o=g,g=s^(u[S>>>24&63]|p[S>>>16&63]|h[S>>>8&63]|y[63&S]|c[T>>>24&63]|l[T>>>16&63]|f[T>>>8&63]|d[63&T])}s=o,o=g,g=s}o=o>>>1|o<<31,g=g>>>1|g<<31,s=1431655765&(o>>>1^g),g^=s,o^=s<<1,s=16711935&(g>>>8^o),o^=s,g^=s<<8,s=858993459&(g>>>2^o),o^=s,g^=s<<2,s=65535&(o>>>16^g),g^=s,o^=s<<16,s=252645135&(o>>>4^g),g^=s,o^=s<<4,r[0]=o,r[1]=g}function s(e){e=e||{};var t,r=(e.mode||"CBC").toUpperCase(),a="DES-"+r;t=e.decrypt?o.cipher.createDecipher(a,e.key):o.cipher.createCipher(a,e.key);var n=t.start;return t.start=function(e,r){var a=null;r instanceof o.util.ByteBuffer&&(a=r,r={}),r=r||{},r.output=a,r.iv=e,n.call(t,r)},t}var o=r(0);r(13),r(19),r(1),e.exports=o.des=o.des||{},o.des.startEncrypting=function(e,t,r,a){var n=s({key:e,output:r,decrypt:!1,mode:a||(null===t?"ECB":"CBC")});return n.start(t),n},o.des.createEncryptionCipher=function(e,t){return s({key:e,output:null,decrypt:!1,mode:t})},o.des.startDecrypting=function(e,t,r,a){var n=s({key:e,output:r,decrypt:!0,mode:a||(null===t?"ECB":"CBC")});return n.start(t),n},o.des.createDecryptionCipher=function(e,t){return s({key:e,output:null,decrypt:!0,mode:t})},o.des.Algorithm=function(e,t){var r=this;r.name=e,r.mode=new t({blockSize:8,cipher:{encrypt:function(e,t){return i(r._keys,e,t,!1)},decrypt:function(e,t){return i(r._keys,e,t,!0)}}}),r._init=!1},o.des.Algorithm.prototype.initialize=function(e){if(!this._init){var t=o.util.createBuffer(e.key);if(0===this.name.indexOf("3DES")&&24!==t.length())throw new Error("Invalid Triple-DES key size: "+8*t.length());this._keys=n(t),this._init=!0}},a("DES-ECB",o.cipher.modes.ecb),a("DES-CBC",o.cipher.modes.cbc),a("DES-CFB",o.cipher.modes.cfb),a("DES-OFB",o.cipher.modes.ofb),a("DES-CTR",o.cipher.modes.ctr),a("3DES-ECB",o.cipher.modes.ecb),a("3DES-CBC",o.cipher.modes.cbc),a("3DES-CFB",o.cipher.modes.cfb),a("3DES-OFB",o.cipher.modes.ofb),a("3DES-CTR",o.cipher.modes.ctr);var c=[16843776,0,65536,16843780,16842756,66564,4,65536,1024,16843776,16843780,1024,16778244,16842756,16777216,4,1028,16778240,16778240,66560,66560,16842752,16842752,16778244,65540,16777220,16777220,65540,0,1028,66564,16777216,65536,16843780,4,16842752,16843776,16777216,16777216,1024,16842756,65536,66560,16777220,1024,4,16778244,66564,16843780,65540,16842752,16778244,16777220,1028,66564,16843776,1028,16778240,16778240,0,65540,66560,0,16842756],u=[-2146402272,-2147450880,32768,1081376,1048576,32,-2146435040,-2147450848,-2147483616,-2146402272,-2146402304,-2147483648,-2147450880,1048576,32,-2146435040,1081344,1048608,-2147450848,0,-2147483648,32768,1081376,-2146435072,1048608,-2147483616,0,1081344,32800,-2146402304,-2146435072,32800,0,1081376,-2146435040,1048576,-2147450848,-2146435072,-2146402304,32768,-2146435072,-2147450880,32,-2146402272,1081376,32,32768,-2147483648,32800,-2146402304,1048576,-2147483616,1048608,-2147450848,-2147483616,1048608,1081344,0,-2147450880,32800,-2147483648,-2146435040,-2146402272,1081344],l=[520,134349312,0,134348808,134218240,0,131592,134218240,131080,134217736,134217736,131072,134349320,131080,134348800,520,134217728,8,134349312,512,131584,134348800,134348808,131592,134218248,131584,131072,134218248,8,134349320,512,134217728,134349312,134217728,131080,520,131072,134349312,134218240,0,512,131080,134349320,134218240,134217736,512,0,134348808,134218248,131072,134217728,134349320,8,131592,131584,134217736,134348800,134218248,520,134348800,131592,8,134348808,131584],p=[8396801,8321,8321,128,8396928,8388737,8388609,8193,0,8396800,8396800,8396929,129,0,8388736,8388609,1,8192,8388608,8396801,128,8388608,8193,8320,8388737,1,8320,8388736,8192,8396928,8396929,129,8388736,8388609,8396800,8396929,129,0,0,8396800,8320,8388736,8388737,1,8396801,8321,8321,128,8396929,129,1,8192,8388609,8193,8396928,8388737,8193,8320,8388608,8396801,128,8388608,8192,8396928],f=[256,34078976,34078720,1107296512,524288,256,1073741824,34078720,1074266368,524288,33554688,1074266368,1107296512,1107820544,524544,1073741824,33554432,1074266112,1074266112,0,1073742080,1107820800,1107820800,33554688,1107820544,1073742080,0,1107296256,34078976,33554432,1107296256,524544,524288,1107296512,256,33554432,1073741824,34078720,1107296512,1074266368,33554688,1073741824,1107820544,34078976,1074266368,256,33554432,1107820544,1107820800,524544,1107296256,1107820800,34078720,0,1074266112,1107296256,524544,33554688,1073742080,524288,0,1074266112,34078976,1073742080],h=[536870928,541065216,16384,541081616,541065216,16,541081616,4194304,536887296,4210704,4194304,536870928,4194320,536887296,536870912,16400,0,4194320,536887312,16384,4210688,536887312,16,541065232,541065232,0,4210704,541081600,16400,4210688,541081600,536870912,536887296,16,541065232,4210688,541081616,4194304,16400,536870928,4194304,536887296,536870912,16400,536870928,541081616,4210688,541065216,4210704,541081600,0,541065232,16,16384,541065216,4210704,16384,4194320,536887312,0,541081600,536870912,4194320,536887312],d=[2097152,69206018,67110914,0,2048,67110914,2099202,69208064,69208066,2097152,0,67108866,2,67108864,69206018,2050,67110912,2099202,2097154,67110912,67108866,69206016,69208064,2097154,69206016,2048,2050,69208066,2099200,2,67108864,2099200,67108864,2099200,2097152,67110914,67110914,69206018,69206018,2,2097154,67108864,67110912,2097152,69208064,2050,2099202,69208064,2050,67108866,69208066,69206016,2099200,0,2,69208066,0,2099202,69206016,2048,67108866,67110912,2048,2097154],y=[268439616,4096,262144,268701760,268435456,268439616,64,268435456,262208,268697600,268701760,266240,268701696,266304,4096,64,268697600,268435520,268439552,4160,266240,262208,268697664,268701696,4160,0,0,268697664,268435520,268439552,266304,262144,266304,262144,268701696,4096,64,268697664,4096,266304,268439552,64,268435520,268697600,268697664,268435456,262144,268439616,0,268701760,262208,268435520,268697600,268439552,268439616,0,268701760,266240,266240,4160,4160,262208,268435456,268701696]},function(e,t,r){function a(e,t,r){var a=f.util.createBuffer(),n=Math.ceil(t.n.bitLength()/8);if(e.length>n-11){var i=new Error("Message is too long for PKCS#1 v1.5 padding.");throw i.length=e.length,i.max=n-11,i}a.putByte(0),a.putByte(r);var s,o=n-3-e.length;if(0===r||1===r){s=0===r?0:255;for(var c=0;c0;){for(var u=0,l=f.random.getBytes(o),c=0;c1;){if(255!==i.getByte()){--i.read;break}++c}else if(2===o)for(c=0;i.length()>1;){if(0===i.getByte()){--i.read;break}++c}if(0!==i.getByte()||c!==n-3-i.length())throw new Error("Encryption block is invalid.");return i.getBytes()}function i(e,t,r){function a(){n(e.pBits,function(t,a){return t?r(t):(e.p=a,null!==e.q?i(t,e.q):void n(e.qBits,i))})}function n(e,t){f.prime.generateProbablePrime(e,s,t)}function i(t,s){if(t)return r(t);if(e.q=s,e.p.compareTo(e.q)<0){var o=e.p;e.p=e.q,e.q=o}if(0!==e.p.subtract(h.ONE).gcd(e.e).compareTo(h.ONE))return e.p=null,void a();if(0!==e.q.subtract(h.ONE).gcd(e.e).compareTo(h.ONE))return e.q=null,void n(e.qBits,i);if(e.p1=e.p.subtract(h.ONE),e.q1=e.q.subtract(h.ONE),e.phi=e.p1.multiply(e.q1),0!==e.phi.gcd(e.e).compareTo(h.ONE))return e.p=e.q=null,void a();if(e.n=e.p.multiply(e.q),e.n.bitLength()!==e.bits)return e.q=null,void n(e.qBits,i);var c=e.e.modInverse(e.phi);e.keys={privateKey:v.rsa.setPrivateKey(e.n,e.e,c,e.p,e.q,c.mod(e.p1),c.mod(e.q1),e.q.modInverse(e.p)),publicKey:v.rsa.setPublicKey(e.n,e.e)},r(null,e.keys)}"function"==typeof t&&(r=t,t={}),t=t||{};var s={algorithm:{name:t.algorithm||"PRIMEINC",options:{workers:t.workers||2,workLoad:t.workLoad||100,workerScript:t.workerScript}}};"prng"in t&&(s.prng=t.prng),a()}function s(e){var t=e.toString(16);t[0]>="8"&&(t="00"+t);var r=f.util.hexToBytes(t);return r.length>1&&(0===r.charCodeAt(0)&&0==(128&r.charCodeAt(1))||255===r.charCodeAt(0)&&128==(128&r.charCodeAt(1)))?r.substr(1):r}function o(e){return e<=100?27:e<=150?18:e<=200?15:e<=250?12:e<=300?9:e<=350?8:e<=400?7:e<=500?6:e<=600?5:e<=800?4:e<=1250?3:2}function c(e){return f.util.isNodejs&&"function"==typeof d[e]}function u(e){return void 0!==g.globalScope&&"object"==typeof g.globalScope.crypto&&"object"==typeof g.globalScope.crypto.subtle&&"function"==typeof g.globalScope.crypto.subtle[e]}function l(e){return void 0!==g.globalScope&&"object"==typeof g.globalScope.msCrypto&&"object"==typeof g.globalScope.msCrypto.subtle&&"function"==typeof g.globalScope.msCrypto.subtle[e]}function p(e){for(var t=f.util.hexToBytes(e.toString(16)),r=new Uint8Array(t.length),a=0;a=0||!a.gcd(t.n).equals(h.ONE));e=e.multiply(a.modPow(t.e,t.n)).mod(t.n);for(var n=e.mod(t.p).modPow(t.dP,t.p),i=e.mod(t.q).modPow(t.dQ,t.q);n.compareTo(i)<0;)n=n.add(t.p);var s=n.subtract(i).multiply(t.qInv).mod(t.p).multiply(t.q).add(i);return s=s.multiply(a.modInverse(t.n)).mod(t.n)};v.rsa.encrypt=function(e,t,r){var n,i=r,s=Math.ceil(t.n.bitLength()/8);!1!==r&&!0!==r?(i=2===r,n=a(e,t,r)):(n=f.util.createBuffer(),n.putBytes(e));for(var o=new h(n.toHex(),16),c=b(o,t,i),u=c.toString(16),l=f.util.createBuffer(),p=s-Math.ceil(u.length/2);p>0;)l.putByte(0),--p;return l.putBytes(f.util.hexToBytes(u)),l.getBytes()},v.rsa.decrypt=function(e,t,r,a){var i=Math.ceil(t.n.bitLength()/8);if(e.length!==i){var s=new Error("Encrypted message length is invalid.");throw s.length=e.length,s.expected=i,s}var o=new h(f.util.createBuffer(e).toHex(),16);if(o.compareTo(t.n)>=0)throw new Error("Encrypted message is invalid.");for(var c=b(o,t,r),u=c.toString(16),l=f.util.createBuffer(),p=i-Math.ceil(u.length/2);p>0;)l.putByte(0),--p;return l.putBytes(f.util.hexToBytes(u)),!1!==a?n(l.getBytes(),t,r):l.getBytes()},v.rsa.createKeyPairGenerationState=function(e,t,r){"string"==typeof e&&(e=parseInt(e,10)),e=e||2048,r=r||{};var a,n=r.prng||f.random,i={nextBytes:function(e){for(var t=n.getBytesSync(e.length),r=0;r>1,pBits:e-(e>>1),pqState:0,num:null,keys:null},a.e.fromInt(a.eInt),a},v.rsa.stepKeyPairGenerationState=function(e,t){"algorithm"in e||(e.algorithm="PRIMEINC");var r=new h(null);r.fromInt(30);for(var a,n=0,i=function(e,t){return e|t},s=+new Date,c=0;null===e.keys&&(t<=0||cu?e.pqState=0:e.num.isProbablePrime(o(e.num.bitLength()))?++e.pqState:e.num.dAddOffset(m[n++%8],0):2===e.pqState?e.pqState=0===e.num.subtract(h.ONE).gcd(e.e).compareTo(h.ONE)?3:0:3===e.pqState&&(e.pqState=0,null===e.p?e.p=e.num:e.q=e.num,null!==e.p&&null!==e.q&&++e.state,e.num=null)}else if(1===e.state)e.p.compareTo(e.q)<0&&(e.num=e.p,e.p=e.q,e.q=e.num),++e.state;else if(2===e.state)e.p1=e.p.subtract(h.ONE),e.q1=e.q.subtract(h.ONE),e.phi=e.p1.multiply(e.q1),++e.state;else if(3===e.state)0===e.phi.gcd(e.e).compareTo(h.ONE)?++e.state:(e.p=null,e.q=null,e.state=0);else if(4===e.state)e.n=e.p.multiply(e.q),e.n.bitLength()===e.bits?++e.state:(e.q=null,e.state=0);else if(5===e.state){var p=e.e.modInverse(e.phi);e.keys={privateKey:v.rsa.setPrivateKey(e.n,e.e,p,e.p,e.q,p.mod(e.p1),p.mod(e.q1),e.q.modInverse(e.p)),publicKey:v.rsa.setPublicKey(e.n,e.e)}}a=+new Date,c+=a-s,s=a}return null!==e.keys},v.rsa.generateKeyPair=function(e,t,r,a){if(1===arguments.length?"object"==typeof e?(r=e,e=void 0):"function"==typeof e&&(a=e,e=void 0):2===arguments.length?"number"==typeof e?"function"==typeof t?(a=t,t=void 0):"number"!=typeof t&&(r=t,t=void 0):(r=e,a=t,e=void 0,t=void 0):3===arguments.length&&("number"==typeof t?"function"==typeof r&&(a=r,r=void 0):(a=r,r=t,t=void 0)),r=r||{},void 0===e&&(e=r.bits||2048),void 0===t&&(t=r.e||65537),!f.options.usePureJavaScript&&!r.prng&&e>=256&&e<=16384&&(65537===t||3===t))if(a){if(c("generateKeyPair"))return d.generateKeyPair("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}},function(e,t,r){if(e)return a(e);a(null,{privateKey:v.privateKeyFromPem(r),publicKey:v.publicKeyFromPem(t)})});if(u("generateKey")&&u("exportKey"))return g.globalScope.crypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:p(t),hash:{name:"SHA-256"}},!0,["sign","verify"]).then(function(e){return g.globalScope.crypto.subtle.exportKey("pkcs8",e.privateKey)}).then(void 0,function(e){a(e)}).then(function(e){if(e){var t=v.privateKeyFromAsn1(y.fromDer(f.util.createBuffer(e)));a(null,{privateKey:t,publicKey:v.setRsaPublicKey(t.n,t.e)})}});if(l("generateKey")&&l("exportKey")){var n=g.globalScope.msCrypto.subtle.generateKey({name:"RSASSA-PKCS1-v1_5",modulusLength:e,publicExponent:p(t),hash:{name:"SHA-256"}},!0,["sign","verify"]);return n.oncomplete=function(e){var t=e.target.result,r=g.globalScope.msCrypto.subtle.exportKey("pkcs8",t.privateKey);r.oncomplete=function(e){var t=e.target.result,r=v.privateKeyFromAsn1(y.fromDer(f.util.createBuffer(t)));a(null,{privateKey:r,publicKey:v.setRsaPublicKey(r.n,r.e)})},r.onerror=function(e){a(e)}},void(n.onerror=function(e){a(e)})}}else if(c("generateKeyPairSync")){var s=d.generateKeyPairSync("rsa",{modulusLength:e,publicExponent:t,publicKeyEncoding:{type:"spki",format:"pem"},privateKeyEncoding:{type:"pkcs8",format:"pem"}});return{privateKey:v.privateKeyFromPem(s.privateKey),publicKey:v.publicKeyFromPem(s.publicKey)}}var o=v.rsa.createKeyPairGenerationState(e,t,r);if(!a)return v.rsa.stepKeyPairGenerationState(o,0),o.keys;i(o,r,a)},v.setRsaPublicKey=v.rsa.setPublicKey=function(e,t){var r={n:e,e:t};return r.encrypt=function(e,t,n){if("string"==typeof t?t=t.toUpperCase():void 0===t&&(t="RSAES-PKCS1-V1_5"),"RSAES-PKCS1-V1_5"===t)t={encode:function(e,t,r){return a(e,t,2).getBytes()}};else if("RSA-OAEP"===t||"RSAES-OAEP"===t)t={encode:function(e,t){return f.pkcs1.encode_rsa_oaep(t,e,n)}};else if(-1!==["RAW","NONE","NULL",null].indexOf(t))t={encode:function(e){return e}};else if("string"==typeof t)throw new Error('Unsupported encryption scheme: "'+t+'".');var i=t.encode(e,r,!0);return v.rsa.encrypt(i,r,!0)},r.verify=function(e,t,a){"string"==typeof a?a=a.toUpperCase():void 0===a&&(a="RSASSA-PKCS1-V1_5"),"RSASSA-PKCS1-V1_5"===a?a={verify:function(e,t){return t=n(t,r,!0),e===y.fromDer(t).value[1].value}}:"NONE"!==a&&"NULL"!==a&&null!==a||(a={verify:function(e,t){return t=n(t,r,!0),e===t}});var i=v.rsa.decrypt(t,r,!0,!1);return a.verify(e,i,r.n.bitLength())},r},v.setRsaPrivateKey=v.rsa.setPrivateKey=function(e,t,r,a,i,s,o,c){var u={n:e,e:t,d:r,p:a,q:i,dP:s,dQ:o,qInv:c};return u.decrypt=function(e,t,r){"string"==typeof t?t=t.toUpperCase():void 0===t&&(t="RSAES-PKCS1-V1_5");var a=v.rsa.decrypt(e,u,!1,!1);if("RSAES-PKCS1-V1_5"===t)t={decode:n};else if("RSA-OAEP"===t||"RSAES-OAEP"===t)t={decode:function(e,t){return f.pkcs1.decode_rsa_oaep(t,e,r)}};else{if(-1===["RAW","NONE","NULL",null].indexOf(t))throw new Error('Unsupported encryption scheme: "'+t+'".');t={decode:function(e){return e}}}return t.decode(a,u,!1)},u.sign=function(e,t){var r=!1;"string"==typeof t&&(t=t.toUpperCase()),void 0===t||"RSASSA-PKCS1-V1_5"===t?(t={encode:I},r=1):"NONE"!==t&&"NULL"!==t&&null!==t||(t={encode:function(){return e}},r=1);var a=t.encode(e,u.n.bitLength());return v.rsa.encrypt(a,u,r)},u},v.wrapRsaPrivateKey=function(e){return y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,y.integerToDer(0).getBytes()),y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[y.create(y.Class.UNIVERSAL,y.Type.OID,!1,y.oidToDer(v.oids.rsaEncryption).getBytes()),y.create(y.Class.UNIVERSAL,y.Type.NULL,!1,"")]),y.create(y.Class.UNIVERSAL,y.Type.OCTETSTRING,!1,y.toDer(e).getBytes())])},v.privateKeyFromAsn1=function(e){var t={},r=[];if(y.validate(e,C,t,r)&&(e=y.fromDer(f.util.createBuffer(t.privateKey))),t={},r=[],!y.validate(e,E,t,r)){var a=new Error("Cannot read private key. ASN.1 object does not contain an RSAPrivateKey.");throw a.errors=r,a}var n,i,s,o,c,u,l,p;return n=f.util.createBuffer(t.privateKeyModulus).toHex(),i=f.util.createBuffer(t.privateKeyPublicExponent).toHex(),s=f.util.createBuffer(t.privateKeyPrivateExponent).toHex(),o=f.util.createBuffer(t.privateKeyPrime1).toHex(),c=f.util.createBuffer(t.privateKeyPrime2).toHex(),u=f.util.createBuffer(t.privateKeyExponent1).toHex(),l=f.util.createBuffer(t.privateKeyExponent2).toHex(),p=f.util.createBuffer(t.privateKeyCoefficient).toHex(),v.setRsaPrivateKey(new h(n,16),new h(i,16),new h(s,16),new h(o,16),new h(c,16),new h(u,16),new h(l,16),new h(p,16))},v.privateKeyToAsn1=v.privateKeyToRSAPrivateKey=function(e){return y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,y.integerToDer(0).getBytes()),y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,s(e.n)),y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,s(e.e)),y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,s(e.d)),y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,s(e.p)),y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,s(e.q)),y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,s(e.dP)),y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,s(e.dQ)),y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,s(e.qInv))])},v.publicKeyFromAsn1=function(e){var t={},r=[];if(y.validate(e,T,t,r)){var a=y.derToOid(t.publicKeyOid);if(a!==v.oids.rsaEncryption){var n=new Error("Cannot read public key. Unknown OID.");throw n.oid=a,n}e=t.rsaPublicKey}if(r=[],!y.validate(e,S,t,r)){var n=new Error("Cannot read public key. ASN.1 object does not contain an RSAPublicKey.");throw n.errors=r,n}var i=f.util.createBuffer(t.publicKeyModulus).toHex(),s=f.util.createBuffer(t.publicKeyExponent).toHex();return v.setRsaPublicKey(new h(i,16),new h(s,16))},v.publicKeyToAsn1=v.publicKeyToSubjectPublicKeyInfo=function(e){return y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[y.create(y.Class.UNIVERSAL,y.Type.OID,!1,y.oidToDer(v.oids.rsaEncryption).getBytes()),y.create(y.Class.UNIVERSAL,y.Type.NULL,!1,"")]),y.create(y.Class.UNIVERSAL,y.Type.BITSTRING,!1,[v.publicKeyToRSAPublicKey(e)])])},v.publicKeyToRSAPublicKey=function(e){return y.create(y.Class.UNIVERSAL,y.Type.SEQUENCE,!0,[y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,s(e.n)),y.create(y.Class.UNIVERSAL,y.Type.INTEGER,!1,s(e.e))])}},function(e,t,r){function a(e,t,r){this.data=[],null!=e&&("number"==typeof e?this.fromNumber(e,t,r):null==t&&"string"!=typeof e?this.fromString(e,256):this.fromString(e,t))}function n(){return new a(null)}function i(e,t,r,a,n,i){for(;--i>=0;){var s=t*this.data[e++]+r.data[a]+n;n=Math.floor(s/67108864),r.data[a++]=67108863&s}return n}function s(e,t,r,a,n,i){for(var s=32767&t,o=t>>15;--i>=0;){var c=32767&this.data[e],u=this.data[e++]>>15,l=o*c+u*s;c=s*c+((32767&l)<<15)+r.data[a]+(1073741823&n),n=(c>>>30)+(l>>>15)+o*u+(n>>>30),r.data[a++]=1073741823&c}return n}function o(e,t,r,a,n,i){for(var s=16383&t,o=t>>14;--i>=0;){var c=16383&this.data[e],u=this.data[e++]>>14,l=o*c+u*s;c=s*c+((16383&l)<<14)+r.data[a]+n,n=(c>>28)+(l>>14)+o*u,r.data[a++]=268435455&c}return n}function c(e){return it.charAt(e)}function u(e,t){var r=st[e.charCodeAt(t)];return null==r?-1:r}function l(e){for(var t=this.t-1;t>=0;--t)e.data[t]=this.data[t];e.t=this.t,e.s=this.s}function p(e){this.t=1,this.s=e<0?-1:0,e>0?this.data[0]=e:e<-1?this.data[0]=e+this.DV:this.t=0}function f(e){var t=n();return t.fromInt(e),t}function h(e,t){var r;if(16==t)r=4;else if(8==t)r=3;else if(256==t)r=8;else if(2==t)r=1;else if(32==t)r=5;else{if(4!=t)return void this.fromRadix(e,t);r=2}this.t=0,this.s=0;for(var n=e.length,i=!1,s=0;--n>=0;){var o=8==r?255&e[n]:u(e,n);o<0?"-"==e.charAt(n)&&(i=!0):(i=!1,0==s?this.data[this.t++]=o:s+r>this.DB?(this.data[this.t-1]|=(o&(1<>this.DB-s):this.data[this.t-1]|=o<=this.DB&&(s-=this.DB))}8==r&&0!=(128&e[0])&&(this.s=-1,s>0&&(this.data[this.t-1]|=(1<0&&this.data[this.t-1]==e;)--this.t}function y(e){if(this.s<0)return"-"+this.negate().toString(e);var t;if(16==e)t=4;else if(8==e)t=3;else if(2==e)t=1;else if(32==e)t=5;else{if(4!=e)return this.toRadix(e);t=2}var r,a=(1<0)for(o>o)>0&&(n=!0,i=c(r));s>=0;)o>(o+=this.DB-t)):(r=this.data[s]>>(o-=t)&a,o<=0&&(o+=this.DB,--s)),r>0&&(n=!0),n&&(i+=c(r));return n?i:"0"}function g(){var e=n();return a.ZERO.subTo(this,e),e}function v(){return this.s<0?this.negate():this}function m(e){var t=this.s-e.s;if(0!=t)return t;var r=this.t;if(0!=(t=r-e.t))return this.s<0?-t:t;for(;--r>=0;)if(0!=(t=this.data[r]-e.data[r]))return t;return 0}function C(e){var t,r=1;return 0!=(t=e>>>16)&&(e=t,r+=16),0!=(t=e>>8)&&(e=t,r+=8),0!=(t=e>>4)&&(e=t,r+=4),0!=(t=e>>2)&&(e=t,r+=2),0!=(t=e>>1)&&(e=t,r+=1),r}function E(){return this.t<=0?0:this.DB*(this.t-1)+C(this.data[this.t-1]^this.s&this.DM)}function S(e,t){var r;for(r=this.t-1;r>=0;--r)t.data[r+e]=this.data[r];for(r=e-1;r>=0;--r)t.data[r]=0;t.t=this.t+e,t.s=this.s}function T(e,t){for(var r=e;r=0;--r)t.data[r+s+1]=this.data[r]>>n|o,o=(this.data[r]&i)<=0;--r)t.data[r]=0;t.data[s]=o,t.t=this.t+s+1,t.s=this.s,t.clamp()}function b(e,t){t.s=this.s;var r=Math.floor(e/this.DB);if(r>=this.t)return void(t.t=0);var a=e%this.DB,n=this.DB-a,i=(1<>a;for(var s=r+1;s>a;a>0&&(t.data[this.t-r-1]|=(this.s&i)<>=this.DB;if(e.t>=this.DB;a+=this.s}else{for(a+=this.s;r>=this.DB;a-=e.s}t.s=a<0?-1:0,a<-1?t.data[r++]=this.DV+a:a>0&&(t.data[r++]=a),t.t=r,t.clamp()}function B(e,t){var r=this.abs(),n=e.abs(),i=r.t;for(t.t=i+n.t;--i>=0;)t.data[i]=0;for(i=0;i=0;)e.data[r]=0;for(r=0;r=t.DV&&(e.data[r+t.t]-=t.DV,e.data[r+t.t+1]=1)}e.t>0&&(e.data[e.t-1]+=t.am(r,t.data[r],e,2*r,0,1)),e.s=0,e.clamp()}function k(e,t,r){var i=e.abs();if(!(i.t<=0)){var s=this.abs();if(s.t0?(i.lShiftTo(l,o),s.lShiftTo(l,r)):(i.copyTo(o),s.copyTo(r));var p=o.t,f=o.data[p-1];if(0!=f){var h=f*(1<1?o.data[p-2]>>this.F2:0),d=this.FV/h,y=(1<=0&&(r.data[r.t++]=1,r.subTo(E,r)),a.ONE.dlShiftTo(p,E),E.subTo(o,o);o.t=0;){var S=r.data[--v]==f?this.DM:Math.floor(r.data[v]*d+(r.data[v-1]+g)*y);if((r.data[v]+=o.am(0,S,r,m,0,p))0&&r.rShiftTo(l,r),c<0&&a.ZERO.subTo(r,r)}}}function w(e){var t=n();return this.abs().divRemTo(e,null,t),this.s<0&&t.compareTo(a.ZERO)>0&&e.subTo(t,t),t}function R(e){this.m=e}function _(e){return e.s<0||e.compareTo(this.m)>=0?e.mod(this.m):e}function L(e){return e}function U(e){e.divRemTo(this.m,null,e)}function D(e,t,r){e.multiplyTo(t,r),this.reduce(r)}function P(e,t){e.squareTo(t),this.reduce(t)}function V(){if(this.t<1)return 0;var e=this.data[0];if(0==(1&e))return 0;var t=3&e;return t=t*(2-(15&e)*t)&15,t=t*(2-(255&e)*t)&255,t=t*(2-((65535&e)*t&65535))&65535,t=t*(2-e*t%this.DV)%this.DV,t>0?this.DV-t:-t}function O(e){this.m=e,this.mp=e.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<0&&this.m.subTo(t,t),t}function x(e){var t=n();return e.copyTo(t),this.reduce(t),t}function M(e){for(;e.t<=this.mt2;)e.data[e.t++]=0;for(var t=0;t>15)*this.mpl&this.um)<<15)&e.DM;for(r=t+this.m.t,e.data[r]+=this.m.am(0,a,e,t,0,this.m.t);e.data[r]>=e.DV;)e.data[r]-=e.DV,e.data[++r]++}e.clamp(),e.drShiftTo(this.m.t,e),e.compareTo(this.m)>=0&&e.subTo(this.m,e)}function F(e,t){e.squareTo(t),this.reduce(t)}function j(e,t,r){e.multiplyTo(t,r),this.reduce(r)}function q(){return 0==(this.t>0?1&this.data[0]:this.s)}function G(e,t){if(e>4294967295||e<1)return a.ONE;var r=n(),i=n(),s=t.convert(this),o=C(e)-1;for(s.copyTo(r);--o>=0;)if(t.sqrTo(r,i),(e&1<0)t.mulTo(i,s,r);else{var c=r;r=i,i=c}return t.revert(r)}function H(e,t){var r;return r=e<256||t.isEven()?new R(t):new O(t),this.exp(e,r)}function Q(){var e=n();return this.copyTo(e),e}function z(){if(this.s<0){if(1==this.t)return this.data[0]-this.DV;if(0==this.t)return-1}else{if(1==this.t)return this.data[0];if(0==this.t)return 0}return(this.data[1]&(1<<32-this.DB)-1)<>24}function W(){return 0==this.t?this.s:this.data[0]<<16>>16}function X(e){return Math.floor(Math.LN2*this.DB/Math.log(e))}function Z(){return this.s<0?-1:this.t<=0||1==this.t&&this.data[0]<=0?0:1}function J(e){if(null==e&&(e=10),0==this.signum()||e<2||e>36)return"0";var t=this.chunkSize(e),r=Math.pow(e,t),a=f(r),i=n(),s=n(),o="";for(this.divRemTo(a,i,s);i.signum()>0;)o=(r+s.intValue()).toString(e).substr(1)+o,i.divRemTo(a,i,s);return s.intValue().toString(e)+o}function $(e,t){this.fromInt(0),null==t&&(t=10);for(var r=this.chunkSize(t),n=Math.pow(t,r),i=!1,s=0,o=0,c=0;c=r&&(this.dMultiply(n),this.dAddOffset(o,0),s=0,o=0))}s>0&&(this.dMultiply(Math.pow(t,s)),this.dAddOffset(o,0)),i&&a.ZERO.subTo(this,this)}function ee(e,t,r){if("number"==typeof t)if(e<2)this.fromInt(1);else for(this.fromNumber(e,r),this.testBit(e-1)||this.bitwiseTo(a.ONE.shiftLeft(e-1),ce,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(t);)this.dAddOffset(2,0),this.bitLength()>e&&this.subTo(a.ONE.shiftLeft(e-1),this);else{var n=new Array,i=7&e;n.length=1+(e>>3),t.nextBytes(n),i>0?n[0]&=(1<0)for(a>a)!=(this.s&this.DM)>>a&&(t[n++]=r|this.s<=0;)a<8?(r=(this.data[e]&(1<>(a+=this.DB-8)):(r=this.data[e]>>(a-=8)&255,a<=0&&(a+=this.DB,--e)),0!=(128&r)&&(r|=-256),0==n&&(128&this.s)!=(128&r)&&++n,(n>0||r!=this.s)&&(t[n++]=r);return t}function re(e){return 0==this.compareTo(e)}function ae(e){return this.compareTo(e)<0?this:e}function ne(e){return this.compareTo(e)>0?this:e}function ie(e,t,r){var a,n,i=Math.min(e.t,this.t);for(a=0;a>=16,t+=16),0==(255&e)&&(e>>=8,t+=8),0==(15&e)&&(e>>=4,t+=4),0==(3&e)&&(e>>=2,t+=2),0==(1&e)&&++t,t}function me(){for(var e=0;e=this.t?0!=this.s:0!=(this.data[t]&1<>=this.DB;if(e.t>=this.DB;a+=this.s}else{for(a+=this.s;r>=this.DB;a+=e.s}t.s=a<0?-1:0,a>0?t.data[r++]=a:a<-1&&(t.data[r++]=this.DV+a),t.t=r,t.clamp()}function Ne(e){var t=n();return this.addTo(e,t),t}function ke(e){var t=n();return this.subTo(e,t),t}function we(e){var t=n();return this.multiplyTo(e,t),t}function Re(e){var t=n();return this.divRemTo(e,t,null),t}function _e(e){var t=n();return this.divRemTo(e,null,t),t}function Le(e){var t=n(),r=n();return this.divRemTo(e,t,r),new Array(t,r)}function Ue(e){this.data[this.t]=this.am(0,e-1,this,0,0,this.t),++this.t,this.clamp()}function De(e,t){if(0!=e){for(;this.t<=t;)this.data[this.t++]=0;for(this.data[t]+=e;this.data[t]>=this.DV;)this.data[t]-=this.DV,++t>=this.t&&(this.data[this.t++]=0),++this.data[t]}}function Pe(){}function Ve(e){return e}function Oe(e,t,r){e.multiplyTo(t,r)}function Ke(e,t){e.squareTo(t)}function xe(e){return this.exp(e,new Pe)}function Me(e,t,r){var a=Math.min(this.t+e.t,t);for(r.s=0,r.t=a;a>0;)r.data[--a]=0;var n;for(n=r.t-this.t;a=0;)r.data[a]=0;for(a=Math.max(t-this.t,0);a2*this.m.t)return e.mod(this.m);if(e.compareTo(this.m)<0)return e;var t=n();return e.copyTo(t),this.reduce(t),t}function Ge(e){return e}function He(e){for(e.drShiftTo(this.m.t-1,this.r2),e.t>this.m.t+1&&(e.t=this.m.t+1,e.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);e.compareTo(this.r2)<0;)e.dAddOffset(1,this.m.t+1);for(e.subTo(this.r2,e);e.compareTo(this.m)>=0;)e.subTo(this.m,e)}function Qe(e,t){e.squareTo(t),this.reduce(t)}function ze(e,t,r){e.multiplyTo(t,r),this.reduce(r)}function Ye(e,t){var r,a,i=e.bitLength(),s=f(1);if(i<=0)return s;r=i<18?1:i<48?3:i<144?4:i<768?5:6,a=i<8?new R(t):t.isEven()?new je(t):new O(t);var o=new Array,c=3,u=r-1,l=(1<1){var p=n();for(a.sqrTo(o[1],p);c<=l;)o[c]=n(),a.mulTo(p,o[c-2],o[c]),c+=2}var h,d,y=e.t-1,g=!0,v=n();for(i=C(e.data[y])-1;y>=0;){for(i>=u?h=e.data[y]>>i-u&l:(h=(e.data[y]&(1<0&&(h|=e.data[y-1]>>this.DB+i-u)),c=r;0==(1&h);)h>>=1,--c;if((i-=c)<0&&(i+=this.DB,--y),g)o[h].copyTo(s),g=!1;else{for(;c>1;)a.sqrTo(s,v),a.sqrTo(v,s),c-=2;c>0?a.sqrTo(s,v):(d=s,s=v,v=d),a.mulTo(v,o[h],s)}for(;y>=0&&0==(e.data[y]&1<0&&(t.rShiftTo(i,t),r.rShiftTo(i,r));t.signum()>0;)(n=t.getLowestSetBit())>0&&t.rShiftTo(n,t),(n=r.getLowestSetBit())>0&&r.rShiftTo(n,r),t.compareTo(r)>=0?(t.subTo(r,t),t.rShiftTo(1,t)):(r.subTo(t,r),r.rShiftTo(1,r));return i>0&&r.lShiftTo(i,r),r}function Xe(e){if(e<=0)return 0;var t=this.DV%e,r=this.s<0?e-1:0;if(this.t>0)if(0==t)r=this.data[0]%e;else for(var a=this.t-1;a>=0;--a)r=(t*r+this.data[a])%e;return r}function Ze(e){var t=e.isEven();if(this.isEven()&&t||0==e.signum())return a.ZERO;for(var r=e.clone(),n=this.clone(),i=f(1),s=f(0),o=f(0),c=f(1);0!=r.signum();){for(;r.isEven();)r.rShiftTo(1,r),t?(i.isEven()&&s.isEven()||(i.addTo(this,i),s.subTo(e,s)),i.rShiftTo(1,i)):s.isEven()||s.subTo(e,s),s.rShiftTo(1,s);for(;n.isEven();)n.rShiftTo(1,n),t?(o.isEven()&&c.isEven()||(o.addTo(this,o),c.subTo(e,c)),o.rShiftTo(1,o)):c.isEven()||c.subTo(e,c),c.rShiftTo(1,c);r.compareTo(n)>=0?(r.subTo(n,r),t&&i.subTo(o,i),s.subTo(c,s)):(n.subTo(r,n),t&&o.subTo(i,o),c.subTo(s,c))}return 0!=n.compareTo(a.ONE)?a.ZERO:c.compareTo(e)>=0?c.subtract(e):c.signum()<0?(c.addTo(e,c),c.signum()<0?c.add(e):c):c}function Je(e){var t,r=this.abs();if(1==r.t&&r.data[0]<=ot[ot.length-1]){for(t=0;t=0);var c=n.modPow(i,this);if(0!=c.compareTo(a.ONE)&&0!=c.compareTo(t)){for(var u=1;u++=64;){for(n=e.h0,i=e.h1,s=e.h2,o=e.h3,h=0;h<16;++h)t[h]=r.getInt32Le(),p=o^i&(s^o),a=n+p+l[h]+t[h],f=u[h],n=o,o=s,s=i,i+=a<>>32-f;for(;h<32;++h)p=s^o&(i^s),a=n+p+l[h]+t[c[h]],f=u[h],n=o,o=s,s=i,i+=a<>>32-f;for(;h<48;++h)p=i^s^o,a=n+p+l[h]+t[c[h]],f=u[h],n=o,o=s,s=i,i+=a<>>32-f;for(;h<64;++h)p=s^(i|~o),a=n+p+l[h]+t[c[h]],f=u[h],n=o,o=s,s=i,i+=a<>>32-f;e.h0=e.h0+n|0,e.h1=e.h1+i|0,e.h2=e.h2+s|0,e.h3=e.h3+o|0,d-=64}}var i=r(0);r(4),r(1);var s=e.exports=i.md5=i.md5||{};i.md.md5=i.md.algorithms.md5=s,s.create=function(){p||a();var e=null,t=i.util.createBuffer(),r=new Array(16),s={algorithm:"md5",blockLength:64,digestLength:16,messageLength:0,fullMessageLength:null,messageLengthSize:8};return s.start=function(){s.messageLength=0,s.fullMessageLength=s.messageLength64=[];for(var r=s.messageLengthSize/4,a=0;a>>0,c>>>0];for(var u=s.fullMessageLength.length-1;u>=0;--u)s.fullMessageLength[u]+=c[1],c[1]=c[0]+(s.fullMessageLength[u]/4294967296>>>0),s.fullMessageLength[u]=s.fullMessageLength[u]>>>0,c[0]=c[1]/4294967296>>>0;return t.putBytes(a),n(e,r,t),(t.read>2048||0===t.length())&&t.compact(),s},s.digest=function(){var a=i.util.createBuffer();a.putBytes(t.bytes());var c=s.fullMessageLength[s.fullMessageLength.length-1]+s.messageLengthSize,u=c&s.blockLength-1;a.putBytes(o.substr(0,s.blockLength-u));for(var l,p=0,f=s.fullMessageLength.length-1;f>=0;--f)l=8*s.fullMessageLength[f]+p,p=l/4294967296>>>0,a.putInt32Le(l>>>0);var h={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3};n(h,r,a);var d=i.util.createBuffer();return d.putInt32Le(h.h0),d.putInt32Le(h.h1),d.putInt32Le(h.h2),d.putInt32Le(h.h3),d},s};var o=null,c=null,u=null,l=null,p=!1},function(e,t,r){var a=r(0);r(8),r(4),r(1);var n,i=a.pkcs5=a.pkcs5||{};a.util.isNodejs&&!a.options.usePureJavaScript&&(n=r(16)),e.exports=a.pbkdf2=i.pbkdf2=function(e,t,r,i,s,o){function c(){if(C>f)return o(null,m);d.start(null,null),d.update(t),d.update(a.util.int32ToBytes(C)),y=v=d.digest().getBytes(),E=2,u()}function u(){if(E<=r)return d.start(null,null),d.update(v),g=d.digest().getBytes(),y=a.util.xorBytes(y,g,l),v=g,++E,a.util.setImmediate(u);m+=C4||!s||"sha1"===s))return"string"!=typeof s&&(s="sha1"),e=Buffer.from(e,"binary"),t=Buffer.from(t,"binary"),o?4===n.pbkdf2Sync.length?n.pbkdf2(e,t,r,i,function(e,t){if(e)return o(e);o(null,t.toString("binary"))}):n.pbkdf2(e,t,r,i,s,function(e,t){if(e)return o(e);o(null,t.toString("binary"))}):4===n.pbkdf2Sync.length?n.pbkdf2Sync(e,t,r,i).toString("binary"):n.pbkdf2Sync(e,t,r,i,s).toString("binary");if(void 0!==s&&null!==s||(s="sha1"),"string"==typeof s){if(!(s in a.md.algorithms))throw new Error("Unknown hash algorithm: "+s);s=a.md[s].create()}var l=s.digestLength;if(i>4294967295*l){var p=new Error("Derived key is too long.");if(o)return o(p);throw p}var f=Math.ceil(i/l),h=i-(f-1)*l,d=a.hmac.create();d.start(s,e);var y,g,v,m="";if(!o){for(var C=1;C<=f;++C){d.start(null,null),d.update(t),d.update(a.util.int32ToBytes(C)),y=v=d.digest().getBytes();for(var E=2;E<=r;++E)d.start(null,null),d.update(v),g=d.digest().getBytes(),y=a.util.xorBytes(y,g,l),v=g;m+=C128)throw new Error('Invalid "nsComment" content.');e.value=p.create(p.Class.UNIVERSAL,p.Type.IA5STRING,!1,e.comment)}else if("subjectKeyIdentifier"===e.name&&t.cert){var g=t.cert.generateSubjectKeyIdentifier();e.subjectKeyIdentifier=g.toHex(),e.value=p.create(p.Class.UNIVERSAL,p.Type.OCTETSTRING,!1,g.getBytes())}else if("authorityKeyIdentifier"===e.name&&t.cert){e.value=p.create(p.Class.UNIVERSAL,p.Type.SEQUENCE,!0,[]);var c=e.value.value;if(e.keyIdentifier){var v=!0===e.keyIdentifier?t.cert.generateSubjectKeyIdentifier().getBytes():e.keyIdentifier;c.push(p.create(p.Class.CONTEXT_SPECIFIC,0,!1,v))}if(e.authorityCertIssuer){var m=[p.create(p.Class.CONTEXT_SPECIFIC,4,!0,[n(!0===e.authorityCertIssuer?t.cert.issuer:e.authorityCertIssuer)])];c.push(p.create(p.Class.CONTEXT_SPECIFIC,1,!0,m))}if(e.serialNumber){var C=l.util.hexToBytes(!0===e.serialNumber?t.cert.serialNumber:e.serialNumber);c.push(p.create(p.Class.CONTEXT_SPECIFIC,2,!1,C))}}else if("cRLDistributionPoints"===e.name){e.value=p.create(p.Class.UNIVERSAL,p.Type.SEQUENCE,!0,[]);for(var d,c=e.value.value,E=p.create(p.Class.UNIVERSAL,p.Type.SEQUENCE,!0,[]),S=p.create(p.Class.CONTEXT_SPECIFIC,0,!0,[]),y=0;y=S&&e2)throw new Error("Cannot read notBefore/notAfter validity times; more than two times were provided in the certificate.");if(d.length<2)throw new Error("Cannot read notBefore/notAfter validity times; they were not provided as either UTCTime or GeneralizedTime.");if(c.validity.notBefore=d[0],c.validity.notAfter=d[1],c.tbsCertificate=r.tbsCertificate,t){if(c.md=null,c.signatureOid in h){var o=h[c.signatureOid];switch(o){case"sha1WithRSAEncryption":c.md=l.md.sha1.create();break;case"md5WithRSAEncryption":c.md=l.md.md5.create();break;case"sha256WithRSAEncryption":c.md=l.md.sha256.create();break;case"sha384WithRSAEncryption":c.md=l.md.sha384.create();break;case"sha512WithRSAEncryption":c.md=l.md.sha512.create();break;case"RSASSA-PSS":c.md=l.md.sha256.create()}}if(null===c.md){var s=new Error("Could not compute certificate digest. Unknown signature OID.");throw s.signatureOid=c.signatureOid,s}var y=p.toDer(c.tbsCertificate);c.md.update(y.getBytes())}var v=l.md.sha1.create();c.issuer.getField=function(e){return a(c.issuer,e)},c.issuer.addField=function(e){i([e]),c.issuer.attributes.push(e)},c.issuer.attributes=f.RDNAttributesAsArray(r.certIssuer,v),r.certIssuerUniqueId&&(c.issuer.uniqueId=r.certIssuerUniqueId),c.issuer.hash=v.digest().toHex();var m=l.md.sha1.create();return c.subject.getField=function(e){return a(c.subject,e)},c.subject.addField=function(e){i([e]),c.subject.attributes.push(e)},c.subject.attributes=f.RDNAttributesAsArray(r.certSubject,m),r.certSubjectUniqueId&&(c.subject.uniqueId=r.certSubjectUniqueId),c.subject.hash=m.digest().toHex(),r.certExtensions?c.extensions=f.certificateExtensionsFromAsn1(r.certExtensions):c.extensions=[],c.publicKey=f.publicKeyFromAsn1(r.subjectPublicKeyInfo),c},f.certificateExtensionsFromAsn1=function(e){for(var t=[],r=0;r1&&(a=r.value.charCodeAt(1),n=r.value.length>2?r.value.charCodeAt(2):0),t.digitalSignature=128==(128&a),t.nonRepudiation=64==(64&a),t.keyEncipherment=32==(32&a),t.dataEncipherment=16==(16&a),t.keyAgreement=8==(8&a),t.keyCertSign=4==(4&a),t.cRLSign=2==(2&a),t.encipherOnly=1==(1&a),t.decipherOnly=128==(128&n)}else if("basicConstraints"===t.name){var r=p.fromDer(t.value);r.value.length>0&&r.value[0].type===p.Type.BOOLEAN?t.cA=0!==r.value[0].value.charCodeAt(0):t.cA=!1;var i=null;r.value.length>0&&r.value[0].type===p.Type.INTEGER?i=r.value[0].value:r.value.length>1&&(i=r.value[1].value),null!==i&&(t.pathLenConstraint=p.derToInteger(i))}else if("extKeyUsage"===t.name)for(var r=p.fromDer(t.value),s=0;s1&&(a=r.value.charCodeAt(1)),t.client=128==(128&a),t.server=64==(64&a),t.email=32==(32&a),t.objsign=16==(16&a),t.reserved=8==(8&a),t.sslCA=4==(4&a),t.emailCA=2==(2&a),t.objCA=1==(1&a)}else if("subjectAltName"===t.name||"issuerAltName"===t.name){t.altNames=[];for(var c,r=p.fromDer(t.value),u=0;u0&&a.value.push(f.certificateExtensionsToAsn1(e.extensions)),a},f.getCertificationRequestInfo=function(e){return p.create(p.Class.UNIVERSAL,p.Type.SEQUENCE,!0,[p.create(p.Class.UNIVERSAL,p.Type.INTEGER,!1,p.integerToDer(e.version).getBytes()),n(e.subject),f.publicKeyToAsn1(e.publicKey),c(e)])},f.distinguishedNameToAsn1=function(e){return n(e)},f.certificateToAsn1=function(e){var t=e.tbsCertificate||f.getTBSCertificate(e);return p.create(p.Class.UNIVERSAL,p.Type.SEQUENCE,!0,[t,p.create(p.Class.UNIVERSAL,p.Type.SEQUENCE,!0,[p.create(p.Class.UNIVERSAL,p.Type.OID,!1,p.oidToDer(e.signatureOid).getBytes()),o(e.signatureOid,e.signatureParameters)]),p.create(p.Class.UNIVERSAL,p.Type.BITSTRING,!1,String.fromCharCode(0)+e.signature)])},f.certificateExtensionsToAsn1=function(e){var t=p.create(p.Class.CONTEXT_SPECIFIC,3,!0,[]),r=p.create(p.Class.UNIVERSAL,p.Type.SEQUENCE,!0,[]);t.value.push(r);for(var a=0;ac.validity.notAfter)&&(s={message:"Certificate is not valid yet or has expired.",error:f.certificateError.certificate_expired,notBefore:c.validity.notBefore,notAfter:c.validity.notAfter,now:n}),null===s){if(u=t[0]||e.getIssuer(c),null===u&&c.isIssuer(c)&&(p=!0,u=c),u){var h=u;l.util.isArray(h)||(h=[h]);for(var d=!1;!d&&h.length>0;){u=h.shift();try{d=u.verify(c)}catch(e){}}d||(s={message:"Certificate signature is invalid.",error:f.certificateError.bad_certificate})}null!==s||u&&!p||e.hasCertificate(c)||(s={message:"Certificate is not trusted.",error:f.certificateError.unknown_ca})}if(null===s&&u&&!c.isIssuer(u)&&(s={message:"Certificate issuer is invalid.",error:f.certificateError.bad_certificate}),null===s)for(var y={keyUsage:!0,basicConstraints:!0},g=0;null===s&&gm.pathLenConstraint&&(s={message:"Certificate basicConstraints pathLenConstraint violated.",error:f.certificateError.bad_certificate})}}var E=null===s||s.error,S=r.verify?r.verify(E,o,a):E;if(!0!==S)throw!0===E&&(s={message:"The application rejected the certificate.",error:f.certificateError.bad_certificate}),(S||0===S)&&("object"!=typeof S||l.util.isArray(S)?"string"==typeof S&&(s.error=S):(S.message&&(s.message=S.message),S.error&&(s.error=S.error))),s;s=null,i=!1,++o}while(t.length>0);return!0}},function(e,t,r){var a=r(0);r(2),r(1),(e.exports=a.pss=a.pss||{}).create=function(e){3===arguments.length&&(e={md:arguments[0],mgf:arguments[1],saltLength:arguments[2]});var t=e.md,r=e.mgf,n=t.digestLength,i=e.salt||null;"string"==typeof i&&(i=a.util.createBuffer(i));var s;if("saltLength"in e)s=e.saltLength;else{if(null===i)throw new Error("Salt length not specified or specific salt not given.");s=i.length()}if(null!==i&&i.length()!==s)throw new Error("Given salt length does not match length of given salt.");var o=e.prng||a.random,c={};return c.encode=function(e,c){var u,l=c-1,p=Math.ceil(l/8),f=e.digest().getBytes();if(p>8*p-l&255;return(E=String.fromCharCode(E.charCodeAt(0)&~S)+E.substr(1))+y+String.fromCharCode(188)},c.verify=function(e,i,o){var c,u=o-1,l=Math.ceil(u/8);if(i=i.substr(-l),l>8*l-u&255;if(0!=(f.charCodeAt(0)&d))throw new Error("Bits beyond keysize not zero as expected.");var y=r.generate(h,p),g="";for(c=0;c4){var r=e;e=s.util.createBuffer();for(var a=0;a0))return!0;for(var a=0;a0))return!0;for(var a=0;a0)return!1;var r=e.length(),a=e.at(r-1);return!(a>this.blockSize<<2)&&(e.truncate(a),!0)},o.cbc=function(e){e=e||{},this.name="CBC",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints)},o.cbc.prototype.start=function(e){if(null===e.iv){if(!this._prev)throw new Error("Invalid IV parameter.");this._iv=this._prev.slice(0)}else{if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=a(e.iv,this.blockSize),this._prev=this._iv.slice(0)}},o.cbc.prototype.encrypt=function(e,t,r){if(e.length()0))return!0;for(var a=0;a0))return!0;for(var a=0;a0)return!1;var r=e.length(),a=e.at(r-1);return!(a>this.blockSize<<2)&&(e.truncate(a),!0)},o.cfb=function(e){e=e||{},this.name="CFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialBlock=new Array(this._ints),this._partialOutput=s.util.createBuffer(),this._partialBytes=0},o.cfb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=a(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},o.cfb.prototype.encrypt=function(e,t,r){var a=e.length();if(0===a)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&a>=this.blockSize)for(var n=0;n0&&(i=this.blockSize-i),this._partialOutput.clear();for(var n=0;n0)e.read-=this.blockSize;else for(var n=0;n0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(a-this._partialBytes)),this._partialBytes=0}},o.cfb.prototype.decrypt=function(e,t,r){var a=e.length();if(0===a)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&a>=this.blockSize)for(var n=0;n0&&(i=this.blockSize-i),this._partialOutput.clear();for(var n=0;n0)e.read-=this.blockSize;else for(var n=0;n0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(a-this._partialBytes)),this._partialBytes=0}},o.ofb=function(e){e=e||{},this.name="OFB",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=s.util.createBuffer(),this._partialBytes=0},o.ofb.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=a(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},o.ofb.prototype.encrypt=function(e,t,r){var a=e.length();if(0===e.length())return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&a>=this.blockSize)for(var n=0;n0&&(i=this.blockSize-i),this._partialOutput.clear();for(var n=0;n0)e.read-=this.blockSize;else for(var n=0;n0&&this._partialOutput.getBytes(this._partialBytes),i>0&&!r)return t.putBytes(this._partialOutput.getBytes(i-this._partialBytes)),this._partialBytes=i,!0;t.putBytes(this._partialOutput.getBytes(a-this._partialBytes)),this._partialBytes=0}},o.ofb.prototype.decrypt=o.ofb.prototype.encrypt,o.ctr=function(e){e=e||{},this.name="CTR",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=null,this._outBlock=new Array(this._ints),this._partialOutput=s.util.createBuffer(),this._partialBytes=0},o.ctr.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");this._iv=a(e.iv,this.blockSize),this._inBlock=this._iv.slice(0),this._partialBytes=0},o.ctr.prototype.encrypt=function(e,t,r){var a=e.length();if(0===a)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&a>=this.blockSize)for(var i=0;i0&&(s=this.blockSize-s),this._partialOutput.clear();for(var i=0;i0&&(e.read-=this.blockSize),this._partialBytes>0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!r)return t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(a-this._partialBytes)),this._partialBytes=0}n(this._inBlock)},o.ctr.prototype.decrypt=o.ctr.prototype.encrypt,o.gcm=function(e){e=e||{},this.name="GCM",this.cipher=e.cipher,this.blockSize=e.blockSize||16,this._ints=this.blockSize/4,this._inBlock=new Array(this._ints),this._outBlock=new Array(this._ints),this._partialOutput=s.util.createBuffer(),this._partialBytes=0,this._R=3774873600},o.gcm.prototype.start=function(e){if(!("iv"in e))throw new Error("Invalid IV parameter.");var t=s.util.createBuffer(e.iv);this._cipherLength=0;var r;if(r="additionalData"in e?s.util.createBuffer(e.additionalData):s.util.createBuffer(),this._tagLength="tagLength"in e?e.tagLength:128,this._tag=null,e.decrypt&&(this._tag=s.util.createBuffer(e.tag).getBytes(),this._tag.length!==this._tagLength/8))throw new Error("Authentication tag does not match tag length.");this._hashBlock=new Array(this._ints),this.tag=null,this._hashSubkey=new Array(this._ints),this.cipher.encrypt([0,0,0,0],this._hashSubkey),this.componentBits=4,this._m=this.generateHashTable(this._hashSubkey,this.componentBits);var a=t.length();if(12===a)this._j0=[t.getInt32(),t.getInt32(),t.getInt32(),1];else{for(this._j0=[0,0,0,0];t.length()>0;)this._j0=this.ghash(this._hashSubkey,this._j0,[t.getInt32(),t.getInt32(),t.getInt32(),t.getInt32()]);this._j0=this.ghash(this._hashSubkey,this._j0,[0,0].concat(i(8*a)))}this._inBlock=this._j0.slice(0),n(this._inBlock),this._partialBytes=0,r=s.util.createBuffer(r),this._aDataLength=i(8*r.length());var o=r.length()%this.blockSize;for(o&&r.fillWithByte(0,this.blockSize-o),this._s=[0,0,0,0];r.length()>0;)this._s=this.ghash(this._hashSubkey,this._s,[r.getInt32(),r.getInt32(),r.getInt32(),r.getInt32()])},o.gcm.prototype.encrypt=function(e,t,r){var a=e.length();if(0===a)return!0;if(this.cipher.encrypt(this._inBlock,this._outBlock),0===this._partialBytes&&a>=this.blockSize){for(var i=0;i0&&(s=this.blockSize-s),this._partialOutput.clear();for(var i=0;i0&&this._partialOutput.getBytes(this._partialBytes),s>0&&!r)return e.read-=this.blockSize,t.putBytes(this._partialOutput.getBytes(s-this._partialBytes)),this._partialBytes=s,!0;t.putBytes(this._partialOutput.getBytes(a-this._partialBytes)),this._partialBytes=0}this._s=this.ghash(this._hashSubkey,this._s,this._outBlock),n(this._inBlock)},o.gcm.prototype.decrypt=function(e,t,r){var a=e.length();if(a0))return!0;this.cipher.encrypt(this._inBlock,this._outBlock),n(this._inBlock),this._hashBlock[0]=e.getInt32(),this._hashBlock[1]=e.getInt32(),this._hashBlock[2]=e.getInt32(),this._hashBlock[3]=e.getInt32(),this._s=this.ghash(this._hashSubkey,this._s,this._hashBlock);for(var i=0;i0;--a)t[a]=e[a]>>>1|(1&e[a-1])<<31;t[0]=e[0]>>>1,r&&(t[0]^=this._R)},o.gcm.prototype.tableMultiply=function(e){for(var t=[0,0,0,0],r=0;r<32;++r){var a=r/8|0,n=e[a]>>>4*(7-r%8)&15,i=this._m[r][n];t[0]^=i[0],t[1]^=i[1],t[2]^=i[2],t[3]^=i[3]}return t},o.gcm.prototype.ghash=function(e,t,r){return t[0]^=r[0],t[1]^=r[1],t[2]^=r[2],t[3]^=r[3],this.tableMultiply(t)},o.gcm.prototype.generateHashTable=function(e,t){for(var r=8/t,a=4*r,n=16*r,i=new Array(n),s=0;s>>1,n=new Array(r);n[a]=e.slice(0);for(var i=a>>>1;i>0;)this.pow(n[2*i],n[i]=[]),i>>=1;for(i=2;i>1,o=s+(1&e.length),c=e.substr(0,o),u=e.substr(s,o),l=a.util.createBuffer(),p=a.hmac.create();r=t+r;var f=Math.ceil(n/16),h=Math.ceil(n/20);p.start("MD5",c);var d=a.util.createBuffer();l.putBytes(r);for(var y=0;y0&&(l.queue(e,l.createAlert(e,{level:l.Alert.Level.warning,description:l.Alert.Description.no_renegotiation})),l.flush(e)),e.process()},l.parseHelloMessage=function(e,t,r){var n=null,i=e.entity===l.ConnectionEnd.client;if(r<38)e.error(e,{message:i?"Invalid ServerHello message. Message too short.":"Invalid ClientHello message. Message too short.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.illegal_parameter}});else{var s=t.fragment,o=s.length();if(n={version:{major:s.getByte(),minor:s.getByte()},random:a.util.createBuffer(s.getBytes(32)),session_id:c(s,1),extensions:[]},i?(n.cipher_suite=s.getBytes(2),n.compression_method=s.getByte()):(n.cipher_suites=c(s,2),n.compression_methods=c(s,1)),(o=r-(o-s.length()))>0){for(var u=c(s,2);u.length()>0;)n.extensions.push({type:[u.getByte(),u.getByte()],data:c(u,2)});if(!i)for(var p=0;p0;){var d=h.getByte();if(0!==d)break;e.session.extensions.server_name.serverNameList.push(c(h,2).getBytes())}}}if(e.session.version&&(n.version.major!==e.session.version.major||n.version.minor!==e.session.version.minor))return e.error(e,{message:"TLS version change is disallowed during renegotiation.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.protocol_version}});if(i)e.session.cipherSuite=l.getCipherSuite(n.cipher_suite);else for(var y=a.util.createBuffer(n.cipher_suites.bytes());y.length()>0&&(e.session.cipherSuite=l.getCipherSuite(y.getBytes(2)),null===e.session.cipherSuite););if(null===e.session.cipherSuite)return e.error(e,{message:"No cipher suites in common.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.handshake_failure},cipherSuite:a.util.bytesToHex(n.cipher_suite)});e.session.compressionMethod=i?n.compression_method:l.CompressionMethod.none}return n},l.createSecurityParameters=function(e,t){var r=e.entity===l.ConnectionEnd.client,a=t.random.bytes(),n=r?e.session.sp.client_random:a,i=r?a:l.createRandom().getBytes();e.session.sp={entity:e.entity,prf_algorithm:l.PRFAlgorithm.tls_prf_sha256,bulk_cipher_algorithm:null,cipher_type:null,enc_key_length:null,block_length:null,fixed_iv_length:null,record_iv_length:null,mac_algorithm:null,mac_length:null,mac_key_length:null,compression_algorithm:e.session.compressionMethod,pre_master_secret:null,master_secret:null,client_random:n,server_random:i}},l.handleServerHello=function(e,t,r){var a=l.parseHelloMessage(e,t,r);if(!e.fail){if(!(a.version.minor<=e.version.minor))return e.error(e,{message:"Incompatible TLS version.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.protocol_version}});e.version.minor=a.version.minor,e.session.version=e.version;var n=a.session_id.bytes();n.length>0&&n===e.session.id?(e.expect=y,e.session.resuming=!0,e.session.sp.server_random=a.random.bytes()):(e.expect=p,e.session.resuming=!1,l.createSecurityParameters(e,a)),e.session.id=n,e.process()}},l.handleClientHello=function(e,t,r){var n=l.parseHelloMessage(e,t,r);if(!e.fail){var i=n.session_id.bytes(),s=null;if(e.sessionCache&&(s=e.sessionCache.getSession(i),null===s?i="":(s.version.major!==n.version.major||s.version.minor>n.version.minor)&&(s=null,i="")),0===i.length&&(i=a.random.getBytes(32)),e.session.id=i,e.session.clientHelloVersion=n.version,e.session.sp={},s)e.version=e.session.version=s.version,e.session.sp=s.sp;else{for(var o,c=1;c0;)n=c(o.certificate_list,3),i=a.asn1.fromDer(n),n=a.pki.certificateFromAsn1(i,!0),u.push(n)}catch(t){return e.error(e,{message:"Could not parse certificate list.",cause:t,send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.bad_certificate}})}var p=e.entity===l.ConnectionEnd.client;!p&&!0!==e.verifyClient||0!==u.length?0===u.length?e.expect=p?f:E:(p?e.session.serverCertificate=u[0]:e.session.clientCertificate=u[0],l.verifyCertificateChain(e,u)&&(e.expect=p?f:E)):e.error(e,{message:p?"No server certificate provided.":"No client certificate provided.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.illegal_parameter}}),e.process()},l.handleServerKeyExchange=function(e,t,r){if(r>0)return e.error(e,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.unsupported_certificate}});e.expect=h,e.process()},l.handleClientKeyExchange=function(e,t,r){if(r<48)return e.error(e,{message:"Invalid key parameters. Only RSA is supported.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.unsupported_certificate}});var n=t.fragment,i={enc_pre_master_secret:c(n,2).getBytes()},s=null;if(e.getPrivateKey)try{s=e.getPrivateKey(e,e.session.serverCertificate),s=a.pki.privateKeyFromPem(s)}catch(t){e.error(e,{message:"Could not get private key.",cause:t,send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.internal_error}})}if(null===s)return e.error(e,{message:"No private key set.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.internal_error}});try{var o=e.session.sp;o.pre_master_secret=s.decrypt(i.enc_pre_master_secret);var u=e.session.clientHelloVersion;if(u.major!==o.pre_master_secret.charCodeAt(0)||u.minor!==o.pre_master_secret.charCodeAt(1))throw new Error("TLS version rollback attack detected.")}catch(e){o.pre_master_secret=a.random.getBytes(48)}e.expect=T,null!==e.session.clientCertificate&&(e.expect=S),e.process()},l.handleCertificateRequest=function(e,t,r){if(r<3)return e.error(e,{message:"Invalid CertificateRequest. Message too short.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.illegal_parameter}});var a=t.fragment,n={certificate_types:c(a,1),certificate_authorities:c(a,2)};e.session.certificateRequest=n,e.expect=d,e.process()},l.handleCertificateVerify=function(e,t,r){if(r<2)return e.error(e,{message:"Invalid CertificateVerify. Message too short.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.illegal_parameter}});var n=t.fragment;n.read-=4;var i=n.bytes();n.read+=4;var s={signature:c(n,2).getBytes()},o=a.util.createBuffer();o.putBuffer(e.session.md5.digest()),o.putBuffer(e.session.sha1.digest()),o=o.getBytes();try{if(!e.session.clientCertificate.publicKey.verify(o,s.signature,"NONE"))throw new Error("CertificateVerify signature does not match.");e.session.md5.update(i),e.session.sha1.update(i)}catch(t){return e.error(e,{message:"Bad signature in CertificateVerify.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.handshake_failure}})}e.expect=T,e.process()},l.handleServerHelloDone=function(e,t,r){if(r>0)return e.error(e,{message:"Invalid ServerHelloDone message. Invalid length.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.record_overflow}});if(null===e.serverCertificate){var n={message:"No server certificate provided. Not enough security.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.insufficient_security}},i=e.verify(e,n.alert.description,0,[]);if(!0!==i)return(i||0===i)&&("object"!=typeof i||a.util.isArray(i)?"number"==typeof i&&(n.alert.description=i):(i.message&&(n.message=i.message),i.alert&&(n.alert.description=i.alert))),e.error(e,n)}null!==e.session.certificateRequest&&(t=l.createRecord(e,{type:l.ContentType.handshake,data:l.createCertificate(e)}),l.queue(e,t)),t=l.createRecord(e,{type:l.ContentType.handshake,data:l.createClientKeyExchange(e)}),l.queue(e,t),e.expect=m;var s=function(e,t){null!==e.session.certificateRequest&&null!==e.session.clientCertificate&&l.queue(e,l.createRecord(e,{type:l.ContentType.handshake,data:l.createCertificateVerify(e,t)})),l.queue(e,l.createRecord(e,{type:l.ContentType.change_cipher_spec,data:l.createChangeCipherSpec()})),e.state.pending=l.createConnectionState(e),e.state.current.write=e.state.pending.write,l.queue(e,l.createRecord(e,{type:l.ContentType.handshake,data:l.createFinished(e)})),e.expect=y,l.flush(e),e.process()};if(null===e.session.certificateRequest||null===e.session.clientCertificate)return s(e,null);l.getClientSignature(e,s)},l.handleChangeCipherSpec=function(e,t){if(1!==t.fragment.getByte())return e.error(e,{message:"Invalid ChangeCipherSpec message received.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.illegal_parameter}});var r=e.entity===l.ConnectionEnd.client;(e.session.resuming&&r||!e.session.resuming&&!r)&&(e.state.pending=l.createConnectionState(e)),e.state.current.read=e.state.pending.read,(!e.session.resuming&&r||e.session.resuming&&!r)&&(e.state.pending=null),e.expect=r?g:I,e.process()},l.handleFinished=function(e,t,r){var i=t.fragment;i.read-=4;var s=i.bytes();i.read+=4;var o=t.fragment.getBytes();i=a.util.createBuffer(),i.putBuffer(e.session.md5.digest()),i.putBuffer(e.session.sha1.digest());var c=e.entity===l.ConnectionEnd.client,u=c?"server finished":"client finished",p=e.session.sp;if(i=n(p.master_secret,u,i.getBytes(),12),i.getBytes()!==o)return e.error(e,{message:"Invalid verify_data in Finished message.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.decrypt_error}});e.session.md5.update(s),e.session.sha1.update(s),(e.session.resuming&&c||!e.session.resuming&&!c)&&(l.queue(e,l.createRecord(e,{type:l.ContentType.change_cipher_spec,data:l.createChangeCipherSpec()})),e.state.current.write=e.state.pending.write,e.state.pending=null,l.queue(e,l.createRecord(e,{type:l.ContentType.handshake,data:l.createFinished(e)}))),e.expect=c?v:b,e.handshaking=!1,++e.handshakes,e.peerCertificate=c?e.session.serverCertificate:e.session.clientCertificate,l.flush(e),e.isConnected=!0,e.connected(e),e.process()},l.handleAlert=function(e,t){var r,a=t.fragment,n={level:a.getByte(),description:a.getByte()};switch(n.description){case l.Alert.Description.close_notify:r="Connection closed.";break;case l.Alert.Description.unexpected_message:r="Unexpected message.";break;case l.Alert.Description.bad_record_mac:r="Bad record MAC.";break;case l.Alert.Description.decryption_failed:r="Decryption failed.";break;case l.Alert.Description.record_overflow:r="Record overflow.";break;case l.Alert.Description.decompression_failure:r="Decompression failed.";break;case l.Alert.Description.handshake_failure:r="Handshake failure.";break;case l.Alert.Description.bad_certificate:r="Bad certificate.";break;case l.Alert.Description.unsupported_certificate:r="Unsupported certificate.";break;case l.Alert.Description.certificate_revoked:r="Certificate revoked.";break;case l.Alert.Description.certificate_expired:r="Certificate expired.";break;case l.Alert.Description.certificate_unknown:r="Certificate unknown.";break;case l.Alert.Description.illegal_parameter:r="Illegal parameter.";break;case l.Alert.Description.unknown_ca:r="Unknown certificate authority.";break;case l.Alert.Description.access_denied:r="Access denied.";break;case l.Alert.Description.decode_error:r="Decode error.";break;case l.Alert.Description.decrypt_error:r="Decrypt error.";break;case l.Alert.Description.export_restriction:r="Export restriction.";break;case l.Alert.Description.protocol_version:r="Unsupported protocol version.";break;case l.Alert.Description.insufficient_security:r="Insufficient security.";break;case l.Alert.Description.internal_error:r="Internal error.";break;case l.Alert.Description.user_canceled:r="User canceled.";break;case l.Alert.Description.no_renegotiation:r="Renegotiation not supported.";break;default:r="Unknown error."}if(n.description===l.Alert.Description.close_notify)return e.close();e.error(e,{message:r,send:!1,origin:e.entity===l.ConnectionEnd.client?"server":"client",alert:n}),e.process()},l.handleHandshake=function(e,t){var r=t.fragment,n=r.getByte(),i=r.getInt24();if(i>r.length())return e.fragmented=t,t.fragment=a.util.createBuffer(),r.read-=4,e.process();e.fragmented=null,r.read-=4;var s=r.bytes(i+4);r.read+=4,n in x[e.entity][e.expect]?(e.entity!==l.ConnectionEnd.server||e.open||e.fail||(e.handshaking=!0,e.session={version:null,extensions:{server_name:{serverNameList:[]}},cipherSuite:null,compressionMethod:null,serverCertificate:null,clientCertificate:null,md5:a.md.md5.create(),sha1:a.md.sha1.create()}),n!==l.HandshakeType.hello_request&&n!==l.HandshakeType.certificate_verify&&n!==l.HandshakeType.finished&&(e.session.md5.update(s),e.session.sha1.update(s)),x[e.entity][e.expect][n](e,t,i)):l.handleUnexpected(e,t)},l.handleApplicationData=function(e,t){e.data.putBuffer(t.fragment),e.dataReady(e),e.process()},l.handleHeartbeat=function(e,t){var r=t.fragment,n=r.getByte(),i=r.getInt16(),s=r.getBytes(i);if(n===l.HeartbeatMessageType.heartbeat_request){if(e.handshaking||i>s.length)return e.process();l.queue(e,l.createRecord(e,{type:l.ContentType.heartbeat,data:l.createHeartbeat(l.HeartbeatMessageType.heartbeat_response,s)})),l.flush(e)}else if(n===l.HeartbeatMessageType.heartbeat_response){if(s!==e.expectedHeartbeatPayload)return e.process();e.heartbeatReceived&&e.heartbeatReceived(e,a.util.createBuffer(s))}e.process()};var p=1,f=2,h=3,d=4,y=5,g=6,v=7,m=8,C=1,E=2,S=3,T=4,I=5,b=6,A=l.handleUnexpected,B=l.handleChangeCipherSpec,N=l.handleAlert,k=l.handleHandshake,w=l.handleApplicationData,R=l.handleHeartbeat,_=[];_[l.ConnectionEnd.client]=[[A,N,k,A,R],[A,N,k,A,R],[A,N,k,A,R],[A,N,k,A,R],[A,N,k,A,R],[B,N,A,A,R],[A,N,k,A,R],[A,N,k,w,R],[A,N,k,A,R]],_[l.ConnectionEnd.server]=[[A,N,k,A,R],[A,N,k,A,R],[A,N,k,A,R],[A,N,k,A,R],[B,N,A,A,R],[A,N,k,A,R],[A,N,k,w,R],[A,N,k,A,R]];var L=l.handleHelloRequest,U=l.handleServerHello,D=l.handleCertificate,P=l.handleServerKeyExchange,V=l.handleCertificateRequest,O=l.handleServerHelloDone,K=l.handleFinished,x=[];x[l.ConnectionEnd.client]=[[A,A,U,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A],[L,A,A,A,A,A,A,A,A,A,A,D,P,V,O,A,A,A,A,A,A],[L,A,A,A,A,A,A,A,A,A,A,A,P,V,O,A,A,A,A,A,A],[L,A,A,A,A,A,A,A,A,A,A,A,A,V,O,A,A,A,A,A,A],[L,A,A,A,A,A,A,A,A,A,A,A,A,A,O,A,A,A,A,A,A],[L,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A],[L,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,K],[L,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A],[L,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A]];var M=l.handleClientHello,F=l.handleClientKeyExchange,j=l.handleCertificateVerify;x[l.ConnectionEnd.server]=[[A,M,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A],[A,A,A,A,A,A,A,A,A,A,A,D,A,A,A,A,A,A,A,A,A],[A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,F,A,A,A,A],[A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,j,A,A,A,A,A],[A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A],[A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,K],[A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A],[A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A,A]],l.generateKeys=function(e,t){var r=n,a=t.client_random+t.server_random;e.session.resuming||(t.master_secret=r(t.pre_master_secret,"master secret",a,48).bytes(),t.pre_master_secret=null),a=t.server_random+t.client_random;var i=2*t.mac_key_length+2*t.enc_key_length,s=e.version.major===l.Versions.TLS_1_0.major&&e.version.minor===l.Versions.TLS_1_0.minor;s&&(i+=2*t.fixed_iv_length);var o=r(t.master_secret,"key expansion",a,i),c={client_write_MAC_key:o.getBytes(t.mac_key_length),server_write_MAC_key:o.getBytes(t.mac_key_length),client_write_key:o.getBytes(t.enc_key_length),server_write_key:o.getBytes(t.enc_key_length)};return s&&(c.client_write_IV=o.getBytes(t.fixed_iv_length),c.server_write_IV=o.getBytes(t.fixed_iv_length)),c},l.createConnectionState=function(e){var t=e.entity===l.ConnectionEnd.client,r=function(){var e={sequenceNumber:[0,0],macKey:null,macLength:0,macFunction:null,cipherState:null,cipherFunction:function(e){return!0},compressionState:null,compressFunction:function(e){return!0},updateSequenceNumber:function(){4294967295===e.sequenceNumber[1]?(e.sequenceNumber[1]=0,++e.sequenceNumber[0]):++e.sequenceNumber[1]}};return e},a={read:r(),write:r()};if(a.read.update=function(e,t){return a.read.cipherFunction(t,a.read)?a.read.compressFunction(e,t,a.read)||e.error(e,{message:"Could not decompress record.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.decompression_failure}}):e.error(e,{message:"Could not decrypt record or bad MAC.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.bad_record_mac}}),!e.fail},a.write.update=function(e,t){return a.write.compressFunction(e,t,a.write)?a.write.cipherFunction(t,a.write)||e.error(e,{message:"Could not encrypt record.",send:!1,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.internal_error}}):e.error(e,{message:"Could not compress record.",send:!1,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.internal_error}}),!e.fail},e.session){var n=e.session.sp;switch(e.session.cipherSuite.initSecurityParameters(n),n.keys=l.generateKeys(e,n),a.read.macKey=t?n.keys.server_write_MAC_key:n.keys.client_write_MAC_key,a.write.macKey=t?n.keys.client_write_MAC_key:n.keys.server_write_MAC_key,e.session.cipherSuite.initConnectionState(a,e,n),n.compression_algorithm){case l.CompressionMethod.none:break;case l.CompressionMethod.deflate:a.read.compressFunction=o,a.write.compressFunction=s;break;default:throw new Error("Unsupported compression algorithm.")}}return a},l.createRandom=function(){var e=new Date,t=+e+6e4*e.getTimezoneOffset(),r=a.util.createBuffer();return r.putInt32(t),r.putBytes(a.random.getBytes(28)),r},l.createRecord=function(e,t){return t.data?{type:t.type,version:{major:e.version.major,minor:e.version.minor},length:t.data.length(),fragment:t.data}:null},l.createAlert=function(e,t){var r=a.util.createBuffer();return r.putByte(t.level),r.putByte(t.description),l.createRecord(e,{type:l.ContentType.alert,data:r})},l.createClientHello=function(e){e.session.clientHelloVersion={major:e.version.major,minor:e.version.minor};for(var t=a.util.createBuffer(),r=0;r0&&(d+=2);var y=e.session.id,g=y.length+1+2+4+28+2+i+1+o+d,v=a.util.createBuffer();return v.putByte(l.HandshakeType.client_hello),v.putInt24(g),v.putByte(e.version.major),v.putByte(e.version.minor),v.putBytes(e.session.sp.client_random),u(v,1,a.util.createBuffer(y)),u(v,2,t),u(v,1,s),d>0&&u(v,2,c),v},l.createServerHello=function(e){var t=e.session.id,r=t.length+1+2+4+28+2+1,n=a.util.createBuffer();return n.putByte(l.HandshakeType.server_hello),n.putInt24(r),n.putByte(e.version.major),n.putByte(e.version.minor),n.putBytes(e.session.sp.server_random),u(n,1,a.util.createBuffer(t)),n.putByte(e.session.cipherSuite.id[0]),n.putByte(e.session.cipherSuite.id[1]),n.putByte(e.session.compressionMethod),n},l.createCertificate=function(e){var t=e.entity===l.ConnectionEnd.client,r=null;if(e.getCertificate){var n;n=t?e.session.certificateRequest:e.session.extensions.server_name.serverNameList,r=e.getCertificate(e,n)}var i=a.util.createBuffer();if(null!==r)try{a.util.isArray(r)||(r=[r]);for(var s=null,o=0;ol.MaxFragment;)n.push(l.createRecord(e,{type:t.type,data:a.util.createBuffer(i.slice(0,l.MaxFragment))})),i=i.slice(l.MaxFragment);i.length>0&&n.push(l.createRecord(e,{type:t.type,data:a.util.createBuffer(i)}))}for(var s=0;s0&&(n=r.order[0]),null!==n&&n in r.cache){t=r.cache[n],delete r.cache[n];for(var i in r.order)if(r.order[i]===n){r.order.splice(i,1);break}}return t},r.setSession=function(e,t){if(r.order.length===r.capacity){var n=r.order.shift();delete r.cache[n]}var n=a.util.bytesToHex(e);r.order.push(n),r.cache[n]=t}}return r},l.createConnection=function(e){var t=null;t=e.caStore?a.util.isArray(e.caStore)?a.pki.createCaStore(e.caStore):e.caStore:a.pki.createCaStore();var r=e.cipherSuites||null;if(null===r){r=[];for(var n in l.CipherSuites)r.push(l.CipherSuites[n])}var i=e.server?l.ConnectionEnd.server:l.ConnectionEnd.client,s=e.sessionCache?l.createSessionCache(e.sessionCache):null,o={version:{major:l.Version.major,minor:l.Version.minor},entity:i,sessionId:e.sessionId,caStore:t,sessionCache:s,cipherSuites:r,connected:e.connected,virtualHost:e.virtualHost||null,verifyClient:e.verifyClient||!1,verify:e.verify||function(e,t,r,a){return t},verifyOptions:e.verifyOptions||{},getCertificate:e.getCertificate||null,getPrivateKey:e.getPrivateKey||null,getSignature:e.getSignature||null,input:a.util.createBuffer(),tlsData:a.util.createBuffer(),data:a.util.createBuffer(),tlsDataReady:e.tlsDataReady,dataReady:e.dataReady,heartbeatReceived:e.heartbeatReceived,closed:e.closed,error:function(t,r){r.origin=r.origin||(t.entity===l.ConnectionEnd.client?"client":"server"),r.send&&(l.queue(t,l.createAlert(t,r.alert)),l.flush(t));var a=!1!==r.fatal;a&&(t.fail=!0),e.error(t,r),a&&t.close(!1)},deflate:e.deflate||null,inflate:e.inflate||null};o.reset=function(e){o.version={major:l.Version.major,minor:l.Version.minor},o.record=null,o.session=null,o.peerCertificate=null,o.state={pending:null,current:null},o.expect=(o.entity,l.ConnectionEnd.client,0),o.fragmented=null,o.records=[],o.open=!1,o.handshakes=0,o.handshaking=!1,o.isConnected=!1,o.fail=!(e||void 0===e),o.input.clear(),o.tlsData.clear(),o.data.clear(),o.state.current=l.createConnectionState(o)},o.reset();var c=function(e,t){var r=t.type-l.ContentType.change_cipher_spec,a=_[e.entity][e.expect];r in a?a[r](e,t):l.handleUnexpected(e,t)},u=function(e){var t=0,r=e.input,n=r.length();if(n<5)t=5-n;else{e.record={type:r.getByte(),version:{major:r.getByte(),minor:r.getByte()},length:r.getInt16(),fragment:a.util.createBuffer(),ready:!1};var i=e.record.version.major===e.version.major;i&&e.session&&e.session.version&&(i=e.record.version.minor===e.version.minor),i||e.error(e,{message:"Incompatible TLS version.",send:!0,alert:{level:l.Alert.Level.fatal,description:l.Alert.Description.protocol_version}})}return t},p=function(e){var t=0,r=e.input,a=r.length();if(a0&&(o.sessionCache&&(t=o.sessionCache.getSession(e)),null===t&&(e="")),0===e.length&&o.sessionCache&&null!==(t=o.sessionCache.getSession())&&(e=t.id),o.session={id:e,version:null,cipherSuite:null,compressionMethod:null,serverCertificate:null,certificateRequest:null,clientCertificate:null,sp:{},md5:a.md.md5.create(),sha1:a.md.sha1.create()},t&&(o.version=t.version,o.session.sp=t.sp),o.session.sp.client_random=l.createRandom().getBytes(),o.open=!0,l.queue(o,l.createRecord(o,{type:l.ContentType.handshake,data:l.createClientHello(o)})),l.flush(o)}},o.process=function(e){var t=0;return e&&o.input.putBytes(e),o.fail||(null!==o.record&&o.record.ready&&o.record.fragment.isEmpty()&&(o.record=null),null===o.record&&(t=u(o)),o.fail||null===o.record||o.record.ready||(t=p(o)),!o.fail&&null!==o.record&&o.record.ready&&c(o,o.record)),t},o.prepare=function(e){return l.queue(o,l.createRecord(o,{type:l.ContentType.application_data,data:a.util.createBuffer(e)})),l.flush(o)},o.prepareHeartbeatRequest=function(e,t){return e instanceof a.util.ByteBuffer&&(e=e.bytes()),void 0===t&&(t=e.length),o.expectedHeartbeatPayload=e,l.queue(o,l.createRecord(o,{type:l.ContentType.heartbeat,data:l.createHeartbeat(l.HeartbeatMessageType.heartbeat_request,e,t)})),l.flush(o)},o.close=function(e){if(!o.fail&&o.sessionCache&&o.session){var t={id:o.session.id,version:o.session.version,sp:o.session.sp};t.sp.keys=null,o.sessionCache.setSession(t.id,t)}o.open&&(o.open=!1,o.input.clear(),(o.isConnected||o.handshaking)&&(o.isConnected=o.handshaking=!1,l.queue(o,l.createAlert(o,{level:l.Alert.Level.warning,description:l.Alert.Description.close_notify})),l.flush(o)),o.closed(o)),o.reset(e)},o},e.exports=a.tls=a.tls||{};for(var H in l)"function"!=typeof l[H]&&(a.tls[H]=l[H]);a.tls.prf_tls1=n,a.tls.hmac_sha1=i,a.tls.createSessionCache=l.createSessionCache,a.tls.createConnection=l.createConnection},function(e,t,r){var a=r(0);r(3),r(6),r(22),r(7),r(15),r(28),r(18),r(11),r(1),r(17);var n=a.asn1,i=e.exports=a.pki=a.pki||{};i.pemToDer=function(e){var t=a.pem.decode(e)[0];if(t.procType&&"ENCRYPTED"===t.procType.type)throw new Error("Could not convert PEM to DER; PEM is encrypted.");return a.util.createBuffer(t.body)},i.privateKeyFromPem=function(e){var t=a.pem.decode(e)[0];if("PRIVATE KEY"!==t.type&&"RSA PRIVATE KEY"!==t.type){var r=new Error('Could not convert private key from PEM; PEM header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".');throw r.headerType=t.type,r}if(t.procType&&"ENCRYPTED"===t.procType.type)throw new Error("Could not convert private key from PEM; PEM is encrypted.");var s=n.fromDer(t.body);return i.privateKeyFromAsn1(s)},i.privateKeyToPem=function(e,t){var r={type:"RSA PRIVATE KEY",body:n.toDer(i.privateKeyToAsn1(e)).getBytes()};return a.pem.encode(r,{maxline:t})},i.privateKeyInfoToPem=function(e,t){var r={type:"PRIVATE KEY",body:n.toDer(e).getBytes()};return a.pem.encode(r,{maxline:t})}},function(e,t,r){function a(e,t){return e.start().update(t).digest().getBytes()}function n(e){var t;if(e){if(!(t=l.oids[u.derToOid(e)])){var r=new Error("Unsupported PRF OID.");throw r.oid=e,r.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],r}}else t="hmacWithSHA1";return i(t)}function i(e){var t=o.md;switch(e){case"hmacWithSHA224":t=o.md.sha512;case"hmacWithSHA1":case"hmacWithSHA256":case"hmacWithSHA384":case"hmacWithSHA512":e=e.substr(8).toLowerCase();break;default:var r=new Error("Unsupported PRF algorithm.");throw r.algorithm=e,r.supported=["hmacWithSHA1","hmacWithSHA224","hmacWithSHA256","hmacWithSHA384","hmacWithSHA512"],r}if(!(t&&e in t))throw new Error("Unknown hash algorithm: "+e);return t[e].create()}function s(e,t,r,a){var n=u.create(u.Class.UNIVERSAL,u.Type.SEQUENCE,!0,[u.create(u.Class.UNIVERSAL,u.Type.OCTETSTRING,!1,e),u.create(u.Class.UNIVERSAL,u.Type.INTEGER,!1,t.getBytes())]);return"hmacWithSHA1"!==a&&n.value.push(u.create(u.Class.UNIVERSAL,u.Type.INTEGER,!1,o.util.hexToBytes(r.toString(16))),u.create(u.Class.UNIVERSAL,u.Type.SEQUENCE,!0,[u.create(u.Class.UNIVERSAL,u.Type.OID,!1,u.oidToDer(l.oids[a]).getBytes()),u.create(u.Class.UNIVERSAL,u.Type.NULL,!1,"")])),n}var o=r(0);if(r(5),r(3),r(10),r(4),r(6),r(15),r(7),r(2),r(25),r(11),r(1),void 0===c)var c=o.jsbn.BigInteger;var u=o.asn1,l=o.pki=o.pki||{};e.exports=l.pbe=o.pbe=o.pbe||{};var p=l.oids,f={name:"EncryptedPrivateKeyInfo",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedPrivateKeyInfo.encryptionAlgorithm",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:u.Class.UNIVERSAL,type:u.Type.OID,constructed:!1,capture:"encryptionOid"},{name:"AlgorithmIdentifier.parameters",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,captureAsn1:"encryptionParams"}]},{name:"EncryptedPrivateKeyInfo.encryptedData",tagClass:u.Class.UNIVERSAL,type:u.Type.OCTETSTRING,constructed:!1,capture:"encryptedData"}]},h={name:"PBES2Algorithms",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.keyDerivationFunc.oid",tagClass:u.Class.UNIVERSAL,type:u.Type.OID,constructed:!1,capture:"kdfOid"},{name:"PBES2Algorithms.params",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.params.salt",tagClass:u.Class.UNIVERSAL,type:u.Type.OCTETSTRING,constructed:!1,capture:"kdfSalt"},{name:"PBES2Algorithms.params.iterationCount",tagClass:u.Class.UNIVERSAL,type:u.Type.INTEGER,constructed:!1,capture:"kdfIterationCount"},{name:"PBES2Algorithms.params.keyLength",tagClass:u.Class.UNIVERSAL,type:u.Type.INTEGER,constructed:!1,optional:!0,capture:"keyLength"},{name:"PBES2Algorithms.params.prf",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,optional:!0,value:[{name:"PBES2Algorithms.params.prf.algorithm",tagClass:u.Class.UNIVERSAL,type:u.Type.OID,constructed:!1,capture:"prfOid"}]}]}]},{name:"PBES2Algorithms.encryptionScheme",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,value:[{name:"PBES2Algorithms.encryptionScheme.oid",tagClass:u.Class.UNIVERSAL,type:u.Type.OID,constructed:!1,capture:"encOid"},{name:"PBES2Algorithms.encryptionScheme.iv",tagClass:u.Class.UNIVERSAL,type:u.Type.OCTETSTRING,constructed:!1,capture:"encIv"}]}]},d={name:"pkcs-12PbeParams",tagClass:u.Class.UNIVERSAL,type:u.Type.SEQUENCE,constructed:!0,value:[{name:"pkcs-12PbeParams.salt",tagClass:u.Class.UNIVERSAL,type:u.Type.OCTETSTRING,constructed:!1,capture:"salt"},{name:"pkcs-12PbeParams.iterations",tagClass:u.Class.UNIVERSAL,type:u.Type.INTEGER,constructed:!1,capture:"iterations"}]};l.encryptPrivateKeyInfo=function(e,t,r){r=r||{},r.saltSize=r.saltSize||8,r.count=r.count||2048,r.algorithm=r.algorithm||"aes128",r.prfAlgorithm=r.prfAlgorithm||"sha1";var a,n,c,f=o.random.getBytesSync(r.saltSize),h=r.count,d=u.integerToDer(h);if(0===r.algorithm.indexOf("aes")||"des"===r.algorithm){var y,g,v;switch(r.algorithm){case"aes128":a=16,y=16,g=p["aes128-CBC"],v=o.aes.createEncryptionCipher;break;case"aes192":a=24,y=16,g=p["aes192-CBC"],v=o.aes.createEncryptionCipher;break;case"aes256":a=32,y=16,g=p["aes256-CBC"],v=o.aes.createEncryptionCipher;break;case"des":a=8,y=8,g=p.desCBC,v=o.des.createEncryptionCipher;break;default:var m=new Error("Cannot encrypt private key. Unknown encryption algorithm.");throw m.algorithm=r.algorithm,m}var C="hmacWith"+r.prfAlgorithm.toUpperCase(),E=i(C),S=o.pkcs5.pbkdf2(t,f,h,a,E),T=o.random.getBytesSync(y),I=v(S);I.start(T),I.update(u.toDer(e)),I.finish(),c=I.output.getBytes();var b=s(f,d,a,C);n=u.create(u.Class.UNIVERSAL,u.Type.SEQUENCE,!0,[u.create(u.Class.UNIVERSAL,u.Type.OID,!1,u.oidToDer(p.pkcs5PBES2).getBytes()),u.create(u.Class.UNIVERSAL,u.Type.SEQUENCE,!0,[u.create(u.Class.UNIVERSAL,u.Type.SEQUENCE,!0,[u.create(u.Class.UNIVERSAL,u.Type.OID,!1,u.oidToDer(p.pkcs5PBKDF2).getBytes()),b]),u.create(u.Class.UNIVERSAL,u.Type.SEQUENCE,!0,[u.create(u.Class.UNIVERSAL,u.Type.OID,!1,u.oidToDer(g).getBytes()),u.create(u.Class.UNIVERSAL,u.Type.OCTETSTRING,!1,T)])])])}else{if("3des"!==r.algorithm){var m=new Error("Cannot encrypt private key. Unknown encryption algorithm.");throw m.algorithm=r.algorithm,m}a=24;var A=new o.util.ByteBuffer(f),S=l.pbe.generatePkcs12Key(t,A,1,h,a),T=l.pbe.generatePkcs12Key(t,A,2,h,a),I=o.des.createEncryptionCipher(S);I.start(T),I.update(u.toDer(e)),I.finish(),c=I.output.getBytes(),n=u.create(u.Class.UNIVERSAL,u.Type.SEQUENCE,!0,[u.create(u.Class.UNIVERSAL,u.Type.OID,!1,u.oidToDer(p["pbeWithSHAAnd3-KeyTripleDES-CBC"]).getBytes()),u.create(u.Class.UNIVERSAL,u.Type.SEQUENCE,!0,[u.create(u.Class.UNIVERSAL,u.Type.OCTETSTRING,!1,f),u.create(u.Class.UNIVERSAL,u.Type.INTEGER,!1,d.getBytes())])])}return u.create(u.Class.UNIVERSAL,u.Type.SEQUENCE,!0,[n,u.create(u.Class.UNIVERSAL,u.Type.OCTETSTRING,!1,c)])},l.decryptPrivateKeyInfo=function(e,t){var r=null,a={},n=[];if(!u.validate(e,f,a,n)){var i=new Error("Cannot read encrypted private key. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw i.errors=n,i}var s=u.derToOid(a.encryptionOid),c=l.pbe.getCipher(s,a.encryptionParams,t),p=o.util.createBuffer(a.encryptedData);return c.update(p),c.finish()&&(r=u.fromDer(c.output)),r},l.encryptedPrivateKeyToPem=function(e,t){var r={type:"ENCRYPTED PRIVATE KEY",body:u.toDer(e).getBytes()};return o.pem.encode(r,{maxline:t})},l.encryptedPrivateKeyFromPem=function(e){var t=o.pem.decode(e)[0];if("ENCRYPTED PRIVATE KEY"!==t.type){var r=new Error('Could not convert encrypted private key from PEM; PEM header type is "ENCRYPTED PRIVATE KEY".');throw r.headerType=t.type,r}if(t.procType&&"ENCRYPTED"===t.procType.type)throw new Error("Could not convert encrypted private key from PEM; PEM is encrypted.");return u.fromDer(t.body)},l.encryptRsaPrivateKey=function(e,t,r){if(r=r||{},!r.legacy){var a=l.wrapRsaPrivateKey(l.privateKeyToAsn1(e));return a=l.encryptPrivateKeyInfo(a,t,r),l.encryptedPrivateKeyToPem(a)}var n,i,s,c;switch(r.algorithm){case"aes128":n="AES-128-CBC",s=16,i=o.random.getBytesSync(16),c=o.aes.createEncryptionCipher;break;case"aes192":n="AES-192-CBC",s=24,i=o.random.getBytesSync(16),c=o.aes.createEncryptionCipher;break;case"aes256":n="AES-256-CBC",s=32,i=o.random.getBytesSync(16),c=o.aes.createEncryptionCipher;break;case"3des":n="DES-EDE3-CBC",s=24,i=o.random.getBytesSync(8),c=o.des.createEncryptionCipher;break;case"des":n="DES-CBC",s=8,i=o.random.getBytesSync(8),c=o.des.createEncryptionCipher;break;default:var p=new Error('Could not encrypt RSA private key; unsupported encryption algorithm "'+r.algorithm+'".');throw p.algorithm=r.algorithm,p}var f=o.pbe.opensslDeriveBytes(t,i.substr(0,8),s),h=c(f);h.start(i),h.update(u.toDer(l.privateKeyToAsn1(e))),h.finish();var d={type:"RSA PRIVATE KEY",procType:{version:"4",type:"ENCRYPTED"},dekInfo:{algorithm:n,parameters:o.util.bytesToHex(i).toUpperCase()},body:h.output.getBytes()};return o.pem.encode(d)},l.decryptRsaPrivateKey=function(e,t){var r=null,a=o.pem.decode(e)[0];if("ENCRYPTED PRIVATE KEY"!==a.type&&"PRIVATE KEY"!==a.type&&"RSA PRIVATE KEY"!==a.type){var n=new Error('Could not convert private key from PEM; PEM header type is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".');throw n.headerType=n,n}if(a.procType&&"ENCRYPTED"===a.procType.type){var i,s;switch(a.dekInfo.algorithm){case"DES-CBC":i=8,s=o.des.createDecryptionCipher;break;case"DES-EDE3-CBC":i=24,s=o.des.createDecryptionCipher;break;case"AES-128-CBC":i=16,s=o.aes.createDecryptionCipher;break;case"AES-192-CBC":i=24,s=o.aes.createDecryptionCipher;break;case"AES-256-CBC":i=32,s=o.aes.createDecryptionCipher;break;case"RC2-40-CBC":i=5,s=function(e){return o.rc2.createDecryptionCipher(e,40)};break;case"RC2-64-CBC":i=8,s=function(e){return o.rc2.createDecryptionCipher(e,64)};break;case"RC2-128-CBC":i=16,s=function(e){return o.rc2.createDecryptionCipher(e,128)};break;default:var n=new Error('Could not decrypt private key; unsupported encryption algorithm "'+a.dekInfo.algorithm+'".');throw n.algorithm=a.dekInfo.algorithm,n}var c=o.util.hexToBytes(a.dekInfo.parameters),p=o.pbe.opensslDeriveBytes(t,c.substr(0,8),i),f=s(p);if(f.start(c),f.update(o.util.createBuffer(a.body)),!f.finish())return r;r=f.output.getBytes()}else r=a.body;return r="ENCRYPTED PRIVATE KEY"===a.type?l.decryptPrivateKeyInfo(u.fromDer(r),t):u.fromDer(r),null!==r&&(r=l.privateKeyFromAsn1(r)),r},l.pbe.generatePkcs12Key=function(e,t,r,a,n,i){var s,c;if(void 0===i||null===i){if(!("sha1"in o.md))throw new Error('"sha1" hash algorithm unavailable.');i=o.md.sha1.create()}var u=i.digestLength,l=i.blockLength,p=new o.util.ByteBuffer,f=new o.util.ByteBuffer;if(null!==e&&void 0!==e){for(c=0;c=0;c--)w>>=8,w+=A.at(c)+k.at(c),k.setAt(c,255&w);N.putBuffer(k)}E=N,p.putBuffer(I)}return p.truncate(p.length()-n),p},l.pbe.getCipher=function(e,t,r){switch(e){case l.oids.pkcs5PBES2:return l.pbe.getCipherForPBES2(e,t,r);case l.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:case l.oids["pbewithSHAAnd40BitRC2-CBC"]:return l.pbe.getCipherForPKCS12PBE(e,t,r);default:var a=new Error("Cannot read encrypted PBE data block. Unsupported OID.");throw a.oid=e,a.supportedOids=["pkcs5PBES2","pbeWithSHAAnd3-KeyTripleDES-CBC","pbewithSHAAnd40BitRC2-CBC"],a}},l.pbe.getCipherForPBES2=function(e,t,r){var a={},i=[];if(!u.validate(t,h,a,i)){var s=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw s.errors=i,s}if((e=u.derToOid(a.kdfOid))!==l.oids.pkcs5PBKDF2){var s=new Error("Cannot read encrypted private key. Unsupported key derivation function OID.");throw s.oid=e,s.supportedOids=["pkcs5PBKDF2"],s}if((e=u.derToOid(a.encOid))!==l.oids["aes128-CBC"]&&e!==l.oids["aes192-CBC"]&&e!==l.oids["aes256-CBC"]&&e!==l.oids["des-EDE3-CBC"]&&e!==l.oids.desCBC){var s=new Error("Cannot read encrypted private key. Unsupported encryption scheme OID.");throw s.oid=e,s.supportedOids=["aes128-CBC","aes192-CBC","aes256-CBC","des-EDE3-CBC","desCBC"],s}var c=a.kdfSalt,p=o.util.createBuffer(a.kdfIterationCount);p=p.getInt(p.length()<<3);var f,d;switch(l.oids[e]){case"aes128-CBC":f=16,d=o.aes.createDecryptionCipher;break;case"aes192-CBC":f=24,d=o.aes.createDecryptionCipher;break;case"aes256-CBC":f=32,d=o.aes.createDecryptionCipher;break;case"des-EDE3-CBC":f=24,d=o.des.createDecryptionCipher;break;case"desCBC":f=8,d=o.des.createDecryptionCipher}var y=n(a.prfOid),g=o.pkcs5.pbkdf2(r,c,p,f,y),v=a.encIv,m=d(g);return m.start(v),m},l.pbe.getCipherForPKCS12PBE=function(e,t,r){var a={},i=[];if(!u.validate(t,d,a,i)){var s=new Error("Cannot read password-based-encryption algorithm parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.");throw s.errors=i,s}var c=o.util.createBuffer(a.salt),p=o.util.createBuffer(a.iterations);p=p.getInt(p.length()<<3);var f,h,y;switch(e){case l.oids["pbeWithSHAAnd3-KeyTripleDES-CBC"]:f=24,h=8,y=o.des.startDecrypting;break;case l.oids["pbewithSHAAnd40BitRC2-CBC"]:f=5,h=8,y=function(e,t){var r=o.rc2.createDecryptionCipher(e,40);return r.start(t,null),r};break;default:var s=new Error("Cannot read PKCS #12 PBE data block. Unsupported OID.");throw s.oid=e,s}var g=n(a.prfOid),v=l.pbe.generatePkcs12Key(r,c,1,p,f,g);return g.start(),y(v,l.pbe.generatePkcs12Key(r,c,2,p,h,g))},l.pbe.opensslDeriveBytes=function(e,t,r,n){if(void 0===n||null===n){if(!("md5"in o.md))throw new Error('"md5" hash algorithm unavailable.');n=o.md.md5.create()}null===t&&(t="");for(var i=[a(n,e+t)],s=16,c=1;s=64;){for(l=0;l<16;++l)t[l]=r.getInt32();for(;l<64;++l)a=t[l-2],a=(a>>>17|a<<15)^(a>>>19|a<<13)^a>>>10,n=t[l-15],n=(n>>>7|n<<25)^(n>>>18|n<<14)^n>>>3,t[l]=a+t[l-7]+n+t[l-16]|0;for(p=e.h0,f=e.h1,h=e.h2,d=e.h3,y=e.h4,g=e.h5,v=e.h6,m=e.h7,l=0;l<64;++l)s=(y>>>6|y<<26)^(y>>>11|y<<21)^(y>>>25|y<<7),o=v^y&(g^v),i=(p>>>2|p<<30)^(p>>>13|p<<19)^(p>>>22|p<<10),c=p&f|h&(p^f),a=m+s+o+u[l]+t[l],n=i+c,m=v,v=g,g=y,y=d+a>>>0,d=h,h=f,f=p,p=a+n>>>0;e.h0=e.h0+p|0,e.h1=e.h1+f|0,e.h2=e.h2+h|0,e.h3=e.h3+d|0,e.h4=e.h4+y|0,e.h5=e.h5+g|0,e.h6=e.h6+v|0,e.h7=e.h7+m|0,C-=64}}var i=r(0);r(4),r(1);var s=e.exports=i.sha256=i.sha256||{};i.md.sha256=i.md.algorithms.sha256=s,s.create=function(){c||a();var e=null,t=i.util.createBuffer(),r=new Array(64),s={algorithm:"sha256",blockLength:64,digestLength:32,messageLength:0,fullMessageLength:null,messageLengthSize:8};return s.start=function(){s.messageLength=0,s.fullMessageLength=s.messageLength64=[];for(var r=s.messageLengthSize/4,a=0;a>>0,c>>>0];for(var u=s.fullMessageLength.length-1;u>=0;--u)s.fullMessageLength[u]+=c[1],c[1]=c[0]+(s.fullMessageLength[u]/4294967296>>>0),s.fullMessageLength[u]=s.fullMessageLength[u]>>>0,c[0]=c[1]/4294967296>>>0;return t.putBytes(a),n(e,r,t),(t.read>2048||0===t.length())&&t.compact(),s},s.digest=function(){var a=i.util.createBuffer();a.putBytes(t.bytes());var c=s.fullMessageLength[s.fullMessageLength.length-1]+s.messageLengthSize,u=c&s.blockLength-1;a.putBytes(o.substr(0,s.blockLength-u));for(var l,p,f=8*s.fullMessageLength[0],h=0;h>>0,f+=p,a.putInt32(f>>>0),f=l>>>0;a.putInt32(f);var d={h0:e.h0,h1:e.h1,h2:e.h2,h3:e.h3,h4:e.h4,h5:e.h5,h6:e.h6,h7:e.h7};n(d,r,a);var y=i.util.createBuffer();return y.putInt32(d.h0),y.putInt32(d.h1),y.putInt32(d.h2),y.putInt32(d.h3),y.putInt32(d.h4),y.putInt32(d.h5),y.putInt32(d.h6),y.putInt32(d.h7),y},s};var o=null,c=!1,u=null},function(e,t,r){var a=r(0);r(1);var n=null;!a.util.isNodejs||a.options.usePureJavaScript||process.versions["node-webkit"]||(n=r(16)),(e.exports=a.prng=a.prng||{}).create=function(e){function t(e){if(o.pools[0].messageLength>=32)return i(),e();var t=32-o.pools[0].messageLength<<5;o.seedFile(t,function(t,r){if(t)return e(t);o.collect(r),i(),e()})}function r(){if(o.pools[0].messageLength>=32)return i();var e=32-o.pools[0].messageLength<<5;o.collect(o.seedFileSync(e)),i()}function i(){o.reseeds=4294967295===o.reseeds?0:o.reseeds+1;var e=o.plugin.md.create();e.update(o.keyBytes);for(var t=1,r=0;r<32;++r)o.reseeds%t==0&&(e.update(o.pools[r].digest().getBytes()),o.pools[r].start()),t<<=1;o.keyBytes=e.digest().getBytes(),e.start(),e.update(o.keyBytes);var a=e.digest().getBytes();o.key=o.plugin.formatKey(o.keyBytes),o.seed=o.plugin.formatSeed(a),o.generated=0}function s(e){var t=null,r=a.util.globalScope,n=r.crypto||r.msCrypto;n&&n.getRandomValues&&(t=function(e){return n.getRandomValues(e)});var i=a.util.createBuffer();if(t)for(;i.length()>16),l+=(32767&u)<<16,l+=u>>15,l=(2147483647&l)+(l>>31),f=4294967295&l;for(var c=0;c<3;++c)p=f>>>(c<<3),p^=Math.floor(256*Math.random()),i.putByte(String.fromCharCode(255&p))}return i.getBytes(e)}for(var o={plugin:e,key:null,seed:null,time:null,reseeds:0,generated:0,keyBytes:""},c=e.md,u=new Array(32),l=0;l<32;++l)u[l]=c.create();return o.pools=u,o.pool=0,o.generate=function(e,r){function n(p){if(p)return r(p);if(l.length()>=e)return r(null,l.getBytes(e));if(o.generated>1048575&&(o.key=null),null===o.key)return a.util.nextTick(function(){t(n)});var f=i(o.key,o.seed);o.generated+=f.length,l.putBytes(f),o.key=c(i(o.key,s(o.seed))),o.seed=u(i(o.key,o.seed)),a.util.setImmediate(n)}if(!r)return o.generateSync(e);var i=o.plugin.cipher,s=o.plugin.increment,c=o.plugin.formatKey,u=o.plugin.formatSeed,l=a.util.createBuffer();o.key=null,n()},o.generateSync=function(e){var t=o.plugin.cipher,n=o.plugin.increment,i=o.plugin.formatKey,s=o.plugin.formatSeed;o.key=null;for(var c=a.util.createBuffer();c.length()1048575&&(o.key=null),null===o.key&&r();var u=t(o.key,o.seed);o.generated+=u.length,c.putBytes(u),o.key=i(t(o.key,n(o.seed))),o.seed=s(t(o.key,o.seed))}return c.getBytes(e)},n?(o.seedFile=function(e,t){n.randomBytes(e,function(e,r){if(e)return t(e);t(null,r.toString())})},o.seedFileSync=function(e){return n.randomBytes(e).toString()}):(o.seedFile=function(e,t){try{t(null,s(e))}catch(e){t(e)}},o.seedFileSync=s),o.collect=function(e){for(var t=e.length,r=0;r>a&255);o.collect(r)},o.registerWorker=function(e){if(e===self)o.seedFile=function(e,t){function r(e){var a=e.data;a.forge&&a.forge.prng&&(self.removeEventListener("message",r),t(a.forge.prng.err,a.forge.prng.bytes))}self.addEventListener("message",r),self.postMessage({forge:{prng:{needed:e}}})};else{var t=function(t){var r=t.data;r.forge&&r.forge.prng&&o.seedFile(r.forge.prng.needed,function(t,r){e.postMessage({forge:{prng:{err:t,bytes:r}}})})};e.addEventListener("message",t)}},o}},function(e,t,r){var a=r(0);r(1);var n=[217,120,249,196,25,221,181,237,40,233,253,121,74,160,216,157,198,126,55,131,43,118,83,142,98,76,100,136,68,139,251,162,23,154,89,245,135,179,79,19,97,69,109,141,9,129,125,50,189,143,64,235,134,183,123,11,240,149,33,34,92,107,78,130,84,214,101,147,206,96,178,28,115,86,192,20,167,140,241,220,18,117,202,31,59,190,228,209,66,61,212,48,163,60,182,38,111,191,14,218,70,105,7,87,39,242,29,155,188,148,67,3,248,17,199,246,144,239,62,231,6,195,213,47,200,102,30,215,8,232,234,222,128,82,238,247,132,170,114,172,53,77,106,42,150,26,210,113,90,21,73,116,75,159,208,94,4,24,164,236,194,224,65,110,15,81,203,204,36,145,175,80,161,244,112,57,153,124,58,133,35,184,180,122,252,2,54,91,37,85,151,49,45,93,250,152,227,138,146,174,5,223,41,16,103,108,186,201,211,0,230,207,225,158,168,44,99,22,1,63,88,226,137,169,13,56,52,27,171,51,255,176,187,72,12,95,185,177,205,46,197,243,219,71,229,165,156,119,10,166,32,104,254,127,193,173],i=[1,2,3,5],s=function(e,t){return e<>16-t},o=function(e,t){return(65535&e)>>t|e<<16-t&65535};e.exports=a.rc2=a.rc2||{},a.rc2.expandKey=function(e,t){"string"==typeof e&&(e=a.util.createBuffer(e)),t=t||128;var r,i=e,s=e.length(),o=t,c=Math.ceil(o/8),u=255>>(7&o);for(r=s;r<128;r++)i.putByte(n[i.at(r-1)+i.at(r-s)&255]);for(i.setAt(128-c,n[i.at(128-c)&u]),r=127-c;r>=0;r--)i.setAt(r,n[i.at(r+1)^i.at(r+c)]);return i};var c=function(e,t,r){var n,c,u,l,p=!1,f=null,h=null,d=null,y=[];for(e=a.rc2.expandKey(e,t),u=0;u<64;u++)y.push(e.getInt16Le());r?(n=function(e){for(u=0;u<4;u++)e[u]+=y[l]+(e[(u+3)%4]&e[(u+2)%4])+(~e[(u+3)%4]&e[(u+1)%4]),e[u]=s(e[u],i[u]),l++},c=function(e){for(u=0;u<4;u++)e[u]+=y[63&e[(u+3)%4]]}):(n=function(e){for(u=3;u>=0;u--)e[u]=o(e[u],i[u]),e[u]-=y[l]+(e[(u+3)%4]&e[(u+2)%4])+(~e[(u+3)%4]&e[(u+1)%4]),l--},c=function(e){for(u=3;u>=0;u--)e[u]-=y[63&e[(u+3)%4]]});var g=function(e){var t=[];for(u=0;u<4;u++){var a=f.getInt16Le();null!==d&&(r?a^=d.getInt16Le():d.putInt16Le(a)),t.push(65535&a)}l=r?0:63;for(var n=0;n=8;)g([[5,n],[1,c],[6,n],[1,c],[5,n]])},finish:function(e){var t=!0;if(r)if(e)t=e(8,f,!r);else{var a=8===f.length()?8:8-f.length();f.fillWithByte(a,a)}if(t&&(p=!0,v.update()),!r&&(t=0===f.length()))if(e)t=e(8,h,!r);else{var n=h.length(),i=h.at(n-1);i>n?t=!1:h.truncate(i)}return t}}};a.rc2.startEncrypting=function(e,t,r){var n=a.rc2.createEncryptionCipher(e,128);return n.start(t,r),n},a.rc2.createEncryptionCipher=function(e,t){return c(e,t,!0)},a.rc2.startDecrypting=function(e,t,r){var n=a.rc2.createDecryptionCipher(e,128);return n.start(t,r),n},a.rc2.createDecryptionCipher=function(e,t){return c(e,t,!1)}},function(e,t,r){function a(e,t,r){r||(r=n.md.sha1.create());for(var a="",i=Math.ceil(t/r.digestLength),s=0;s>24&255,s>>16&255,s>>8&255,255&s);r.start(),r.update(e+o),a+=r.digest().getBytes()}return a.substring(0,t)}var n=r(0);r(1),r(2),r(9);var i=e.exports=n.pkcs1=n.pkcs1||{};i.encode_rsa_oaep=function(e,t,r){var i,s,o,c;"string"==typeof r?(i=r,s=arguments[3]||void 0,o=arguments[4]||void 0):r&&(i=r.label||void 0,s=r.seed||void 0,o=r.md||void 0,r.mgf1&&r.mgf1.md&&(c=r.mgf1.md)),o?o.start():o=n.md.sha1.create(),c||(c=o);var u=Math.ceil(e.n.bitLength()/8),l=u-2*o.digestLength-2;if(t.length>l){var p=new Error("RSAES-OAEP input message length is too long.");throw p.length=t.length,p.maxLength=l,p}i||(i=""),o.update(i,"raw");for(var f=o.digest(),h="",d=l-t.length,y=0;yt&&(e=s(t,r)),e.isProbablePrime(o))return u(null,e);e.dAddOffset(l[i++%8],0)}while(c<0||+new Date-pe&&(c=s(e,t));var h=c.toString(16);r.target.postMessage({hex:h,workLoad:p}),c.dAddOffset(f,0)}}l=Math.max(1,l);for(var a=[],n=0;n=0&&n.push(o):n.push(o))}return n}function n(e){if(e.composed||e.constructed){for(var t=u.util.createBuffer(),r=0;r0&&(n=l.create(l.Class.UNIVERSAL,l.Type.SET,!0,c));var h=[],d=[];null!==t&&(d=u.util.isArray(t)?t:[t]);for(var y=[],g=0;g0){var E=l.create(l.Class.UNIVERSAL,l.Type.SEQUENCE,!0,y),S=l.create(l.Class.UNIVERSAL,l.Type.SEQUENCE,!0,[l.create(l.Class.UNIVERSAL,l.Type.OID,!1,l.oidToDer(p.oids.data).getBytes()),l.create(l.Class.CONTEXT_SPECIFIC,0,!0,[l.create(l.Class.UNIVERSAL,l.Type.OCTETSTRING,!1,l.toDer(E).getBytes())])]);h.push(S)}var T=null;if(null!==e){var I=p.wrapRsaPrivateKey(p.privateKeyToAsn1(e));T=null===r?l.create(l.Class.UNIVERSAL,l.Type.SEQUENCE,!0,[l.create(l.Class.UNIVERSAL,l.Type.OID,!1,l.oidToDer(p.oids.keyBag).getBytes()),l.create(l.Class.CONTEXT_SPECIFIC,0,!0,[I]),n]):l.create(l.Class.UNIVERSAL,l.Type.SEQUENCE,!0,[l.create(l.Class.UNIVERSAL,l.Type.OID,!1,l.oidToDer(p.oids.pkcs8ShroudedKeyBag).getBytes()),l.create(l.Class.CONTEXT_SPECIFIC,0,!0,[p.encryptPrivateKeyInfo(I,r,a)]),n]);var b=l.create(l.Class.UNIVERSAL,l.Type.SEQUENCE,!0,[T]),A=l.create(l.Class.UNIVERSAL,l.Type.SEQUENCE,!0,[l.create(l.Class.UNIVERSAL,l.Type.OID,!1,l.oidToDer(p.oids.data).getBytes()),l.create(l.Class.CONTEXT_SPECIFIC,0,!0,[l.create(l.Class.UNIVERSAL,l.Type.OCTETSTRING,!1,l.toDer(b).getBytes())])]);h.push(A)}var B,N=l.create(l.Class.UNIVERSAL,l.Type.SEQUENCE,!0,h);if(a.useMac){var o=u.md.sha1.create(),k=new u.util.ByteBuffer(u.random.getBytes(a.saltSize)),w=a.count,e=f.generateKey(r,k,3,w,20),R=u.hmac.create();R.start(o,e),R.update(l.toDer(N).getBytes());var _=R.getMac();B=l.create(l.Class.UNIVERSAL,l.Type.SEQUENCE,!0,[l.create(l.Class.UNIVERSAL,l.Type.SEQUENCE,!0,[l.create(l.Class.UNIVERSAL,l.Type.SEQUENCE,!0,[l.create(l.Class.UNIVERSAL,l.Type.OID,!1,l.oidToDer(p.oids.sha1).getBytes()),l.create(l.Class.UNIVERSAL,l.Type.NULL,!1,"")]),l.create(l.Class.UNIVERSAL,l.Type.OCTETSTRING,!1,_.getBytes())]),l.create(l.Class.UNIVERSAL,l.Type.OCTETSTRING,!1,k.getBytes()),l.create(l.Class.UNIVERSAL,l.Type.INTEGER,!1,l.integerToDer(w).getBytes())])}return l.create(l.Class.UNIVERSAL,l.Type.SEQUENCE,!0,[l.create(l.Class.UNIVERSAL,l.Type.INTEGER,!1,l.integerToDer(3).getBytes()),l.create(l.Class.UNIVERSAL,l.Type.SEQUENCE,!0,[l.create(l.Class.UNIVERSAL,l.Type.OID,!1,l.oidToDer(p.oids.data).getBytes()),l.create(l.Class.CONTEXT_SPECIFIC,0,!0,[l.create(l.Class.UNIVERSAL,l.Type.OCTETSTRING,!1,l.toDer(N).getBytes())])]),B])},f.generateKey=u.pbe.generatePkcs12Key},function(e,t,r){var a=r(0);r(3),r(1);var n=a.asn1,i=e.exports=a.pkcs7asn1=a.pkcs7asn1||{};a.pkcs7=a.pkcs7||{},a.pkcs7.asn1=i;var s={name:"ContentInfo",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"ContentInfo.ContentType",tagClass:n.Class.UNIVERSAL,type:n.Type.OID,constructed:!1,capture:"contentType"},{name:"ContentInfo.content",tagClass:n.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,captureAsn1:"content"}]};i.contentInfoValidator=s;var o={name:"EncryptedContentInfo",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentType",tagClass:n.Class.UNIVERSAL,type:n.Type.OID,constructed:!1,capture:"contentType"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedContentInfo.contentEncryptionAlgorithm.algorithm",tagClass:n.Class.UNIVERSAL,type:n.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"EncryptedContentInfo.contentEncryptionAlgorithm.parameter",tagClass:n.Class.UNIVERSAL,captureAsn1:"encParameter"}]},{name:"EncryptedContentInfo.encryptedContent",tagClass:n.Class.CONTEXT_SPECIFIC,type:0,capture:"encryptedContent",captureAsn1:"encryptedContentAsn1"}]};i.envelopedDataValidator={name:"EnvelopedData",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"EnvelopedData.Version",tagClass:n.Class.UNIVERSAL,type:n.Type.INTEGER,constructed:!1,capture:"version"},{name:"EnvelopedData.RecipientInfos",tagClass:n.Class.UNIVERSAL,type:n.Type.SET,constructed:!0,captureAsn1:"recipientInfos"}].concat(o)},i.encryptedDataValidator={name:"EncryptedData",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"EncryptedData.Version",tagClass:n.Class.UNIVERSAL,type:n.Type.INTEGER,constructed:!1,capture:"version"}].concat(o)};var c={name:"SignerInfo",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.version",tagClass:n.Class.UNIVERSAL,type:n.Type.INTEGER,constructed:!1},{name:"SignerInfo.issuerAndSerialNumber",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.issuerAndSerialNumber.issuer",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"SignerInfo.issuerAndSerialNumber.serialNumber",tagClass:n.Class.UNIVERSAL,type:n.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"SignerInfo.digestAlgorithm",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"SignerInfo.digestAlgorithm.algorithm",tagClass:n.Class.UNIVERSAL,type:n.Type.OID,constructed:!1,capture:"digestAlgorithm"},{name:"SignerInfo.digestAlgorithm.parameter",tagClass:n.Class.UNIVERSAL,constructed:!1,captureAsn1:"digestParameter",optional:!0}]},{name:"SignerInfo.authenticatedAttributes",tagClass:n.Class.CONTEXT_SPECIFIC,type:0,constructed:!0,optional:!0,capture:"authenticatedAttributes"},{name:"SignerInfo.digestEncryptionAlgorithm",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,capture:"signatureAlgorithm"},{name:"SignerInfo.encryptedDigest",tagClass:n.Class.UNIVERSAL,type:n.Type.OCTETSTRING,constructed:!1,capture:"signature"},{name:"SignerInfo.unauthenticatedAttributes",tagClass:n.Class.CONTEXT_SPECIFIC,type:1,constructed:!0,optional:!0,capture:"unauthenticatedAttributes"}]};i.signedDataValidator={name:"SignedData",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"SignedData.Version",tagClass:n.Class.UNIVERSAL,type:n.Type.INTEGER,constructed:!1,capture:"version"},{name:"SignedData.DigestAlgorithms",tagClass:n.Class.UNIVERSAL,type:n.Type.SET,constructed:!0,captureAsn1:"digestAlgorithms"},s,{name:"SignedData.Certificates",tagClass:n.Class.CONTEXT_SPECIFIC,type:0,optional:!0,captureAsn1:"certificates"},{name:"SignedData.CertificateRevocationLists",tagClass:n.Class.CONTEXT_SPECIFIC,type:1,optional:!0,captureAsn1:"crls"},{name:"SignedData.SignerInfos",tagClass:n.Class.UNIVERSAL,type:n.Type.SET,capture:"signerInfos",optional:!0,value:[c]}]},i.recipientInfoValidator={name:"RecipientInfo",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.version",tagClass:n.Class.UNIVERSAL,type:n.Type.INTEGER,constructed:!1,capture:"version"},{name:"RecipientInfo.issuerAndSerial",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.issuerAndSerial.issuer",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,captureAsn1:"issuer"},{name:"RecipientInfo.issuerAndSerial.serialNumber",tagClass:n.Class.UNIVERSAL,type:n.Type.INTEGER,constructed:!1,capture:"serial"}]},{name:"RecipientInfo.keyEncryptionAlgorithm",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"RecipientInfo.keyEncryptionAlgorithm.algorithm",tagClass:n.Class.UNIVERSAL,type:n.Type.OID,constructed:!1,capture:"encAlgorithm"},{name:"RecipientInfo.keyEncryptionAlgorithm.parameter",tagClass:n.Class.UNIVERSAL,constructed:!1,captureAsn1:"encParameter"}]},{name:"RecipientInfo.encryptedKey",tagClass:n.Class.UNIVERSAL,type:n.Type.OCTETSTRING,constructed:!1,capture:"encKey"}]}},function(e,t,r){var a=r(0);r(1),a.mgf=a.mgf||{},(e.exports=a.mgf.mgf1=a.mgf1=a.mgf1||{}).create=function(e){return{generate:function(t,r){for(var n=new a.util.ByteBuffer,i=Math.ceil(r/e.digestLength),s=0;s=128;){for(L=0;L<16;++L)t[L][0]=r.getInt32()>>>0,t[L][1]=r.getInt32()>>>0;for(;L<80;++L)P=t[L-2],U=P[0],D=P[1],a=((U>>>19|D<<13)^(D>>>29|U<<3)^U>>>6)>>>0,n=((U<<13|D>>>19)^(D<<3|U>>>29)^(U<<26|D>>>6))>>>0,O=t[L-15],U=O[0],D=O[1],i=((U>>>1|D<<31)^(U>>>8|D<<24)^U>>>7)>>>0,s=((U<<31|D>>>1)^(U<<24|D>>>8)^(U<<25|D>>>7))>>>0,V=t[L-7],K=t[L-16],D=n+V[1]+s+K[1],t[L][0]=a+V[0]+i+K[0]+(D/4294967296>>>0)>>>0,t[L][1]=D>>>0;for(g=e[0][0],v=e[0][1],m=e[1][0],C=e[1][1],E=e[2][0],S=e[2][1],T=e[3][0],I=e[3][1],b=e[4][0],A=e[4][1],B=e[5][0],N=e[5][1],k=e[6][0],w=e[6][1],R=e[7][0],_=e[7][1],L=0;L<80;++L)u=((b>>>14|A<<18)^(b>>>18|A<<14)^(A>>>9|b<<23))>>>0,p=((b<<18|A>>>14)^(b<<14|A>>>18)^(A<<23|b>>>9))>>>0,f=(k^b&(B^k))>>>0,h=(w^A&(N^w))>>>0,o=((g>>>28|v<<4)^(v>>>2|g<<30)^(v>>>7|g<<25))>>>0,c=((g<<4|v>>>28)^(v<<30|g>>>2)^(v<<25|g>>>7))>>>0,d=(g&m|E&(g^m))>>>0,y=(v&C|S&(v^C))>>>0,D=_+p+h+l[L][1]+t[L][1],a=R+u+f+l[L][0]+t[L][0]+(D/4294967296>>>0)>>>0,n=D>>>0,D=c+y,i=o+d+(D/4294967296>>>0)>>>0,s=D>>>0,R=k,_=w,k=B,w=N,B=b,N=A,D=I+n,b=T+a+(D/4294967296>>>0)>>>0,A=D>>>0,T=E,I=S,E=m,S=C,m=g,C=v,D=n+s,g=a+i+(D/4294967296>>>0)>>>0,v=D>>>0;D=e[0][1]+v,e[0][0]=e[0][0]+g+(D/4294967296>>>0)>>>0,e[0][1]=D>>>0,D=e[1][1]+C,e[1][0]=e[1][0]+m+(D/4294967296>>>0)>>>0,e[1][1]=D>>>0,D=e[2][1]+S,e[2][0]=e[2][0]+E+(D/4294967296>>>0)>>>0,e[2][1]=D>>>0,D=e[3][1]+I,e[3][0]=e[3][0]+T+(D/4294967296>>>0)>>>0,e[3][1]=D>>>0,D=e[4][1]+A,e[4][0]=e[4][0]+b+(D/4294967296>>>0)>>>0,e[4][1]=D>>>0,D=e[5][1]+N,e[5][0]=e[5][0]+B+(D/4294967296>>>0)>>>0,e[5][1]=D>>>0,D=e[6][1]+w,e[6][0]=e[6][0]+k+(D/4294967296>>>0)>>>0,e[6][1]=D>>>0,D=e[7][1]+_,e[7][0]=e[7][0]+R+(D/4294967296>>>0)>>>0,e[7][1]=D>>>0,x-=128}}var i=r(0);r(4),r(1);var s=e.exports=i.sha512=i.sha512||{};i.md.sha512=i.md.algorithms.sha512=s;var o=i.sha384=i.sha512.sha384=i.sha512.sha384||{};o.create=function(){return s.create("SHA-384")},i.md.sha384=i.md.algorithms.sha384=o,i.sha512.sha256=i.sha512.sha256||{create:function(){return s.create("SHA-512/256")}},i.md["sha512/256"]=i.md.algorithms["sha512/256"]=i.sha512.sha256,i.sha512.sha224=i.sha512.sha224||{create:function(){return s.create("SHA-512/224")}},i.md["sha512/224"]=i.md.algorithms["sha512/224"]=i.sha512.sha224,s.create=function(e){if(u||a(),void 0===e&&(e="SHA-512"),!(e in p))throw new Error("Invalid SHA-512 algorithm: "+e);for(var t=p[e],r=null,s=i.util.createBuffer(),o=new Array(80),l=0;l<80;++l)o[l]=new Array(2);var f=64;switch(e){case"SHA-384":f=48;break;case"SHA-512/256":f=32;break;case"SHA-512/224":f=28}var h={algorithm:e.replace("-","").toLowerCase(),blockLength:128,digestLength:f,messageLength:0,fullMessageLength:null,messageLengthSize:16};return h.start=function(){h.messageLength=0,h.fullMessageLength=h.messageLength128=[];for(var e=h.messageLengthSize/4,a=0;a>>0,a>>>0];for(var c=h.fullMessageLength.length-1;c>=0;--c)h.fullMessageLength[c]+=a[1],a[1]=a[0]+(h.fullMessageLength[c]/4294967296>>>0),h.fullMessageLength[c]=h.fullMessageLength[c]>>>0,a[0]=a[1]/4294967296>>>0;return s.putBytes(e),n(r,o,s),(s.read>2048||0===s.length())&&s.compact(),h},h.digest=function(){var t=i.util.createBuffer();t.putBytes(s.bytes());var a=h.fullMessageLength[h.fullMessageLength.length-1]+h.messageLengthSize,u=a&h.blockLength-1;t.putBytes(c.substr(0,h.blockLength-u));for(var l,p,f=8*h.fullMessageLength[0],d=0;d>>0,f+=p,t.putInt32(f>>>0),f=l>>>0;t.putInt32(f);for(var y=new Array(r.length),d=0;d0;)i.push(o%a),o=o/a|0}var c="";for(r=0;0===e.at(r)&&r=0;--r)c+=t[i[r]];return c}var a={};e.exports=a;var n={};a.encode=function(e,t,a){if("string"!=typeof t)throw new TypeError('"alphabet" must be a string.');if(void 0!==a&&"number"!=typeof a)throw new TypeError('"maxline" must be a number.');var n="";if(e instanceof Uint8Array){var i=0,s=t.length,o=t.charAt(0),c=[0];for(i=0;i0;)c.push(l%s),l=l/s|0}for(i=0;0===e[i]&&i=0;--i)n+=t[c[i]]}else n=r(e,t);if(a){var p=new RegExp(".{1,"+a+"}","g");n=n.match(p).join("\r\n")}return n},a.decode=function(e,t){if("string"!=typeof e)throw new TypeError('"input" must be a string.');if("string"!=typeof t)throw new TypeError('"alphabet" must be a string.');var r=n[t];if(!r){r=n[t]=[];for(var a=0;a>=8;for(;l>0;)o.push(255&l),l>>=8}for(var p=0;e[p]===s&&p=l.Versions.TLS_1_1.minor&&s.output.putBytes(n),s.update(e.fragment),s.finish(i)&&(e.fragment=s.output,e.length=e.fragment.length(),r=!0),r}function i(e,t,r){if(!r){var a=e-t.length()%e;t.fillWithByte(a-1,a)}return!0}function s(e,t,r){var a=!0;if(r){for(var n=t.length(),i=t.last(),s=n-1-i;s=i?(e.fragment=n.output.getBytes(p-i),o=n.output.getBytes(i)):e.fragment=n.output.getBytes(),e.fragment=u.util.createBuffer(e.fragment),e.length=e.fragment.length();var f=t.macFunction(t.macKey,t.sequenceNumber,e);return t.updateSequenceNumber(),a=c(t.macKey,o,f)&&a}function c(e,t,r){var a=u.hmac.create();return a.start("SHA1",e),a.update(t),t=a.digest().getBytes(),a.start(null,null),a.update(r),r=a.digest().getBytes(),t===r}var u=r(0);r(5),r(20);var l=e.exports=u.tls;l.CipherSuites.TLS_RSA_WITH_AES_128_CBC_SHA={id:[0,47],name:"TLS_RSA_WITH_AES_128_CBC_SHA",initSecurityParameters:function(e){e.bulk_cipher_algorithm=l.BulkCipherAlgorithm.aes,e.cipher_type=l.CipherType.block,e.enc_key_length=16,e.block_length=16,e.fixed_iv_length=16,e.record_iv_length=16,e.mac_algorithm=l.MACAlgorithm.hmac_sha1,e.mac_length=20,e.mac_key_length=20},initConnectionState:a},l.CipherSuites.TLS_RSA_WITH_AES_256_CBC_SHA={id:[0,53],name:"TLS_RSA_WITH_AES_256_CBC_SHA",initSecurityParameters:function(e){e.bulk_cipher_algorithm=l.BulkCipherAlgorithm.aes,e.cipher_type=l.CipherType.block,e.enc_key_length=32,e.block_length=16,e.fixed_iv_length=16,e.record_iv_length=16,e.mac_algorithm=l.MACAlgorithm.hmac_sha1,e.mac_length=20,e.mac_key_length=20},initConnectionState:a}},function(e,t,r){var a=r(0);r(30),e.exports=a.mgf=a.mgf||{},a.mgf.mgf1=a.mgf1},function(e,t,r){function a(e){var t=e.message;if(t instanceof Uint8Array||t instanceof K)return t;var r=e.encoding;if(void 0===t){if(!e.md)throw new TypeError('"options.message" or "options.md" not specified.');t=e.md.digest().getBytes(),r="binary"}if("string"==typeof t&&!r)throw new TypeError('"options.encoding" must be "binary" or "utf8".');if("string"==typeof t){if("undefined"!=typeof Buffer)return Buffer.from(t,r);t=new O(t,r)}else if(!(t instanceof O))throw new TypeError('"options.message" must be a node.js Buffer, a Uint8Array, a forge ByteBuffer, or a string with "options.encoding" specifying its encoding.');for(var a=new K(t.length()),n=0;n=32;--a){for(r=0,n=a-32,i=a-12;n>8,t[n]-=256*r;t[n]+=r,t[a]=0}for(r=0,n=0;n<32;++n)t[n]+=r-(t[31]>>4)*Q[n],r=t[n]>>8,t[n]&=255;for(n=0;n<32;++n)t[n]-=r*Q[n];for(a=0;a<32;++a)t[a+1]+=t[a]>>8,e[a]=255&t[a]}function u(e){for(var t=new Float64Array(64),r=0;r<64;++r)t[r]=e[r],e[r]=0;c(e,t)}function l(e,t){var r=N(),a=N(),n=N(),i=N(),s=N(),o=N(),c=N(),u=N(),l=N();w(r,e[1],e[0]),w(l,t[1],t[0]),_(r,r,l),k(a,e[0],e[1]),k(l,t[0],t[1]),_(a,a,l),_(n,e[3],t[3]),_(n,n,q),_(i,e[2],t[2]),k(i,i,i),w(s,a,r),w(o,i,n),k(c,i,n),k(u,a,r),_(e[0],s,o),_(e[1],u,c),_(e[2],c,o),_(e[3],s,u)}function p(e,t,r){for(var a=0;a<4;++a)B(e[a],t[a],r)}function f(e,t){var r=N(),a=N(),n=N();b(n,t[2]),_(r,t[0],n),_(a,t[1],n),h(e,a),e[31]^=E(r)<<7}function h(e,t){var r,a,n,i=N(),s=N();for(r=0;r<16;++r)s[r]=t[r];for(A(s),A(s),A(s),a=0;a<2;++a){for(i[0]=s[0]-65517,r=1;r<15;++r)i[r]=s[r]-65535-(i[r-1]>>16&1),i[r-1]&=65535;i[15]=s[15]-32767-(i[14]>>16&1),n=i[15]>>16&1,i[14]&=65535,B(s,i,1-n)}for(r=0;r<16;r++)e[2*r]=255&s[r],e[2*r+1]=s[r]>>8}function d(e,t){var r=N(),a=N(),n=N(),i=N(),s=N(),o=N(),c=N();return I(e[2],F),y(e[1],t),R(n,e[1]),_(i,n,j),w(n,n,e[2]),k(i,e[2],i),R(s,i),R(o,s),_(c,o,s),_(r,c,n),_(r,r,i),g(r,r),_(r,r,n),_(r,r,i),_(r,r,i),_(e[0],r,i),R(a,e[0]),_(a,a,i),v(a,n)&&_(e[0],e[0],z),R(a,e[0]),_(a,a,i),v(a,n)?-1:(E(e[0])===t[31]>>7&&w(e[0],M,e[0]),_(e[3],e[0],e[1]),0)}function y(e,t){var r;for(r=0;r<16;++r)e[r]=t[2*r]+(t[2*r+1]<<8);e[15]&=32767}function g(e,t){var r,a=N();for(r=0;r<16;++r)a[r]=t[r];for(r=250;r>=0;--r)R(a,a),1!==r&&_(a,a,t);for(r=0;r<16;++r)e[r]=a[r]}function v(e,t){var r=new K(32),a=new K(32);return h(r,e),h(a,t),m(r,0,a,0)}function m(e,t,r,a){return C(e,t,r,a,32)}function C(e,t,r,a,n){var i,s=0;for(i=0;i>>8)-1}function E(e){var t=new K(32);return h(t,e),1&t[0]}function S(e,t,r){var a,n;for(I(e[0],M),I(e[1],F),I(e[2],F),I(e[3],M),n=255;n>=0;--n)a=r[n/8|0]>>(7&n)&1,p(e,t,a),l(t,e),l(e,e),p(e,t,a)}function T(e,t){var r=[N(),N(),N(),N()];I(r[0],G),I(r[1],H),I(r[2],F),_(r[3],G,H),S(e,r,t)}function I(e,t){var r;for(r=0;r<16;r++)e[r]=0|t[r]}function b(e,t){var r,a=N();for(r=0;r<16;++r)a[r]=t[r];for(r=253;r>=0;--r)R(a,a),2!==r&&4!==r&&_(a,a,t);for(r=0;r<16;++r)e[r]=a[r]}function A(e){var t,r,a=1;for(t=0;t<16;++t)r=e[t]+a+65535,a=Math.floor(r/65536),e[t]=r-65536*a;e[0]+=a-1+37*(a-1)}function B(e,t,r){for(var a,n=~(r-1),i=0;i<16;++i)a=n&(e[i]^t[i]),e[i]^=a,t[i]^=a}function N(e){var t,r=new Float64Array(16);if(e)for(t=0;t=0};var M=N(),F=N([1]),j=N([30883,4953,19914,30187,55467,16705,2637,112,59544,30585,16505,36039,65139,11119,27886,20995]),q=N([61785,9906,39828,60374,45398,33411,5274,224,53552,61171,33010,6542,64743,22239,55772,9222]),G=N([54554,36645,11616,51542,42930,38181,51040,26924,56412,64982,57905,49316,21502,52590,14035,8553]),H=N([26200,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214,26214]),Q=new Float64Array([237,211,245,92,26,99,18,88,214,156,247,162,222,249,222,20,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16]),z=N([41136,18958,6951,50414,58488,44335,6150,12099,55207,15867,153,11085,57099,20417,9344,11139])},function(e,t,r){var a=r(0);r(3);var n=a.asn1;t.privateKeyValidator={name:"PrivateKeyInfo",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"PrivateKeyInfo.version",tagClass:n.Class.UNIVERSAL,type:n.Type.INTEGER,constructed:!1,capture:"privateKeyVersion"},{name:"PrivateKeyInfo.privateKeyAlgorithm",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:n.Class.UNIVERSAL,type:n.Type.OID,constructed:!1,capture:"privateKeyOid"}]},{name:"PrivateKeyInfo",tagClass:n.Class.UNIVERSAL,type:n.Type.OCTETSTRING,constructed:!1,capture:"privateKey"}]},t.publicKeyValidator={name:"SubjectPublicKeyInfo",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,captureAsn1:"subjectPublicKeyInfo",value:[{name:"SubjectPublicKeyInfo.AlgorithmIdentifier",tagClass:n.Class.UNIVERSAL,type:n.Type.SEQUENCE,constructed:!0,value:[{name:"AlgorithmIdentifier.algorithm",tagClass:n.Class.UNIVERSAL,type:n.Type.OID,constructed:!1,capture:"publicKeyOid"}]},{tagClass:n.Class.UNIVERSAL,type:n.Type.BITSTRING,constructed:!1,composed:!0,captureBitStringValue:"ed25519PublicKey"}]}},function(e,t,r){function a(e,t,r,a){e.generate=function(e,i){for(var s=new n.util.ByteBuffer,o=Math.ceil(i/a)+r,c=new n.util.ByteBuffer,u=r;u0&&(s=n.util.fillString(String.fromCharCode(0),c)+s),{encapsulation:t.encrypt(s,"NONE"),key:e.generate(s,a)}},a.decrypt=function(t,r,a){var n=t.decrypt(r,"NONE");return e.generate(n,a)},a},n.kem.kdf1=function(e,t){a(this,e,0,t||e.digestLength)},n.kem.kdf2=function(e,t){a(this,e,1,t||e.digestLength)}},function(e,t,r){e.exports=r(4),r(14),r(9),r(23),r(32)},function(e,t,r){function a(e){var t={},r=[];if(!d.validate(e,y.asn1.recipientInfoValidator,t,r)){var a=new Error("Cannot read PKCS#7 RecipientInfo. ASN.1 object is not an PKCS#7 RecipientInfo.");throw a.errors=r,a}return{version:t.version.charCodeAt(0),issuer:h.pki.RDNAttributesAsArray(t.issuer),serialNumber:h.util.createBuffer(t.serial).toHex(),encryptedContent:{algorithm:d.derToOid(t.encAlgorithm),parameter:t.encParameter.value,content:t.encKey}}}function n(e){return d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[d.create(d.Class.UNIVERSAL,d.Type.INTEGER,!1,d.integerToDer(e.version).getBytes()),d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[h.pki.distinguishedNameToAsn1({attributes:e.issuer}),d.create(d.Class.UNIVERSAL,d.Type.INTEGER,!1,h.util.hexToBytes(e.serialNumber))]),d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[d.create(d.Class.UNIVERSAL,d.Type.OID,!1,d.oidToDer(e.encryptedContent.algorithm).getBytes()),d.create(d.Class.UNIVERSAL,d.Type.NULL,!1,"")]),d.create(d.Class.UNIVERSAL,d.Type.OCTETSTRING,!1,e.encryptedContent.content)])}function i(e){for(var t=[],r=0;r0){for(var r=d.create(d.Class.CONTEXT_SPECIFIC,1,!0,[]),a=0;a=r&&n0&&n.value[0].value.push(d.create(d.Class.CONTEXT_SPECIFIC,0,!0,e)),a.length>0&&n.value[0].value.push(d.create(d.Class.CONTEXT_SPECIFIC,1,!0,a)),n.value[0].value.push(d.create(d.Class.UNIVERSAL,d.Type.SET,!0,r.signerInfos)),d.create(d.Class.UNIVERSAL,d.Type.SEQUENCE,!0,[d.create(d.Class.UNIVERSAL,d.Type.OID,!1,d.oidToDer(r.type).getBytes()),n])},addSigner:function(e){var t=e.issuer,a=e.serialNumber;if(e.certificate){var n=e.certificate;"string"==typeof n&&(n=h.pki.certificateFromPem(n)),t=n.issuer.attributes,a=n.serialNumber}var i=e.key;if(!i)throw new Error("Could not add PKCS#7 signer; no private key specified.");"string"==typeof i&&(i=h.pki.privateKeyFromPem(i));var s=e.digestAlgorithm||h.pki.oids.sha1;switch(s){case h.pki.oids.sha1:case h.pki.oids.sha256:case h.pki.oids.sha384:case h.pki.oids.sha512:case h.pki.oids.md5:break;default:throw new Error("Could not add PKCS#7 signer; unknown message digest algorithm: "+s)}var o=e.authenticatedAttributes||[];if(o.length>0){for(var c=!1,u=!1,l=0;l="8"&&(r="00"+r);var a=s.util.hexToBytes(r);e.putInt32(a.length),e.putBytes(a)}function n(e,t){e.putInt32(t.length),e.putString(t)}function i(){for(var e=s.md.sha1.create(),t=arguments.length,r=0;r0&&(this.state=g[this.state].block)},v.prototype.unblock=function(e){return e=void 0===e?1:e,this.blocks-=e,0===this.blocks&&this.state!==f&&(this.state=u,C(this,0)),this.blocks},v.prototype.sleep=function(e){e=void 0===e?0:e,this.state=g[this.state].sleep;var t=this;this.timeoutId=setTimeout(function(){t.timeoutId=null,t.state=u,C(t,0)},e)},v.prototype.wait=function(e){e.wait(this)},v.prototype.wakeup=function(){this.state===p&&(cancelTimeout(this.timeoutId),this.timeoutId=null,this.state=u,C(this,0))},v.prototype.cancel=function(){this.state=g[this.state].cancel,this.permitsNeeded=0,null!==this.timeoutId&&(cancelTimeout(this.timeoutId),this.timeoutId=null),this.subtasks=[]},v.prototype.fail=function(e){if(this.error=!0,E(this,!0),e)e.error=this.error,e.swapTime=this.swapTime,e.userData=this.userData,C(e,0);else{if(null!==this.parent){for(var t=this.parent;null!==t.parent;)t.error=this.error,t.swapTime=this.swapTime,t.userData=this.userData,t=t.parent;E(t,!0)}this.failureCallback&&this.failureCallback(this)}};var m=function(e){e.error=!1,e.state=g[e.state][y],setTimeout(function(){e.state===u&&(e.swapTime=+new Date,e.run(e),C(e,0))},0)},C=function(e,t){var r=t>30||+new Date-e.swapTime>20,a=function(t){if(t++,e.state===u)if(r&&(e.swapTime=+new Date),e.subtasks.length>0){var a=e.subtasks.shift();a.error=e.error,a.swapTime=e.swapTime,a.userData=e.userData,a.run(a),a.error||C(a,t)}else E(e),e.error||null!==e.parent&&(e.parent.error=e.error,e.parent.swapTime=e.swapTime,e.parent.userData=e.userData,C(e.parent,t))};r?setTimeout(a,0):a(t)},E=function(e,t){e.state=f,delete i[e.id],null===e.parent&&(e.type in o?0===o[e.type].length?a.log.error(n,"[%s][%s] task queue empty [%s]",e.id,e.name,e.type):o[e.type][0]!==e?a.log.error(n,"[%s][%s] task not first in queue [%s]",e.id,e.name,e.type):(o[e.type].shift(),0===o[e.type].length?delete o[e.type]:o[e.type][0].start()):a.log.error(n,"[%s][%s] task queue missing [%s]",e.id,e.name,e.type),t||(e.error&&e.failureCallback?e.failureCallback(e):!e.error&&e.successCallback&&e.successCallback(e)))};e.exports=a.task=a.task||{},a.task.start=function(e){var t=new v({run:e.run,name:e.name||"?"});t.type=e.type,t.successCallback=e.success||null,t.failureCallback=e.failure||null,t.type in o?o[e.type].push(t):(o[t.type]=[t],m(t))},a.task.cancel=function(e){e in o&&(o[e]=[o[e][0]])},a.task.createCondition=function(){var e={tasks:{}};return e.wait=function(t){t.id in e.tasks||(t.block(),e.tasks[t.id]=t)},e.notify=function(){var t=e.tasks;e.tasks={};for(var r in t)t[r].unblock()},e}}])}); +//# sourceMappingURL=forge.min.js.map \ No newline at end of file diff --git a/node_modules/node-forge/dist/forge.min.js.map b/node_modules/node-forge/dist/forge.min.js.map new file mode 100644 index 0000000..5350010 --- /dev/null +++ b/node_modules/node-forge/dist/forge.min.js.map @@ -0,0 +1 @@ +{"version":3,"file":"forge.min.js","sources":["webpack:///forge.min.js"],"mappings":"AAAA","sourceRoot":""} \ No newline at end of file diff --git a/node_modules/node-forge/dist/prime.worker.min.js b/node_modules/node-forge/dist/prime.worker.min.js new file mode 100644 index 0000000..7f91855 --- /dev/null +++ b/node_modules/node-forge/dist/prime.worker.min.js @@ -0,0 +1,2 @@ +!function(t){function i(o){if(r[o])return r[o].exports;var s=r[o]={i:o,l:!1,exports:{}};return t[o].call(s.exports,s,s.exports,i),s.l=!0,s.exports}var r={};i.m=t,i.c=r,i.d=function(t,r,o){i.o(t,r)||Object.defineProperty(t,r,{configurable:!1,enumerable:!0,get:o})},i.n=function(t){var r=t&&t.__esModule?function(){return t.default}:function(){return t};return i.d(r,"a",r),r},i.o=function(t,i){return Object.prototype.hasOwnProperty.call(t,i)},i.p="",i(i.s=1)}([function(t,i){t.exports={options:{usePureJavaScript:!1}}},function(t,i,r){r(2),t.exports=r(0)},function(t,i,r){function o(t){for(var i=new p(t.hex,16),r=0,o=t.workLoad,a=0;a=0);var f=o.modPow(s,t);if(0!==f.compareTo(p.ONE)&&0!==f.compareTo(i)){for(var d=r;--d;){if(f=f.modPowInt(2,t),0===f.compareTo(p.ONE))return!1;if(0===f.compareTo(i))break}if(0===d)return!1}}return!0}function e(){return{nextBytes:function(t){for(var i=0;i=0;){var e=i*this.data[t++]+r.data[o]+s;s=Math.floor(e/67108864),r.data[o++]=67108863&e}return s}function e(t,i,r,o,s,a){for(var e=32767&i,n=i>>15;--a>=0;){var h=32767&this.data[t],u=this.data[t++]>>15,f=n*h+u*e;h=e*h+((32767&f)<<15)+r.data[o]+(1073741823&s),s=(h>>>30)+(f>>>15)+n*u+(s>>>30),r.data[o++]=1073741823&h}return s}function n(t,i,r,o,s,a){for(var e=16383&i,n=i>>14;--a>=0;){var h=16383&this.data[t],u=this.data[t++]>>14,f=n*h+u*e;h=e*h+((16383&f)<<14)+r.data[o]+s,s=(h>>28)+(f>>14)+n*u,r.data[o++]=268435455&h}return s}function h(t){return ai.charAt(t)}function u(t,i){var r=ei[t.charCodeAt(i)];return null==r?-1:r}function f(t){for(var i=this.t-1;i>=0;--i)t.data[i]=this.data[i];t.t=this.t,t.s=this.s}function p(t){this.t=1,this.s=t<0?-1:0,t>0?this.data[0]=t:t<-1?this.data[0]=t+this.DV:this.t=0}function d(t){var i=s();return i.fromInt(t),i}function c(t,i){var r;if(16==i)r=4;else if(8==i)r=3;else if(256==i)r=8;else if(2==i)r=1;else if(32==i)r=5;else{if(4!=i)return void this.fromRadix(t,i);r=2}this.t=0,this.s=0;for(var s=t.length,a=!1,e=0;--s>=0;){var n=8==r?255&t[s]:u(t,s);n<0?"-"==t.charAt(s)&&(a=!0):(a=!1,0==e?this.data[this.t++]=n:e+r>this.DB?(this.data[this.t-1]|=(n&(1<>this.DB-e):this.data[this.t-1]|=n<=this.DB&&(e-=this.DB))}8==r&&0!=(128&t[0])&&(this.s=-1,e>0&&(this.data[this.t-1]|=(1<0&&this.data[this.t-1]==t;)--this.t}function l(t){if(this.s<0)return"-"+this.negate().toString(t);var i;if(16==t)i=4;else if(8==t)i=3;else if(2==t)i=1;else if(32==t)i=5;else{if(4!=t)return this.toRadix(t);i=2}var r,o=(1<0)for(n>n)>0&&(s=!0,a=h(r));e>=0;)n>(n+=this.DB-i)):(r=this.data[e]>>(n-=i)&o,n<=0&&(n+=this.DB,--e)),r>0&&(s=!0),s&&(a+=h(r));return s?a:"0"}function v(){var t=s();return o.ZERO.subTo(this,t),t}function T(){return this.s<0?this.negate():this}function y(t){var i=this.s-t.s;if(0!=i)return i;var r=this.t;if(0!=(i=r-t.t))return this.s<0?-i:i;for(;--r>=0;)if(0!=(i=this.data[r]-t.data[r]))return i;return 0}function b(t){var i,r=1;return 0!=(i=t>>>16)&&(t=i,r+=16),0!=(i=t>>8)&&(t=i,r+=8),0!=(i=t>>4)&&(t=i,r+=4),0!=(i=t>>2)&&(t=i,r+=2),0!=(i=t>>1)&&(t=i,r+=1),r}function D(){return this.t<=0?0:this.DB*(this.t-1)+b(this.data[this.t-1]^this.s&this.DM)}function g(t,i){var r;for(r=this.t-1;r>=0;--r)i.data[r+t]=this.data[r];for(r=t-1;r>=0;--r)i.data[r]=0;i.t=this.t+t,i.s=this.s}function B(t,i){for(var r=t;r=0;--r)i.data[r+e+1]=this.data[r]>>s|n,n=(this.data[r]&a)<=0;--r)i.data[r]=0;i.data[e]=n,i.t=this.t+e+1,i.s=this.s,i.clamp()}function w(t,i){i.s=this.s;var r=Math.floor(t/this.DB);if(r>=this.t)return void(i.t=0);var o=t%this.DB,s=this.DB-o,a=(1<>o;for(var e=r+1;e>o;o>0&&(i.data[this.t-r-1]|=(this.s&a)<>=this.DB;if(t.t>=this.DB;o+=this.s}else{for(o+=this.s;r>=this.DB;o-=t.s}i.s=o<0?-1:0,o<-1?i.data[r++]=this.DV+o:o>0&&(i.data[r++]=o),i.t=r,i.clamp()}function E(t,i){var r=this.abs(),s=t.abs(),a=r.t;for(i.t=a+s.t;--a>=0;)i.data[a]=0;for(a=0;a=0;)t.data[r]=0;for(r=0;r=i.DV&&(t.data[r+i.t]-=i.DV,t.data[r+i.t+1]=1)}t.t>0&&(t.data[t.t-1]+=i.am(r,i.data[r],t,2*r,0,1)),t.s=0,t.clamp()}function R(t,i,r){var a=t.abs();if(!(a.t<=0)){var e=this.abs();if(e.t0?(a.lShiftTo(f,n),e.lShiftTo(f,r)):(a.copyTo(n),e.copyTo(r));var p=n.t,d=n.data[p-1];if(0!=d){var c=d*(1<1?n.data[p-2]>>this.F2:0),m=this.FV/c,l=(1<=0&&(r.data[r.t++]=1,r.subTo(D,r)),o.ONE.dlShiftTo(p,D),D.subTo(n,n);n.t=0;){var g=r.data[--T]==d?this.DM:Math.floor(r.data[T]*m+(r.data[T-1]+v)*l);if((r.data[T]+=n.am(0,g,r,y,0,p))0&&r.rShiftTo(f,r),h<0&&o.ZERO.subTo(r,r)}}}function x(t){var i=s();return this.abs().divRemTo(t,null,i),this.s<0&&i.compareTo(o.ZERO)>0&&t.subTo(i,i),i}function N(t){this.m=t}function A(t){return t.s<0||t.compareTo(this.m)>=0?t.mod(this.m):t}function L(t){return t}function V(t){t.divRemTo(this.m,null,t)}function q(t,i,r){t.multiplyTo(i,r),this.reduce(r)}function I(t,i){t.squareTo(i),this.reduce(i)}function P(){if(this.t<1)return 0;var t=this.data[0];if(0==(1&t))return 0;var i=3&t;return i=i*(2-(15&t)*i)&15,i=i*(2-(255&t)*i)&255,i=i*(2-((65535&t)*i&65535))&65535,i=i*(2-t*i%this.DV)%this.DV,i>0?this.DV-i:-i}function Z(t){this.m=t,this.mp=t.invDigit(),this.mpl=32767&this.mp,this.mph=this.mp>>15,this.um=(1<0&&this.m.subTo(i,i),i}function j(t){var i=s();return t.copyTo(i),this.reduce(i),i}function k(t){for(;t.t<=this.mt2;)t.data[t.t++]=0;for(var i=0;i>15)*this.mpl&this.um)<<15)&t.DM;for(r=i+this.m.t,t.data[r]+=this.m.am(0,o,t,i,0,this.m.t);t.data[r]>=t.DV;)t.data[r]-=t.DV,t.data[++r]++}t.clamp(),t.drShiftTo(this.m.t,t),t.compareTo(this.m)>=0&&t.subTo(this.m,t)}function C(t,i){t.squareTo(i),this.reduce(i)}function z(t,i,r){t.multiplyTo(i,r),this.reduce(r)}function U(){return 0==(this.t>0?1&this.data[0]:this.s)}function _(t,i){if(t>4294967295||t<1)return o.ONE;var r=s(),a=s(),e=i.convert(this),n=b(t)-1;for(e.copyTo(r);--n>=0;)if(i.sqrTo(r,a),(t&1<0)i.mulTo(a,e,r);else{var h=r;r=a,a=h}return i.revert(r)}function J(t,i){var r;return r=t<256||i.isEven()?new N(i):new Z(i),this.exp(t,r)}function G(){var t=s();return this.copyTo(t),t}function H(){if(this.s<0){if(1==this.t)return this.data[0]-this.DV;if(0==this.t)return-1}else{if(1==this.t)return this.data[0];if(0==this.t)return 0}return(this.data[1]&(1<<32-this.DB)-1)<>24}function Q(){return 0==this.t?this.s:this.data[0]<<16>>16}function W(t){return Math.floor(Math.LN2*this.DB/Math.log(t))}function X(){return this.s<0?-1:this.t<=0||1==this.t&&this.data[0]<=0?0:1}function Y(t){if(null==t&&(t=10),0==this.signum()||t<2||t>36)return"0";var i=this.chunkSize(t),r=Math.pow(t,i),o=d(r),a=s(),e=s(),n="";for(this.divRemTo(o,a,e);a.signum()>0;)n=(r+e.intValue()).toString(t).substr(1)+n,a.divRemTo(o,a,e);return e.intValue().toString(t)+n}function $(t,i){this.fromInt(0),null==i&&(i=10);for(var r=this.chunkSize(i),s=Math.pow(i,r),a=!1,e=0,n=0,h=0;h=r&&(this.dMultiply(s),this.dAddOffset(n,0),e=0,n=0))}e>0&&(this.dMultiply(Math.pow(i,e)),this.dAddOffset(n,0)),a&&o.ZERO.subTo(this,this)}function tt(t,i,r){if("number"==typeof i)if(t<2)this.fromInt(1);else for(this.fromNumber(t,r),this.testBit(t-1)||this.bitwiseTo(o.ONE.shiftLeft(t-1),ht,this),this.isEven()&&this.dAddOffset(1,0);!this.isProbablePrime(i);)this.dAddOffset(2,0),this.bitLength()>t&&this.subTo(o.ONE.shiftLeft(t-1),this);else{var s=new Array,a=7&t;s.length=1+(t>>3),i.nextBytes(s),a>0?s[0]&=(1<0)for(o>o)!=(this.s&this.DM)>>o&&(i[s++]=r|this.s<=0;)o<8?(r=(this.data[t]&(1<>(o+=this.DB-8)):(r=this.data[t]>>(o-=8)&255,o<=0&&(o+=this.DB,--t)),0!=(128&r)&&(r|=-256),0==s&&(128&this.s)!=(128&r)&&++s,(s>0||r!=this.s)&&(i[s++]=r);return i}function rt(t){return 0==this.compareTo(t)}function ot(t){return this.compareTo(t)<0?this:t}function st(t){return this.compareTo(t)>0?this:t}function at(t,i,r){var o,s,a=Math.min(t.t,this.t);for(o=0;o>=16,i+=16),0==(255&t)&&(t>>=8,i+=8),0==(15&t)&&(t>>=4,i+=4),0==(3&t)&&(t>>=2,i+=2),0==(1&t)&&++i,i}function yt(){for(var t=0;t=this.t?0!=this.s:0!=(this.data[i]&1<>=this.DB;if(t.t>=this.DB;o+=this.s}else{for(o+=this.s;r>=this.DB;o+=t.s}i.s=o<0?-1:0,o>0?i.data[r++]=o:o<-1&&(i.data[r++]=this.DV+o),i.t=r,i.clamp()}function Ot(t){var i=s();return this.addTo(t,i),i}function Rt(t){var i=s();return this.subTo(t,i),i}function xt(t){var i=s();return this.multiplyTo(t,i),i}function Nt(t){var i=s();return this.divRemTo(t,i,null),i}function At(t){var i=s();return this.divRemTo(t,null,i),i}function Lt(t){var i=s(),r=s();return this.divRemTo(t,i,r),new Array(i,r)}function Vt(t){this.data[this.t]=this.am(0,t-1,this,0,0,this.t),++this.t,this.clamp()}function qt(t,i){if(0!=t){for(;this.t<=i;)this.data[this.t++]=0;for(this.data[i]+=t;this.data[i]>=this.DV;)this.data[i]-=this.DV,++i>=this.t&&(this.data[this.t++]=0),++this.data[i]}}function It(){}function Pt(t){return t}function Zt(t,i,r){t.multiplyTo(i,r)}function Ft(t,i){t.squareTo(i)}function jt(t){return this.exp(t,new It)}function kt(t,i,r){var o=Math.min(this.t+t.t,i);for(r.s=0,r.t=o;o>0;)r.data[--o]=0;var s;for(s=r.t-this.t;o=0;)r.data[o]=0;for(o=Math.max(i-this.t,0);o2*this.m.t)return t.mod(this.m);if(t.compareTo(this.m)<0)return t;var i=s();return t.copyTo(i),this.reduce(i),i}function _t(t){return t}function Jt(t){for(t.drShiftTo(this.m.t-1,this.r2),t.t>this.m.t+1&&(t.t=this.m.t+1,t.clamp()),this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3),this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);t.compareTo(this.r2)<0;)t.dAddOffset(1,this.m.t+1);for(t.subTo(this.r2,t);t.compareTo(this.m)>=0;)t.subTo(this.m,t)}function Gt(t,i){t.squareTo(i),this.reduce(i)}function Ht(t,i,r){t.multiplyTo(i,r),this.reduce(r)}function Kt(t,i){var r,o,a=t.bitLength(),e=d(1);if(a<=0)return e;r=a<18?1:a<48?3:a<144?4:a<768?5:6,o=a<8?new N(i):i.isEven()?new zt(i):new Z(i);var n=new Array,h=3,u=r-1,f=(1<1){var p=s();for(o.sqrTo(n[1],p);h<=f;)n[h]=s(),o.mulTo(p,n[h-2],n[h]),h+=2}var c,m,l=t.t-1,v=!0,T=s();for(a=b(t.data[l])-1;l>=0;){for(a>=u?c=t.data[l]>>a-u&f:(c=(t.data[l]&(1<0&&(c|=t.data[l-1]>>this.DB+a-u)),h=r;0==(1&c);)c>>=1,--h;if((a-=h)<0&&(a+=this.DB,--l),v)n[c].copyTo(e),v=!1;else{for(;h>1;)o.sqrTo(e,T),o.sqrTo(T,e),h-=2;h>0?o.sqrTo(e,T):(m=e,e=T,T=m),o.mulTo(T,n[c],e)}for(;l>=0&&0==(t.data[l]&1<0&&(i.rShiftTo(a,i),r.rShiftTo(a,r));i.signum()>0;)(s=i.getLowestSetBit())>0&&i.rShiftTo(s,i),(s=r.getLowestSetBit())>0&&r.rShiftTo(s,r),i.compareTo(r)>=0?(i.subTo(r,i),i.rShiftTo(1,i)):(r.subTo(i,r),r.rShiftTo(1,r));return a>0&&r.lShiftTo(a,r),r}function Wt(t){if(t<=0)return 0;var i=this.DV%t,r=this.s<0?t-1:0;if(this.t>0)if(0==i)r=this.data[0]%t;else for(var o=this.t-1;o>=0;--o)r=(i*r+this.data[o])%t;return r}function Xt(t){var i=t.isEven();if(this.isEven()&&i||0==t.signum())return o.ZERO;for(var r=t.clone(),s=this.clone(),a=d(1),e=d(0),n=d(0),h=d(1);0!=r.signum();){for(;r.isEven();)r.rShiftTo(1,r),i?(a.isEven()&&e.isEven()||(a.addTo(this,a),e.subTo(t,e)),a.rShiftTo(1,a)):e.isEven()||e.subTo(t,e),e.rShiftTo(1,e);for(;s.isEven();)s.rShiftTo(1,s),i?(n.isEven()&&h.isEven()||(n.addTo(this,n),h.subTo(t,h)),n.rShiftTo(1,n)):h.isEven()||h.subTo(t,h),h.rShiftTo(1,h);r.compareTo(s)>=0?(r.subTo(s,r),i&&a.subTo(n,a),e.subTo(h,e)):(s.subTo(r,s),i&&n.subTo(a,n),h.subTo(e,h))}return 0!=s.compareTo(o.ONE)?o.ZERO:h.compareTo(t)>=0?h.subtract(t):h.signum()<0?(h.addTo(t,h),h.signum()<0?h.add(t):h):h}function Yt(t){var i,r=this.abs();if(1==r.t&&r.data[0]<=ni[ni.length-1]){for(i=0;i=0);var h=s.modPow(a,this);if(0!=h.compareTo(o.ONE)&&0!=h.compareTo(i)){for(var u=1;u++n8uFT685yDP~}E^(ZSfF+G3387pF)roE5ki@}G z0q%8?WGOPSB_qix+{?Wo5JCwh^iJp{bV6?-^e)RJruW`^2fyE$UCFW&xc~3H_kEu) zXLshz%$YN1&N*{tW|g~45$`BU;nj*#!IY}vVTz*sr}P=7DEr1+!&B?4YJAH&+M|i7 z$n7^al1z3^oiu6b(xnrZ?lv(NUo>ggz4zXG(&QU_9hc#s=2N;HbRaA6?YtUliKEdX6m1<|U8*WN81YP|!DJH_JC= z@~(T@Y!G(eNrR;AU@(FED^=c))P0rdysxkCaF2=^)&WAl>~KZ?ja)c;{9%~!XFLs% zXDB&07Hd}?DznZ~6kwHb+}{z}Rq-kll{{rXPhTHnTooE7_R$<89GJqN^>MG^T-W$REwKdy(Y@n65>ki3toJgVZYHasTo>n@m@- ztv%tMwmcb<*nHwD)M~f&*2>mZZHZ2QG6>l^T_=_&lA(^`oLR1lb@kTkj;Nbwyj-L;9SqjzB1`f@5tus3yGG3bXxDa2fZYc?XoC zJ(S3+oh=i!(QwRF(-jR;pKg@fLddgAC9|HISg`m9Elbw6dOHTqO3|Ra+8$dZ+M;bqBS?zS)tLw4t&V(jX$B#1 zkVwX3%Z*?x8U=4!usxOt<+UZI+xbwdNQ9!TMm!V@wJix1FA60|M-r7w{B7;Tu{+Tf zAS(zEDTn|h+oJY65lYrVKa558+Y=9U#Fm6)k{F6pDlwvYdaR?f4Z1c^FQk|;TT(9z zruh@0J$HvK#vs)440`GSwB9P;T5B9Sr-j?Q5)lpa8A|3QV_Ch{g0Ze>QoxA)dbq6} z-HN5L_~N4YK%H~jlNk-cq@>(=TdTuFb#$9dIOxK*Xd)C(&Iv7@)fNpU^pHds+OPTZ zYNYV;?5s??k}=z8Gst%I=V}ggg~OqELT{G*YR&DSrZp3*dO|W}bU;Zn}fnmX8a z^4g`MPLDt&CGAkjY`N6svaaaX$YOu%pt&fsXKo;J^tOz zk(?V3VOa4{>#Tmh2yeHZ1JBn_fpl$9mtmO6K-9vvWF&)eqk-)jDP>EwFq@LoPX)Ha z(Mc;|+<480?;$=Nhv`C6dZN*o%cQ@(ecK9}7(%Ai=5KF1DwH#tk=vdRyNxH19VZ!F zlI+l)p~8U`M+~4cux!FM*UKrBC+{iO%1Ir|CSgFKc+}sX*WBNstJ&$%XtukgAy2na zp60CR%0toS`3({3;Ohjb@YfT%xc&ig5k^8ipj{bA1GUjmxD$_OnX?x&t-Hwh5qFo*JG|O1} zLW$B&KN86SL0PeXaBQjDHb_p4M5x>Lr8i3(ef zCqS&vi@_L+`lX5pb=mSA|62004x&ELh-b#rsx?!y*MwQ)YYeQ7qJ>Br^U zw$}hd4aJ8Ia8$V^BXcvv(XL=A6Cw-RQ|b0bNsosXVI~U^zapp%wKh{(!nMR7Z}Y<% zJrbWljf4wP?-FQUBHu~OqMG?Ze>4__K9DohA!HaFV%3H=m`HR{UAQ)LvgG6c>!w$!!+I9r67*hwTtNo*}5Pi(tFgG&oK;ZdZqP_77yKQ{-FmqW31 z8*~aFoA%nM3>20nDJCO#ARhGx4+-xt>k1oy~n=}S(iNC!oR5n0+9iO?~pLsK< zyeK0OXWLZKyp>y+=f}o2IrLBPMssW1BJiNwFL!eU(fz#Togr5y;cg~1S`-bnx-yAE zXYMll!vVR%=FS*;T3&-?a(?}+f&n?BIi6_8Ten{Y%}YY@w(#;Q*?E3$MtT!kX`MxG zL~xrcuMCX6)eX}t=TU_0~QU98X(LOqI4_)@8mb)JY~C4K8=dAcEYe46*IBD@c_PofKsBMYd8atEyCJ zWHH{&HFeYHH#E<#oKtyFbv@~++`>DmP*yp2?yTDBmGi(T*q%LiR`tB<(wzC8?)c@r zY4hjJL!GL+g>w*ZCzHhb(x`V@<@AG_53W9}d2W4mLql~{A&v0h(DJ$D+(WG%$Yahy z)y>s&s@(P_ygJ&N?;soIRo2hTv(XJne>~}u1+{Yya!DkdPx18n>VeF8}1JMtzI@Afxrw?jTFnxY~LtTCI{JB+?^Q!YO*Vi*;sdISzA&f%W7s- zAKJXIb`HeaTseJS?E(~+5YdH*>0(PO5jT*VF3+u3Rh_9>)?c$KR-~fhz=K}%x2l$ln<`mfc%_;$_7?$KrXsy$eikh=&*KHRdbHMmu@5Q zE&$K{qb48UKk!175lfids=7JV*##h8g%EdGZsBxWJDQ=8Rfm=5)C)=tsh9DoEY#~^ z88FMN9@Ue%$AO+*x1d_LBPitNLbZ|Wgd%(FoHQvLLnh@QZIiOm(xki%)w8On+h!pp zUX(x}EW=S->Y`yr-9nLw#Fh@R<>(k^))^#7j&|LQ&QuJjSxfp}KYuP}wLGV?+@8d{ zIx)ZAdG(cZ8fxn5XJ?qmMih2kyF#sGQx3td&_-;^VHD<6z`zUoi!t~j+mN#?7uts; zS=WWd!s)llgCN%KvQ?8>tVtctM|!>_FuQhMo?KGVx}z;wo{V+Q!iw8IU{jJP55!_g zgf;%o{sT$$Qbb~$9qUSjrc0kPCga9tk#CNoVQsW7iOugoYCE+$yJFOoN-!_BjanWA z@=zWKHIYx-xy%MkAg=5vriVO>sdjE1^4k&%BW(!vI{m?rhmI4IZAloLD^5p~*pL*U zED2e};W)6j2D_OfrD@COW`kU>Bphv>LpKs+1x3+J%C0>OE6V)#WLpO$UW1^9{J&jN zZfnWh`r6r*^@laj!UW968ssQX^`Y}f^{cY@hJ444r`Olco#$lgs}I7I7uuNxmG!li zbLKU8b12XX+fbP8iM(P%A=WRLQAQG;a6HywN8g4`99_wG^R&a7Ypb@es;;S=KWm=T z86ktER%+3~9I|*s{*r|rx z{>*W%cYj5`jLcaX2Xg{$$=;(AuH%Bd%>*Yk}&L&H1qTKNcipzDm(b&(B zui7eRi6{(@g>+gA#*Nq8L(xUa$o9^GVgF%aWy5avfnlJl4HgkC8*q0q)xL5t2O_KN zw|z=T+W|y_*vJm7B;_R6_mEw2#9t5@nR|gXbNryk4h+vG>%Yq?!#g@pkN9Ak9 zDkc!uCyba~;CAje#*Ht`rerNQ?ZG5rLAw``M5M1L<(8lz-sN=T(x!0(gaE}cVGQwg$>n+<7(#}X4f$6 zsr0#gcBiccna(B8F6TyO92@WPIq6WV?i4!LG~@D@b+p@bFtKcEMHih7f?zC>*rioQ z>OL$WQ+=)sJB75e&&}>q^n`RXZfq|?VN7JJ)M_U%g0?Q-idGRA2-(Vys1SQ8c~dmb z9n4%5<>y=)jnnAXXq;y$DUv*f$=p_wR1$_GI!zvPh&a|UmQVwG?#==(=cZ{~VPN1r z6KTDDW6~M37u1riE~CbkNM-V6<~Gzi)#sKdx!DUkmgULbS&b9E{r2}2RK^!|k?-n0K+QY z$_&f5ZM~X2?APS6j|U+@e0r=kRGD;Vr;X0!D5#XTQdQ`v6Z1@~)O4q^MmsR@(3OZ3 z$X1yprC z+&?EDO^$VUpHzV`)hflan?KtF1L9~*pEZUnjlP)*2}_Q6t3^Cb5&AZw*fom|)`WWr9RHMFcQEH721 zfig2M=N5)d9N({;beQhToEK~*yRn61A=tRjKHc|?rIO1=$N;8&{>uS4QWdj zIQ-b#eUBZWVmVx7&W{rBWC`RZ`a87GMSP?czM=7L-=XBuYBw+5wg@8Al5`!f&8wYV zU7s)0ncES26EVQ;3g~-hVPe4d1e(0hhb2HabUR#D=lJL3C1bN+YG zy1&yOXv3f&I(O#Nj)W_d(hwF0Lp#oi`Q+h*FLN>hX_DmHvTOd>A<&CMx?uHW{1#RU<$m6$JnS*OG zuj*wOIqBlahJ`iR*h5Z$oDAo5kxaKTsU_guL*j^7Ta@{jn-wq*%hwUFRWIx0|M(~W z$I)z&fgM*nMLaN1=c1O*$J>)07_t*p7bkKqVC2z!dDk}MW*v)UWqUhoV@I&XtlemL z+IMDKIus44a7Qc|GCJ)lY!}wdmhrY-n4cZRCbPW@!A{-M=v-UVmkWyVb<#(S2Ra)S zp=6{DYra1q0*GluaCy94BqM&mNVWx%0-@$&v8d~axQK)TanTxD;z#9A)k}>KBXQKtVJX6CLf#J4DBF6d;iFgFw7XU>%K!q`w2?L+xGEN1KQ)MrE36 zfnAb(Bt=IIY$TS)gFLW^2mL&h;73Jxaw!i+c`(6)NAXraZ(Yn=Lp;>Z7sYuf%DWOg z+{VLk9trWbb{^^CZ3*6%10fz*&J(E6#zRRS3i0+OygkXoe%==6OWOF7 zD32`X{toUxiif&*$71de^P~KHv7avr@oepHtlO~lkh#}NQOAOVQ-K!OMS+#lfnIQJ*Ge>o38t`Xh} z#$!Bugc^>=c^GuT47y&zBT3!{CfoVq4&LtP?E&5%ct<<$i1DbOM_YL` z#G{b&avtm8F-R}LkL=>{D334Y35>LZCt^I2;E5zpw((>;PlDA1UlQU=V|;m=8te?I zt%(2_NT`bvOVtR{@JcG;2Q}K7P@`=a(UBNYEULna)a2rJHQ5nSlbvm9a!I>-Q~)!- zm`A{PWKlUQ7v=fo-tyA&VdW#seVU>v<>SgHR7}>CirVs-6|<0ESW#H$OYH-b9y1@*CxeVquSe~I47_89XMTRIg zM2Vr58ElBb$_+Nu&?*dlxWPsk#wdf2Hu!diYkPz5VDKFc!!+DG8J;nQI@ZV=Z{+W6 zxU5k=w!Oh78+p4Lg;R{e-HgKB4Zep_xTjJ0H=}Sbqi}DdaH>(bk5RaHb`V6zQ2$6$2^n`^K`jFNhzq`@ee zXOzr0N){NUhZ^iK!+W^F{$a32gEbkf*6-$hYrAEavqhh&Hagl88=28j|l>L{+~@!yB|2Xit0|Z_uCk z0^aCjVhV5c!@7}9F7`PQ#(6R~ z^flZ#;54L9$9pZ_XW)G%-e=)`Hs0speJ z%aOhUa24QcZj=L8ehn1%S^yMu#P!@5xt<#b-T=4}b#8*j;azz%(zgI^1>6p}18^7M z9>9Ho2LKNN9tJ!Dcnt6a;3>c}fad@&0J;G^fX#qjz{`MF0j~qz1iTG+7w|sdL%_#? zPXV6;z65*?_!jUT;0M4@fL{Q=0sa82P+@3*;{eA4P5_()SOYi}a5~@&z*&H^0p|eD z1)K+f+}Zi6G3^4RF9ci!xEOE=;AfJfYD`~;^ku41bvfV)z?H~f1-Ke;4d7b9b%5&u z>s4cq8}PnSHL7m{+zhw{a4X<8;BNBeT`v4CB9#Re0M%AdMtSpifYVw6~6rqq~8R*MWX|}19%VcKHvkuhp6)r z-XG)r3ErQohWHWhp8&rA_JvUK+7C`l7;}#m#*D*^8OPzZ3UEANHQ)qvdJ^Ddz#8Q1 zjTxs2_hG{QmMYvQ3E^G@?e7CV5F<*EW9|o;3ddXO-l-J6wiLdu)TsR! zOnf3nlo_?3qUzVkeJ|YaBNABngBUTySokBD{|WFj;1|HJfZqVW1O5Q?0pKqduF#By z#{gCWj@3q#yI&IJM(rBS-L00pPtlM*MKfwo)kX|O$x!!)7}S^w_YbVXeHN0V3f+HT zP}>){%|iDYuDY#)JGuR%0fjS0Nv7!ZD*?vncLjnHcxX%rO%sZX<>yNT)A8WC5DMoU z0U9DLS=S&sgk_xacyN^qAUxPAqUN9kRiL+$`Exli=uh^kxE)~5`_KMRS7qQ=adD>N ze@r6WSp-#(L^5yZ4+S23jJfQ3(4zXSt#6j=lt)vD19Fb=O3TWe*-}bL6hm?!PP0K$?dMz+LLiwzl%qEn*PU9q zl!j)f!t>`-VGFvD=qdkwUjAR05$ZdqL&lVhL1k@C6a!T(wjpTnqhlc4gFi+66BVZ! zlIBXk{Hbu>82~}S@(bJ*ic91>f07qz*A;_ItCX0i;DcsZageguo>WTY|4EnLKk1gU z{EWrsfXzfUqtatoHZ`0cBeK~+B4EnM|H1fW4}T$qAvpx4amopkUXAhsd2a^Gbxmx; z9SN7q1r75+TcEQpSB8>Qt^SFY1*1fkdz(Fdl=F}bD_I8mc^U9G$f^xe5%}X$#if&) zkW-W6E0y|_{nMR#ic9OSHbAGOjp@0G(Zuw2J2*4W$U~HImu+I?Fl>G0Qiu6qUxV&A zoFsKNsH1`0<4=dIT}EbRsKqX}ieK7lFf&LC$oMFUwK)s0C^aZP55dsn7-rZ6RMH>Tw8&Xj^Zm{PPSQ@np;O7UJy zDcKwDYbsO9_F>A9eYv|x8LsTd-Nni%&;CpqeE?IoJCG^9N~UZ-jVU`!hwd}AiWa15 znXIANI*5FoXNJ2>*@@K>=QFu`h%&C=V2mIy4>ZQlV#~`2Q7pltym0o=L%Fi&p{nw?!7@s8nj1vba*2$&_}c9NfW_S%t)r8s*B|7*`JI|(QyLMJF*j5=a`ci>BGs4baoA+j!%)# zQwi_!oW@9Qr^8Dec{-d(d@Wih&cGviCLUd9;j!dwJeHn=$3M@-<6r0DarF6k{QCkt z{&OK7E7(PN9>Xrib0xb3&tuu8jJR8e=PGs?p2xGxS*1eUU4i!rcwdS4iFjXy_epqP zjrYlTUxW7=ysyRk6uhs)`&7KI2b{*%<9Rx}0nfGUMm*18H{p3E_Ws&vh9_N*=@j&Q`XUP3thOG<=>9MUcqk1Xs^Uho}>Fa@Vpv3d5*5{!t+|};yJp# z2hZ!VgJ;Tm?A@7i19t9AxeVu>lpjXv-E0${_pp)U z+`B0EvF#s0$)ikp46nzT@&uDc@FXMKeF~l2&z`oY;~8WgV9(;*fM zLS`fDwlisD9!4n5l}+qLMyj+K=||WWbp0snWz^qGcs|ZvX4L5`cs|Kq#q%ll8lF$H z*YSLYy@BVm>`gqMV{hU4JocPSd4c_hDJk|2lHKeWJk#u5JbT!q822P}r9SKMPYd3A z_K@C(C?>NH(7E?RU`8q**{psnb?y_e_Y(UAl7E@eNMDg7eU;G=Ut=`3*BK4!4Mqcb zQ!@FM9M0Qv2=7Sd-({cT`5yZWd`wZkV9Mu6?56y{lu_KhyYdSw_=1GN*q8R}EBp1e z)bwxU^IOTzcQXCG&EXHA`748S`HlUE$8oYaO*w(HU%}sM zK4h4CFXdz|ev`ugU0UZKC|Scv^-ke^Y?ynhaysXB1wyXn6`*h#FId63au#2~Rpo4c z4ASS|sVe94l}Mk*kL64`pC5$(p=K*sYKVPOVK>Bump=@;#(i@N($}i?6YQ-hIL<}3r zFXcKb;_5oCbC+T&W3|hG5La?`Iajz>Rj=SW;zadI?2}OKD#Q^kWs0(gQm4!pS5wvN zIJ*W_1r0^bSFYp5>VhUEkS)9(g(tv7QCfnL6|2ETN}Cc@Gvzm;+%AZn&9n^mCSYlh z#p*fiI>eagGStw{V;8dBGF5H?%i=c9ZUu*81829_5+0$GfDL&xr8Lp2KA9409*GG#_ zID3xk+lkLOd!Fk)@daluaD9966=x}~?;yV6tefjQin|y~bKMl*bJoN4oy3ovy~y=3 z;%Ck_bA7D%m9s5eA18k2te5NKMIUD`aeaa~MrAK^eP?m3%3k5RC042IRj%(MR;%na zu1^#vs_b>HPZB4q>?AhP<1D+X6CXE1}Tj%;GZ>TT>{%=7K+W6bjgczfkuroe4( zVaf;0m8tj%6yihnDRzDzvCmNPWA-^O)<0oi@M7ar_9ZWNea61x#qQ7HRyqfwWG|8*0KS7bahWaz~$m>#nff{+;>aWlu zuSfk2w0>g0gVxV%1$X^{_AaFl&AGBd)m5$>gS`}2R;s!Nccd1p$MEB@r&`HZsm0o{ za1+W&T+c9eyb2B8z}RZE6nCpMlY(aQ1eG+Hu@hBjFxIrwcvey;QIq>sYN|R-1vQ0Z zxPtRct&^$NgDMP@tx>T%%g?`_vrOTLa<-#j$_TbE-0qHSKcVn3%p(+aS2h#T@9xYH ziZ+Lp2t}XA3WZ`cvLg}Z`q@7PbBEZ`Lh*#zDVSSjgzGG(o`8Ks!M}x)cN`M=h&gV? zyAVOfEqE6pw73m#?=6frVa4w=?LlNq9>Sw^B%<<1kr?tm9_3#$EEz%>x{9lx<6VL6 z#;{+I7!F5zEZ!qdoL`OTwP~9p{|>GI`$SQwEmU~ zPpDg~a!T)&3h$grPfdk)$)xv5g(qgx`=-K^GU@$N;mMiw{;BY;ne+jv@RUsYz*Km* zOu8}^-aV6^mJ08YNl#CO_spcLQsKX4($%T(UYT@FD!g|leNZYqHItr^3h$FiKc&{4 zp)&8jijtb#J^65D!j=h>ckW<~}Z5N~JUGcow*)O9j_R!(}sy1Ma{ zWDjCveuLVduAZ&Z>6qJN3s_Z!2Qy6q-ZDAFx;t3PN~zQw{{yLWR8zURq)1UHXDZ=y z)fHG;6vej!D{Kc(HS(EUiR_dzS!7JAaoo&tN@Ogma^L!MCX`_7J>GgrrTm5oB_8A` z89q-Pb3=)#&}5GBpRam{(E!slz+Pv7#5;Hxt8DvG0!hh$x&UX(jp@` zb9+XoCa0{|s8-6C;lvjio3dV)EwP2sRJUgj$gt%i_4bkiMWMv%@WtvXFVBCS8%l;ioM?T-x$1bQ_18{o zS@j#4!N^>y;r2X>k@;45f_lpOmP(;QY5DAt&w#LB+Q2T3vb!K{K+}LQm0{QbTi>Z@ z`@L+nDyXHbA5=6%qn7KCsJkAzyoaI$G~W#w-S}B;S+Cx3PRUTv+eU4J(7)1<1A4lr z?go{63kW3#^_w%OZwCy@tzxe0<(RgltltOAW<(C-Thieh)e=on(sehf$~GwfK7g`E z6>iTQNx63{X!i}KU6w<;w+FPBY}p3UzJ8)<%wwLWd5TVx4z3sW2jU%qUi)=u^m2FT z(kMeL-N8d_YzGu#g&=C0oga~H~OD#azYs}z@PpmTEN4pq_iQ|?q1 z-L2%45VveCM7J%(nFEFBTSZbl(dm_ZCgie}ID57w&UP*bc9&Y1PsL6qNmLu%Gu?{a zqm-y7CCcmWmf}Rte-9FkGiT0JY=+wPvHpYUm94Ci_~)pSu3l58tor{#`di7to(5|b z;nn$U2K#3ZHk~Mv}L)axWs4%UK?7%|u@ZJkirSW0aI!jn*%Q|e`%!d)icvsr1ZBWQ%Bp`+<#uf7Wq#kUPHtD7Hv7Q#9=`<&{zrmcq(WIr1>Fuf8q$)kq037v)E<^VN z0>~a)=Tp|X!q&QgfaXK(6s6ceX!1oiH1ScqVY^1vHf~`Xx8{T`RnmMx!Z)AUbu-?N zR9>om#`~$Z_Y=}O9#N&046;z^F>MRg>|$wEj)h7`pn+5WqpEkmKZ{?eo^_ZLs#(vg zPM~HjvaNN#>VHg?G0yqIsXc@3eHpt-20Gf~Qp&f>K<5cqoAh?Vtvm^9o2ir-x~J%A zDV?Bj#3Kdrl zYCplyj>aoTs>+cHjI@kq`5gWyBONQ(w^aj| zx9n8^?+iLnjEE; zU4&kcW~Pq$zbL;wUtm2_WAs0lU`nO)i*Bq<*sYRBIdyA~0@0|B2(!}T8R@Z%^rY1| z!{B57Zy3I9@ndGpqA{q?(HJE6Tyn31`*M!G@R-!(kkY~@w~U+Il2#|T^Z;H2nE3Bd zWt9Aj?1)urC}XOy_jMJNbfqR+*NO$?OowIi*V*~uj0sIo(ViN$N1z+EDANr;l#Pn) z3-riiI9iImw)C?rKgkcl+NT&;MVrUYWDfJs0bkUK`^n7_k_2o=7FUX z{;Gvj&2Ag(!yRqV5aB3!*O z2nQ3;{MF=8s2ZmhePu*+B@wO4v^B+5nQ}>n|0Nl{eUR>ULKWKnsmabBU^A$N??F_Hw~Q*fWrDEw{tBryp=BXSqnft#KEZ`H36b-v z%_J(Na3t|{5G>ZZ0W42nz-mJ3s?Ck3tKIUrD^+uVf@a%uD8UdYfiv5-bcrZ9+kt^5 z3_DeGpk%DBQlYMPBzyOQ;g?j~;Q6S?eg{!d$u!+|AUiRp8(9Z21`V_dG2h??zw@bM?QXLLv2V{o0@r&;y3Q-etISl%p2fte;R!2P?EF zUuLrPC1apMb#tY~Q4I`}2q3|rdv=P;R6wi+7o_4t*7T81?@a$D@5ro9Q$+uU%F?#V zrt9X=k%%SSLc4wNaJotNgQA;M97EIWq3HvMrh6CX3{8VX?U5NYGFQL|xG*x8%h+mU z@H77pN2Xz98hNK7r}Xtfj9?4A??T@Vj=tSlbp$3y$m9>(I^cCM;s4`$4?H=)H z_{(n5#Uxr|4cquYZn6f6uH@9^A-0m7nNg(8B$SpbcoDY23l!v0-Yu1;Xp({4d^%%W?h*9EuKVk27U*%n?GRlbsETJyr; z{jI6KdBC;Xta@+>EF_f*H<)7Gge{SVw2Paw%H)CT2bc4eNEbPe?#NQ`nn>lmYd0^ZIw7B{}HT6c?@_f=L? z%<69DylFjeEOF}Iz*$WR^RMT0Xffc%gKC|?W}d(ll#X(7^f80&UOQV}X0#57WJ4J_ zeBj8zGb(a4@L@*(%D9xnqW&m3!l7klvMpwA1;f-G!=PvXL0MbB~&5oR?o#}B}C!&p{lF`%(nsFFrwA8YAjpwS)v2=K8wvyZ7O`WOWi zpQ!#%RJ`9~{`VN(zcK%BtZ|*1cJ3nDiN@|(8ms>+jhwa}9BoHt+nz*i7`4f%6QxjM z(A>rdSDu>Oaw8`P+;k&PO;h|ga^#^Xohl@AI`&M^Yq1zBhatZFl0N=LO_VBB!xb-NlS_C7~5*`n7ZcvMT7o{x%QqeBX+~ zU;+8yAhx_%r_yv&kw%XRd0?g_f<_OadU8=Nw03(B!HSj+xWSG?kFGo1J%K!l$xn3$ zJb`>H<7Y6jqHsd6fDS@wUFw>E6-u8FEDRL*KUH0YoALsA0oRa6`uaAx1MYw^3Df^nYHsnPSSk zBkh-p0-oaS&?##Eb)_9p$?oK@>(TlVK8cmkz1$3Pc8`djb=ISTE~Oq5w!3RQGT@n} z)Evn$Q!Zp&NT&Tuom7uMkqWp1qV7D#F+xS@QguzQhCc~^r6R(z-e#DNfL5uvG9#KApo18&<;Wg+*-0nN zJh(=g!{W)|knL_e8wdQM;MNVhk)>DEy z$VX6Ut+V^WECw*Edb(yURLB)XbaXl^M&Om|sXLpofPvvIC0_-5O|^W^x>GebFvT~f z=4&oM68taYs;=+S9sYxb?_f2nxw3Lg%PCCe?;*LQ{okl9->Sq|a|Af)u@ zNEjK9j>6?AbUB5`(^-xyQI6UsD_7Y+ER&Wy18e2#l!YG!0ik1v)xY7<*Zy9}i$!ti?_F~;>I8uWa zh=9H_=<%8)FHgWdny5i0E@Hu;C^_J2DO^poOPG@5 zhETkUad_mth;lDc-a<#qnSs#3av_nI$I89w9!Xyl#h=?fIb;DQquwpe8DZaJ?Wd+uCvUi0(hyym;|6br)S9QzCItuy_)t1x=$)-PtEoAQZ9(Smi6ikj3-7ah>9mL zVQBh3vLY6Jr>160qY-<2yJn4`z@Uego|ey8K<}yfoFi_4p@PPVOoOjz9o(5Dk?9JP zMbtpYS+~eT=+ZZk!n?c`BonB(Bri3+<`Yi#w+Z7#VDlCN8|v&NCZG}%wl%Wj#enXL z&|MKlbSKLu;|Dj9x4#2gc+tX3E!O-`TfoL@G-`2*Y%zHoG8nrJ8Pu#6iuJNskA|np zhCBVW@Gv9TNTT*>jQ;PBOw_Jh&y*ftDa8Uk-8JVU4k;uh0hOA|D1*wUOC@L_OFosA zke5a%eX4C|()0@n*ODJTL9EE%+-=oTv?aYc!Y$-7;ntRP_(a4Iz3K2t6iSE``O3Pr zOvUy`h6-z?%a|e7n85DT)WInt`EMRnw0S?b#DuSfHQ^O;-z{bhy zy2GakGVQ-ProAJI8c&7GT$TrNG%mXdUM$;zNXM+yjf13JuqilG;O4P!A}I{AQ2 zwhsVvXJRj}=?mau{$iuS%SH~|BxLs(rwQ(rVsbVbThel)k(L_`kjE3dKiX-XE}Zku zafcRQ2Ydo+Tr2F2W!|XBzZ=i!FV08taU{628Euiva<)-TH*u^~HxcD?XzwY8gYlbq zclb;}=Lp3ZF=f;KGihw+Lh!2aWUD}==gC&P=Cs<9E-to@1KyzHfJ|(hp3rOE#8IOM z@h!Q6^Vxvy@dY$6wHO0C%Na)DsL0L4HI`^pd|u6E`xb89#v`}zrdzqSfk$rTO}BCD zP9C|9H{H&yyLsex-n4;R_wvXF-gF1I?&py^c+;KSdXPu%XFVtw(v}9^P~>w;tz_dwJ7++wC=WDQ7wfz7c+t7xfD8Z3v0PVZTU!T zL9~90jCU@Pia!KpXN&CVS`jq+7SfSRrDh{SYI=t+Q2g%@{dEHs?6Rzao#QB&cU0sy zYJ54%9M0XsGN*GNFyEoYky7ApW!pGcx=mU_5h{MnYd+>mcg?wi{POKv;m?!!4Uz~J z$d)xcyhbgig>4OQe2C3_h$;Rxs*Og)I|ed+C+k1!xl0B`Ub;`QBgu`-u5>q};CZbK zo_Vit#YpVoXm>_iWWDix0e_A4l!6&-%QhlTa(Ne!C&N02kf67xW#sA=Bk3+FC4YD8 z-CM@dPq7vGSP0T`PdtY9!~tY7P8zEzq5_S+T?**8m*}#|vuwr`mr;BLoT1BQP+)Km zQ?cG3Ie@c~#EE8eqI<{L3$fPE358r6DG0hibW^k#5NIL;6kRLs25sG?rHf0z(a7$Z zBN++-eiDK0seZcKe}QOxpQUHM&q(6;=1A^7xnSgFPSakbslK1lIgC7Je}u_BF5Ys` z_D96|pz#39p4B`}G#}h%n`haI3cF1O>O9on<~eG!u|NL;jky2-V$^WgUDMhwHFFP z&b&~t6&DIb2p5T&7YSv>MS?CuXszjn1i(gPzFeti=0hU>r&wB^3LyR+-*TNAzF5%n z60u%Ryq@-7DpHM)vzd=GCGr^dH;=LKI{A$lI(w7ZUkzt)Ct=U?_5j>4c}n@#0G#vv z@qco0&R57;9Gy_rZIR33V=_=#2NUQYP;bv)jK}&=^lTte^&mCIfBF9j|Nj$Sv0b=A z5T}nzE3UEiK}J6`;l)#E;xU`FbYjml1UvT=)tN)&o+srarpD3~kBxNG;{|#=O=|pv zR1U90PHs|Pm7CNjnaVZy&vXEa?n}NP`jWMh)@-tWguiTKguiTKhJM+`sDIhUs57`F zB|A91Ex|gJ3Ln!?Vu`f@h<7DIZhGldeX~4OALU|F7{l$h@*`-w2FtC15{%U;;W;HF zuY=U(SF!8Z>FP7=A@&4&My6h7Z?pGhN_k4o!vPf9zQX=e_K(ox$v>Nbr%BHGGRJ=H z`OGo8Qi*ANl+An;x&>0G)$MW!e?dSj+w%T`wLUZ!Y4?Ld0A@AbBumb@Qz$YhHM$cvpr=k6|2E} zcD8yQiK~tuEJma&`O7(L8=`_(TAs9}yd@?$Ehh>hS zvTUuR#R@i^)scR_NWfc(^&non{Z6C=*Rp%q1GYLm&*+E+dkRP3gZTgR+lv=i=K5rt z4Kobd%`>^dL{gH--k7E_qzC_1gx%qb)qxi<-I*n>I~9JC`A;TSla`ZTC#k-`a>Zr$ zpVg%Q!l<;6oW6P_-C2&FY?HQZ(%mvd{-~vKNOz6w#9NTn54+bKqA#-k%dgD?gP<)r zOL;G&Q{+%)DgTgl%b87uKh5ez=Gto@hOWH^VvgUc&WQss=hI4p*pV)Ks`&S*9M@TC)Dc$P$@#aF#we&)SClPn+f$+|9Ke(UkB1) z<89Q^^e1f7rP%62R`(KlwU1b_3{#MQozd0SN6g`revFf`jN>zwVSl$Ic`P}?Nv2uJ z-}|d(jmY7<)N@bJ}UXL;pghUO}V$ z$ceNtgf}pRu^0j>yer*zi!BCP2I!qt1$&W^h}DA;wj$&pjvrj(#4G|Gy_Yd8@ZIg` z>icppG7q>bovlR4sK|q?@v8nkcPVxz53$Cp`!Qv}jBLEdX)t6|Bl_648!6TS3xo4e=X zUMla&mVesU*OM;FgU3ks&>h_Mg3qu>u|A>?tVEmrT@js(P?X+HH$YCDj|i}&hT7TZ zX}$8E(XQq#m)D6}%V!MF@OmK+)7Fbk^mU6E@=jkL{SvE?!mV`84cLsxdZ=3{2K$IkFBK?hr`&qUh!X+aeR`?-^2-aV1~!pU*kI#^#iIn|3`!TQR{ZT({c zJ_5TEZCzhq?tefj$|p=<-2ZWI9Bb8_0pkhddSz9LNxdc`v6r0QsSoL>IsMb3qx%f2w=bkS!jbj^pS zOFrH5>5<>o=TW6m9Yud~i+JGIY(-f|VTh3)5XJe5O|tPDF0U8A;jrS4{0xFSh=RuN zC|e-EDgTahyLb78q4S%te7ZBlNa*FaUmHVgXL;pFkWXJ3ruzCa+!Hm@jt-A^7e-WC zMmZfApi=WYx|PFdFKo@hSF-ULR8dWxf-KFSdk{{her8JXd(_{b5S9bjPd0YSiG3-- z_9EFPk1E&v#N-Y<(?y<5f8gLeL+)}$=91L%<;dLqHPL;=Vn@}{Da*LpU zSm7?A7+&RWp}4%tJwkDNm3xKa@hbNTB~K{#3nkyBJRp<;m-3)c3d@v-gi`=lbWWi z7`3J4d!Fd+-g@-(k_)f&=DKs!ZFrw$&Mo&wQS-1+K(7ZR$_}7gI_r3i{AhZN|9j>g zFEPJ~GMG_19sYt@tF?9hFPJxz54b4X@&o$!CK)Q*F5Qjwh>ivQgo0nc&c09r!#${b zlRX9S(CYdUAAOMYH3-qTDMj}_Ds3`bek7`+nbLz)e;cu$e!-s(xcpzTmY=A~uULza zLX~2>3SU2=xW5Od_E)UsXR7@i)&7}kS5g&^b%J(_^YMzuI#KKI2xGX7v0Jb0{_bBv+$qf)$?WqhbeTlve#Qpp+kB!eYpQE>#o@(ScyDpLI&K0AAv5F6*!0^ zHj44yGAEO%QuC-#!0Z&27jNk6bEz(#N?~Ga9utzA6vQRd-%$EHI}M(~Uor$Dn5|UH zFUWntYK~J`?RPLMgQFe=OWDEIe!MF0$f(hAA3kZ{z zqAaIyxW5h1WbzqMec!^@(xP!|5mt>qxW%l~H0yNDTB})SXx5pUb(UtGty$-2 z*14K>o@Sk|Sr=&5g_?DdW?igVmuS|dnzc@|F4L^bHR}q^x>B>Q(yXgB>l)3vRB5 z(XP|lpv~vj9kT3BD!WT2@22EEGIzr;R3$y@tLJ}8q9Qt~00e29`8 zG4f99VM=b2*iDptL?$1hxlGv9h`7)-s z(|U!HhY|8HBwm#ryhga!W%3P5z9}2MMaj2i@*PUPE0gb1@;#Y+kCN|8svl7DLy7%} zk{?4uI;~GA`KiQyDye@;v-DZNxIdTJ&nfwZ#C}Q1ub@<&*4LE$Mq&AVn{~H#gy$ zQu-(0U(&+gfd2@52>7p5cm!A%SeIjUh+lVO+F+{;n;bOhCqh^->8=nKO}aaTLnhrB z!o8-Y$*_YZgLX@X;fQJVaMV>8GwIYG8b^h)Nt-=X0h}-`bJ!(lJzl zkBTvh`H0ntv(j-Kg_(%M(h0C9K^8$U6Lbm$6HKRp;LT!9;!|`6WpHaTTDS&JSGwum z;@EW7@Cop1u}m>JIwwjQ4ty{SadkS6vI`(f(m%s-5S}8QLmx^{L16WC(QttL2rSG= zOj>4^&6{lQ^BPJuDh||;8D7y-R$U@hEu7e=Dh+Bz!h+{~Yp&N$h{U)lw0_heAf)3pV zLVS_HLwCR;LeO0x*eC@USePiSfYd}T$TuPq1pY&7Am2*MAm4#}Z}`G7FET)W5PJjp z5#%T78^|vvy)`rH*@EsbYQALfm4dG`-1j7|96j`_VZ!s!lZmnO;%G09!u=XCj+U%C zo5M5A{$}W2I2m3>WqeyidPzayS#3wKJy+B#`KvxM4x;70)tVF_{XHznt*dP3fWNEL z<0HGS`FIsyR9b8QIc}j4wy;)ft6yuYJ|qHna`nMTV6LH>l3w>$Q;W@Kg8@Ia_;jd- z6FK}M5&&P2wb{L@?ZI_eVO@%X?b++$x>Q%v-uJRMLasY$li8ag^K8;S#O-lOMcd5A zaJu5V%v3pNt$Q_-H^+fgb|H~;P4iaozuSk9#M<@v|^GR}HxJFYi& zitA4)6F2eA8#PC=p~6?GlFjW&8@1|dct{hS5tX>_**k42$qyhj&`z~A{0CK(WOSE@ zzsGiQ*&!9~m3A7JIcjQKhJJ??GAo~oGNo{zD=+wtsF;%6k!+%+T97ZRzJx!RkR|q` zD%z76xU8vO)+xcKA5*xMeUgP%bn3MVBpq)zv=b^?09^^KDV4Mph(4+QX909ksSZE( zQuK0eUIjHfr-D^Gsi5;T)0nL)jO~JgRZQSva=)^(IQx`}cBSSgu-0?h@sr@sIDQ)Z zS;tqwpL6^y_z&a*9L<+?BH+BMFoy~k96t|!$?*%|msPZ7uNL-xTheaBZ!Y1j{wDW{ N=}kMC{SRmsVf86^2=M>_ literal 0 HcmV?d00001 diff --git a/node_modules/node-forge/lib/aes.js b/node_modules/node-forge/lib/aes.js new file mode 100644 index 0000000..3c1ddb2 --- /dev/null +++ b/node_modules/node-forge/lib/aes.js @@ -0,0 +1,1091 @@ +/** + * Advanced Encryption Standard (AES) implementation. + * + * This implementation is based on the public domain library 'jscrypto' which + * was written by: + * + * Emily Stark (estark@stanford.edu) + * Mike Hamburg (mhamburg@stanford.edu) + * Dan Boneh (dabo@cs.stanford.edu) + * + * Parts of this code are based on the OpenSSL implementation of AES: + * http://www.openssl.org + * + * @author Dave Longley + * + * Copyright (c) 2010-2014 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./cipher'); +require('./cipherModes'); +require('./util'); + +/* AES API */ +module.exports = forge.aes = forge.aes || {}; + +/** + * Deprecated. Instead, use: + * + * var cipher = forge.cipher.createCipher('AES-', key); + * cipher.start({iv: iv}); + * + * Creates an AES cipher object to encrypt data using the given symmetric key. + * The output will be stored in the 'output' member of the returned cipher. + * + * The key and iv may be given as a string of bytes, an array of bytes, + * a byte buffer, or an array of 32-bit words. + * + * @param key the symmetric key to use. + * @param iv the initialization vector to use. + * @param output the buffer to write to, null to create one. + * @param mode the cipher mode to use (default: 'CBC'). + * + * @return the cipher. + */ +forge.aes.startEncrypting = function(key, iv, output, mode) { + var cipher = _createCipher({ + key: key, + output: output, + decrypt: false, + mode: mode + }); + cipher.start(iv); + return cipher; +}; + +/** + * Deprecated. Instead, use: + * + * var cipher = forge.cipher.createCipher('AES-', key); + * + * Creates an AES cipher object to encrypt data using the given symmetric key. + * + * The key may be given as a string of bytes, an array of bytes, a + * byte buffer, or an array of 32-bit words. + * + * @param key the symmetric key to use. + * @param mode the cipher mode to use (default: 'CBC'). + * + * @return the cipher. + */ +forge.aes.createEncryptionCipher = function(key, mode) { + return _createCipher({ + key: key, + output: null, + decrypt: false, + mode: mode + }); +}; + +/** + * Deprecated. Instead, use: + * + * var decipher = forge.cipher.createDecipher('AES-', key); + * decipher.start({iv: iv}); + * + * Creates an AES cipher object to decrypt data using the given symmetric key. + * The output will be stored in the 'output' member of the returned cipher. + * + * The key and iv may be given as a string of bytes, an array of bytes, + * a byte buffer, or an array of 32-bit words. + * + * @param key the symmetric key to use. + * @param iv the initialization vector to use. + * @param output the buffer to write to, null to create one. + * @param mode the cipher mode to use (default: 'CBC'). + * + * @return the cipher. + */ +forge.aes.startDecrypting = function(key, iv, output, mode) { + var cipher = _createCipher({ + key: key, + output: output, + decrypt: true, + mode: mode + }); + cipher.start(iv); + return cipher; +}; + +/** + * Deprecated. Instead, use: + * + * var decipher = forge.cipher.createDecipher('AES-', key); + * + * Creates an AES cipher object to decrypt data using the given symmetric key. + * + * The key may be given as a string of bytes, an array of bytes, a + * byte buffer, or an array of 32-bit words. + * + * @param key the symmetric key to use. + * @param mode the cipher mode to use (default: 'CBC'). + * + * @return the cipher. + */ +forge.aes.createDecryptionCipher = function(key, mode) { + return _createCipher({ + key: key, + output: null, + decrypt: true, + mode: mode + }); +}; + +/** + * Creates a new AES cipher algorithm object. + * + * @param name the name of the algorithm. + * @param mode the mode factory function. + * + * @return the AES algorithm object. + */ +forge.aes.Algorithm = function(name, mode) { + if(!init) { + initialize(); + } + var self = this; + self.name = name; + self.mode = new mode({ + blockSize: 16, + cipher: { + encrypt: function(inBlock, outBlock) { + return _updateBlock(self._w, inBlock, outBlock, false); + }, + decrypt: function(inBlock, outBlock) { + return _updateBlock(self._w, inBlock, outBlock, true); + } + } + }); + self._init = false; +}; + +/** + * Initializes this AES algorithm by expanding its key. + * + * @param options the options to use. + * key the key to use with this algorithm. + * decrypt true if the algorithm should be initialized for decryption, + * false for encryption. + */ +forge.aes.Algorithm.prototype.initialize = function(options) { + if(this._init) { + return; + } + + var key = options.key; + var tmp; + + /* Note: The key may be a string of bytes, an array of bytes, a byte + buffer, or an array of 32-bit integers. If the key is in bytes, then + it must be 16, 24, or 32 bytes in length. If it is in 32-bit + integers, it must be 4, 6, or 8 integers long. */ + + if(typeof key === 'string' && + (key.length === 16 || key.length === 24 || key.length === 32)) { + // convert key string into byte buffer + key = forge.util.createBuffer(key); + } else if(forge.util.isArray(key) && + (key.length === 16 || key.length === 24 || key.length === 32)) { + // convert key integer array into byte buffer + tmp = key; + key = forge.util.createBuffer(); + for(var i = 0; i < tmp.length; ++i) { + key.putByte(tmp[i]); + } + } + + // convert key byte buffer into 32-bit integer array + if(!forge.util.isArray(key)) { + tmp = key; + key = []; + + // key lengths of 16, 24, 32 bytes allowed + var len = tmp.length(); + if(len === 16 || len === 24 || len === 32) { + len = len >>> 2; + for(var i = 0; i < len; ++i) { + key.push(tmp.getInt32()); + } + } + } + + // key must be an array of 32-bit integers by now + if(!forge.util.isArray(key) || + !(key.length === 4 || key.length === 6 || key.length === 8)) { + throw new Error('Invalid key parameter.'); + } + + // encryption operation is always used for these modes + var mode = this.mode.name; + var encryptOp = (['CFB', 'OFB', 'CTR', 'GCM'].indexOf(mode) !== -1); + + // do key expansion + this._w = _expandKey(key, options.decrypt && !encryptOp); + this._init = true; +}; + +/** + * Expands a key. Typically only used for testing. + * + * @param key the symmetric key to expand, as an array of 32-bit words. + * @param decrypt true to expand for decryption, false for encryption. + * + * @return the expanded key. + */ +forge.aes._expandKey = function(key, decrypt) { + if(!init) { + initialize(); + } + return _expandKey(key, decrypt); +}; + +/** + * Updates a single block. Typically only used for testing. + * + * @param w the expanded key to use. + * @param input an array of block-size 32-bit words. + * @param output an array of block-size 32-bit words. + * @param decrypt true to decrypt, false to encrypt. + */ +forge.aes._updateBlock = _updateBlock; + +/** Register AES algorithms **/ + +registerAlgorithm('AES-ECB', forge.cipher.modes.ecb); +registerAlgorithm('AES-CBC', forge.cipher.modes.cbc); +registerAlgorithm('AES-CFB', forge.cipher.modes.cfb); +registerAlgorithm('AES-OFB', forge.cipher.modes.ofb); +registerAlgorithm('AES-CTR', forge.cipher.modes.ctr); +registerAlgorithm('AES-GCM', forge.cipher.modes.gcm); + +function registerAlgorithm(name, mode) { + var factory = function() { + return new forge.aes.Algorithm(name, mode); + }; + forge.cipher.registerAlgorithm(name, factory); +} + +/** AES implementation **/ + +var init = false; // not yet initialized +var Nb = 4; // number of words comprising the state (AES = 4) +var sbox; // non-linear substitution table used in key expansion +var isbox; // inversion of sbox +var rcon; // round constant word array +var mix; // mix-columns table +var imix; // inverse mix-columns table + +/** + * Performs initialization, ie: precomputes tables to optimize for speed. + * + * One way to understand how AES works is to imagine that 'addition' and + * 'multiplication' are interfaces that require certain mathematical + * properties to hold true (ie: they are associative) but they might have + * different implementations and produce different kinds of results ... + * provided that their mathematical properties remain true. AES defines + * its own methods of addition and multiplication but keeps some important + * properties the same, ie: associativity and distributivity. The + * explanation below tries to shed some light on how AES defines addition + * and multiplication of bytes and 32-bit words in order to perform its + * encryption and decryption algorithms. + * + * The basics: + * + * The AES algorithm views bytes as binary representations of polynomials + * that have either 1 or 0 as the coefficients. It defines the addition + * or subtraction of two bytes as the XOR operation. It also defines the + * multiplication of two bytes as a finite field referred to as GF(2^8) + * (Note: 'GF' means "Galois Field" which is a field that contains a finite + * number of elements so GF(2^8) has 256 elements). + * + * This means that any two bytes can be represented as binary polynomials; + * when they multiplied together and modularly reduced by an irreducible + * polynomial of the 8th degree, the results are the field GF(2^8). The + * specific irreducible polynomial that AES uses in hexadecimal is 0x11b. + * This multiplication is associative with 0x01 as the identity: + * + * (b * 0x01 = GF(b, 0x01) = b). + * + * The operation GF(b, 0x02) can be performed at the byte level by left + * shifting b once and then XOR'ing it (to perform the modular reduction) + * with 0x11b if b is >= 128. Repeated application of the multiplication + * of 0x02 can be used to implement the multiplication of any two bytes. + * + * For instance, multiplying 0x57 and 0x13, denoted as GF(0x57, 0x13), can + * be performed by factoring 0x13 into 0x01, 0x02, and 0x10. Then these + * factors can each be multiplied by 0x57 and then added together. To do + * the multiplication, values for 0x57 multiplied by each of these 3 factors + * can be precomputed and stored in a table. To add them, the values from + * the table are XOR'd together. + * + * AES also defines addition and multiplication of words, that is 4-byte + * numbers represented as polynomials of 3 degrees where the coefficients + * are the values of the bytes. + * + * The word [a0, a1, a2, a3] is a polynomial a3x^3 + a2x^2 + a1x + a0. + * + * Addition is performed by XOR'ing like powers of x. Multiplication + * is performed in two steps, the first is an algebriac expansion as + * you would do normally (where addition is XOR). But the result is + * a polynomial larger than 3 degrees and thus it cannot fit in a word. So + * next the result is modularly reduced by an AES-specific polynomial of + * degree 4 which will always produce a polynomial of less than 4 degrees + * such that it will fit in a word. In AES, this polynomial is x^4 + 1. + * + * The modular product of two polynomials 'a' and 'b' is thus: + * + * d(x) = d3x^3 + d2x^2 + d1x + d0 + * with + * d0 = GF(a0, b0) ^ GF(a3, b1) ^ GF(a2, b2) ^ GF(a1, b3) + * d1 = GF(a1, b0) ^ GF(a0, b1) ^ GF(a3, b2) ^ GF(a2, b3) + * d2 = GF(a2, b0) ^ GF(a1, b1) ^ GF(a0, b2) ^ GF(a3, b3) + * d3 = GF(a3, b0) ^ GF(a2, b1) ^ GF(a1, b2) ^ GF(a0, b3) + * + * As a matrix: + * + * [d0] = [a0 a3 a2 a1][b0] + * [d1] [a1 a0 a3 a2][b1] + * [d2] [a2 a1 a0 a3][b2] + * [d3] [a3 a2 a1 a0][b3] + * + * Special polynomials defined by AES (0x02 == {02}): + * a(x) = {03}x^3 + {01}x^2 + {01}x + {02} + * a^-1(x) = {0b}x^3 + {0d}x^2 + {09}x + {0e}. + * + * These polynomials are used in the MixColumns() and InverseMixColumns() + * operations, respectively, to cause each element in the state to affect + * the output (referred to as diffusing). + * + * RotWord() uses: a0 = a1 = a2 = {00} and a3 = {01}, which is the + * polynomial x3. + * + * The ShiftRows() method modifies the last 3 rows in the state (where + * the state is 4 words with 4 bytes per word) by shifting bytes cyclically. + * The 1st byte in the second row is moved to the end of the row. The 1st + * and 2nd bytes in the third row are moved to the end of the row. The 1st, + * 2nd, and 3rd bytes are moved in the fourth row. + * + * More details on how AES arithmetic works: + * + * In the polynomial representation of binary numbers, XOR performs addition + * and subtraction and multiplication in GF(2^8) denoted as GF(a, b) + * corresponds with the multiplication of polynomials modulo an irreducible + * polynomial of degree 8. In other words, for AES, GF(a, b) will multiply + * polynomial 'a' with polynomial 'b' and then do a modular reduction by + * an AES-specific irreducible polynomial of degree 8. + * + * A polynomial is irreducible if its only divisors are one and itself. For + * the AES algorithm, this irreducible polynomial is: + * + * m(x) = x^8 + x^4 + x^3 + x + 1, + * + * or {01}{1b} in hexadecimal notation, where each coefficient is a bit: + * 100011011 = 283 = 0x11b. + * + * For example, GF(0x57, 0x83) = 0xc1 because + * + * 0x57 = 87 = 01010111 = x^6 + x^4 + x^2 + x + 1 + * 0x85 = 131 = 10000101 = x^7 + x + 1 + * + * (x^6 + x^4 + x^2 + x + 1) * (x^7 + x + 1) + * = x^13 + x^11 + x^9 + x^8 + x^7 + + * x^7 + x^5 + x^3 + x^2 + x + + * x^6 + x^4 + x^2 + x + 1 + * = x^13 + x^11 + x^9 + x^8 + x^6 + x^5 + x^4 + x^3 + 1 = y + * y modulo (x^8 + x^4 + x^3 + x + 1) + * = x^7 + x^6 + 1. + * + * The modular reduction by m(x) guarantees the result will be a binary + * polynomial of less than degree 8, so that it can fit in a byte. + * + * The operation to multiply a binary polynomial b with x (the polynomial + * x in binary representation is 00000010) is: + * + * b_7x^8 + b_6x^7 + b_5x^6 + b_4x^5 + b_3x^4 + b_2x^3 + b_1x^2 + b_0x^1 + * + * To get GF(b, x) we must reduce that by m(x). If b_7 is 0 (that is the + * most significant bit is 0 in b) then the result is already reduced. If + * it is 1, then we can reduce it by subtracting m(x) via an XOR. + * + * It follows that multiplication by x (00000010 or 0x02) can be implemented + * by performing a left shift followed by a conditional bitwise XOR with + * 0x1b. This operation on bytes is denoted by xtime(). Multiplication by + * higher powers of x can be implemented by repeated application of xtime(). + * + * By adding intermediate results, multiplication by any constant can be + * implemented. For instance: + * + * GF(0x57, 0x13) = 0xfe because: + * + * xtime(b) = (b & 128) ? (b << 1 ^ 0x11b) : (b << 1) + * + * Note: We XOR with 0x11b instead of 0x1b because in javascript our + * datatype for b can be larger than 1 byte, so a left shift will not + * automatically eliminate bits that overflow a byte ... by XOR'ing the + * overflow bit with 1 (the extra one from 0x11b) we zero it out. + * + * GF(0x57, 0x02) = xtime(0x57) = 0xae + * GF(0x57, 0x04) = xtime(0xae) = 0x47 + * GF(0x57, 0x08) = xtime(0x47) = 0x8e + * GF(0x57, 0x10) = xtime(0x8e) = 0x07 + * + * GF(0x57, 0x13) = GF(0x57, (0x01 ^ 0x02 ^ 0x10)) + * + * And by the distributive property (since XOR is addition and GF() is + * multiplication): + * + * = GF(0x57, 0x01) ^ GF(0x57, 0x02) ^ GF(0x57, 0x10) + * = 0x57 ^ 0xae ^ 0x07 + * = 0xfe. + */ +function initialize() { + init = true; + + /* Populate the Rcon table. These are the values given by + [x^(i-1),{00},{00},{00}] where x^(i-1) are powers of x (and x = 0x02) + in the field of GF(2^8), where i starts at 1. + + rcon[0] = [0x00, 0x00, 0x00, 0x00] + rcon[1] = [0x01, 0x00, 0x00, 0x00] 2^(1-1) = 2^0 = 1 + rcon[2] = [0x02, 0x00, 0x00, 0x00] 2^(2-1) = 2^1 = 2 + ... + rcon[9] = [0x1B, 0x00, 0x00, 0x00] 2^(9-1) = 2^8 = 0x1B + rcon[10] = [0x36, 0x00, 0x00, 0x00] 2^(10-1) = 2^9 = 0x36 + + We only store the first byte because it is the only one used. + */ + rcon = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1B, 0x36]; + + // compute xtime table which maps i onto GF(i, 0x02) + var xtime = new Array(256); + for(var i = 0; i < 128; ++i) { + xtime[i] = i << 1; + xtime[i + 128] = (i + 128) << 1 ^ 0x11B; + } + + // compute all other tables + sbox = new Array(256); + isbox = new Array(256); + mix = new Array(4); + imix = new Array(4); + for(var i = 0; i < 4; ++i) { + mix[i] = new Array(256); + imix[i] = new Array(256); + } + var e = 0, ei = 0, e2, e4, e8, sx, sx2, me, ime; + for(var i = 0; i < 256; ++i) { + /* We need to generate the SubBytes() sbox and isbox tables so that + we can perform byte substitutions. This requires us to traverse + all of the elements in GF, find their multiplicative inverses, + and apply to each the following affine transformation: + + bi' = bi ^ b(i + 4) mod 8 ^ b(i + 5) mod 8 ^ b(i + 6) mod 8 ^ + b(i + 7) mod 8 ^ ci + for 0 <= i < 8, where bi is the ith bit of the byte, and ci is the + ith bit of a byte c with the value {63} or {01100011}. + + It is possible to traverse every possible value in a Galois field + using what is referred to as a 'generator'. There are many + generators (128 out of 256): 3,5,6,9,11,82 to name a few. To fully + traverse GF we iterate 255 times, multiplying by our generator + each time. + + On each iteration we can determine the multiplicative inverse for + the current element. + + Suppose there is an element in GF 'e'. For a given generator 'g', + e = g^x. The multiplicative inverse of e is g^(255 - x). It turns + out that if use the inverse of a generator as another generator + it will produce all of the corresponding multiplicative inverses + at the same time. For this reason, we choose 5 as our inverse + generator because it only requires 2 multiplies and 1 add and its + inverse, 82, requires relatively few operations as well. + + In order to apply the affine transformation, the multiplicative + inverse 'ei' of 'e' can be repeatedly XOR'd (4 times) with a + bit-cycling of 'ei'. To do this 'ei' is first stored in 's' and + 'x'. Then 's' is left shifted and the high bit of 's' is made the + low bit. The resulting value is stored in 's'. Then 'x' is XOR'd + with 's' and stored in 'x'. On each subsequent iteration the same + operation is performed. When 4 iterations are complete, 'x' is + XOR'd with 'c' (0x63) and the transformed value is stored in 'x'. + For example: + + s = 01000001 + x = 01000001 + + iteration 1: s = 10000010, x ^= s + iteration 2: s = 00000101, x ^= s + iteration 3: s = 00001010, x ^= s + iteration 4: s = 00010100, x ^= s + x ^= 0x63 + + This can be done with a loop where s = (s << 1) | (s >> 7). However, + it can also be done by using a single 16-bit (in this case 32-bit) + number 'sx'. Since XOR is an associative operation, we can set 'sx' + to 'ei' and then XOR it with 'sx' left-shifted 1,2,3, and 4 times. + The most significant bits will flow into the high 8 bit positions + and be correctly XOR'd with one another. All that remains will be + to cycle the high 8 bits by XOR'ing them all with the lower 8 bits + afterwards. + + At the same time we're populating sbox and isbox we can precompute + the multiplication we'll need to do to do MixColumns() later. + */ + + // apply affine transformation + sx = ei ^ (ei << 1) ^ (ei << 2) ^ (ei << 3) ^ (ei << 4); + sx = (sx >> 8) ^ (sx & 255) ^ 0x63; + + // update tables + sbox[e] = sx; + isbox[sx] = e; + + /* Mixing columns is done using matrix multiplication. The columns + that are to be mixed are each a single word in the current state. + The state has Nb columns (4 columns). Therefore each column is a + 4 byte word. So to mix the columns in a single column 'c' where + its rows are r0, r1, r2, and r3, we use the following matrix + multiplication: + + [2 3 1 1]*[r0,c]=[r'0,c] + [1 2 3 1] [r1,c] [r'1,c] + [1 1 2 3] [r2,c] [r'2,c] + [3 1 1 2] [r3,c] [r'3,c] + + r0, r1, r2, and r3 are each 1 byte of one of the words in the + state (a column). To do matrix multiplication for each mixed + column c' we multiply the corresponding row from the left matrix + with the corresponding column from the right matrix. In total, we + get 4 equations: + + r0,c' = 2*r0,c + 3*r1,c + 1*r2,c + 1*r3,c + r1,c' = 1*r0,c + 2*r1,c + 3*r2,c + 1*r3,c + r2,c' = 1*r0,c + 1*r1,c + 2*r2,c + 3*r3,c + r3,c' = 3*r0,c + 1*r1,c + 1*r2,c + 2*r3,c + + As usual, the multiplication is as previously defined and the + addition is XOR. In order to optimize mixing columns we can store + the multiplication results in tables. If you think of the whole + column as a word (it might help to visualize by mentally rotating + the equations above by counterclockwise 90 degrees) then you can + see that it would be useful to map the multiplications performed on + each byte (r0, r1, r2, r3) onto a word as well. For instance, we + could map 2*r0,1*r0,1*r0,3*r0 onto a word by storing 2*r0 in the + highest 8 bits and 3*r0 in the lowest 8 bits (with the other two + respectively in the middle). This means that a table can be + constructed that uses r0 as an index to the word. We can do the + same with r1, r2, and r3, creating a total of 4 tables. + + To construct a full c', we can just look up each byte of c in + their respective tables and XOR the results together. + + Also, to build each table we only have to calculate the word + for 2,1,1,3 for every byte ... which we can do on each iteration + of this loop since we will iterate over every byte. After we have + calculated 2,1,1,3 we can get the results for the other tables + by cycling the byte at the end to the beginning. For instance + we can take the result of table 2,1,1,3 and produce table 3,2,1,1 + by moving the right most byte to the left most position just like + how you can imagine the 3 moved out of 2,1,1,3 and to the front + to produce 3,2,1,1. + + There is another optimization in that the same multiples of + the current element we need in order to advance our generator + to the next iteration can be reused in performing the 2,1,1,3 + calculation. We also calculate the inverse mix column tables, + with e,9,d,b being the inverse of 2,1,1,3. + + When we're done, and we need to actually mix columns, the first + byte of each state word should be put through mix[0] (2,1,1,3), + the second through mix[1] (3,2,1,1) and so forth. Then they should + be XOR'd together to produce the fully mixed column. + */ + + // calculate mix and imix table values + sx2 = xtime[sx]; + e2 = xtime[e]; + e4 = xtime[e2]; + e8 = xtime[e4]; + me = + (sx2 << 24) ^ // 2 + (sx << 16) ^ // 1 + (sx << 8) ^ // 1 + (sx ^ sx2); // 3 + ime = + (e2 ^ e4 ^ e8) << 24 ^ // E (14) + (e ^ e8) << 16 ^ // 9 + (e ^ e4 ^ e8) << 8 ^ // D (13) + (e ^ e2 ^ e8); // B (11) + // produce each of the mix tables by rotating the 2,1,1,3 value + for(var n = 0; n < 4; ++n) { + mix[n][e] = me; + imix[n][sx] = ime; + // cycle the right most byte to the left most position + // ie: 2,1,1,3 becomes 3,2,1,1 + me = me << 24 | me >>> 8; + ime = ime << 24 | ime >>> 8; + } + + // get next element and inverse + if(e === 0) { + // 1 is the inverse of 1 + e = ei = 1; + } else { + // e = 2e + 2*2*2*(10e)) = multiply e by 82 (chosen generator) + // ei = ei + 2*2*ei = multiply ei by 5 (inverse generator) + e = e2 ^ xtime[xtime[xtime[e2 ^ e8]]]; + ei ^= xtime[xtime[ei]]; + } + } +} + +/** + * Generates a key schedule using the AES key expansion algorithm. + * + * The AES algorithm takes the Cipher Key, K, and performs a Key Expansion + * routine to generate a key schedule. The Key Expansion generates a total + * of Nb*(Nr + 1) words: the algorithm requires an initial set of Nb words, + * and each of the Nr rounds requires Nb words of key data. The resulting + * key schedule consists of a linear array of 4-byte words, denoted [wi ], + * with i in the range 0 <= i < Nb(Nr + 1). + * + * KeyExpansion(byte key[4*Nk], word w[Nb*(Nr+1)], Nk) + * AES-128 (Nb=4, Nk=4, Nr=10) + * AES-192 (Nb=4, Nk=6, Nr=12) + * AES-256 (Nb=4, Nk=8, Nr=14) + * Note: Nr=Nk+6. + * + * Nb is the number of columns (32-bit words) comprising the State (or + * number of bytes in a block). For AES, Nb=4. + * + * @param key the key to schedule (as an array of 32-bit words). + * @param decrypt true to modify the key schedule to decrypt, false not to. + * + * @return the generated key schedule. + */ +function _expandKey(key, decrypt) { + // copy the key's words to initialize the key schedule + var w = key.slice(0); + + /* RotWord() will rotate a word, moving the first byte to the last + byte's position (shifting the other bytes left). + + We will be getting the value of Rcon at i / Nk. 'i' will iterate + from Nk to (Nb * Nr+1). Nk = 4 (4 byte key), Nb = 4 (4 words in + a block), Nr = Nk + 6 (10). Therefore 'i' will iterate from + 4 to 44 (exclusive). Each time we iterate 4 times, i / Nk will + increase by 1. We use a counter iNk to keep track of this. + */ + + // go through the rounds expanding the key + var temp, iNk = 1; + var Nk = w.length; + var Nr1 = Nk + 6 + 1; + var end = Nb * Nr1; + for(var i = Nk; i < end; ++i) { + temp = w[i - 1]; + if(i % Nk === 0) { + // temp = SubWord(RotWord(temp)) ^ Rcon[i / Nk] + temp = + sbox[temp >>> 16 & 255] << 24 ^ + sbox[temp >>> 8 & 255] << 16 ^ + sbox[temp & 255] << 8 ^ + sbox[temp >>> 24] ^ (rcon[iNk] << 24); + iNk++; + } else if(Nk > 6 && (i % Nk === 4)) { + // temp = SubWord(temp) + temp = + sbox[temp >>> 24] << 24 ^ + sbox[temp >>> 16 & 255] << 16 ^ + sbox[temp >>> 8 & 255] << 8 ^ + sbox[temp & 255]; + } + w[i] = w[i - Nk] ^ temp; + } + + /* When we are updating a cipher block we always use the code path for + encryption whether we are decrypting or not (to shorten code and + simplify the generation of look up tables). However, because there + are differences in the decryption algorithm, other than just swapping + in different look up tables, we must transform our key schedule to + account for these changes: + + 1. The decryption algorithm gets its key rounds in reverse order. + 2. The decryption algorithm adds the round key before mixing columns + instead of afterwards. + + We don't need to modify our key schedule to handle the first case, + we can just traverse the key schedule in reverse order when decrypting. + + The second case requires a little work. + + The tables we built for performing rounds will take an input and then + perform SubBytes() and MixColumns() or, for the decrypt version, + InvSubBytes() and InvMixColumns(). But the decrypt algorithm requires + us to AddRoundKey() before InvMixColumns(). This means we'll need to + apply some transformations to the round key to inverse-mix its columns + so they'll be correct for moving AddRoundKey() to after the state has + had its columns inverse-mixed. + + To inverse-mix the columns of the state when we're decrypting we use a + lookup table that will apply InvSubBytes() and InvMixColumns() at the + same time. However, the round key's bytes are not inverse-substituted + in the decryption algorithm. To get around this problem, we can first + substitute the bytes in the round key so that when we apply the + transformation via the InvSubBytes()+InvMixColumns() table, it will + undo our substitution leaving us with the original value that we + want -- and then inverse-mix that value. + + This change will correctly alter our key schedule so that we can XOR + each round key with our already transformed decryption state. This + allows us to use the same code path as the encryption algorithm. + + We make one more change to the decryption key. Since the decryption + algorithm runs in reverse from the encryption algorithm, we reverse + the order of the round keys to avoid having to iterate over the key + schedule backwards when running the encryption algorithm later in + decryption mode. In addition to reversing the order of the round keys, + we also swap each round key's 2nd and 4th rows. See the comments + section where rounds are performed for more details about why this is + done. These changes are done inline with the other substitution + described above. + */ + if(decrypt) { + var tmp; + var m0 = imix[0]; + var m1 = imix[1]; + var m2 = imix[2]; + var m3 = imix[3]; + var wnew = w.slice(0); + end = w.length; + for(var i = 0, wi = end - Nb; i < end; i += Nb, wi -= Nb) { + // do not sub the first or last round key (round keys are Nb + // words) as no column mixing is performed before they are added, + // but do change the key order + if(i === 0 || i === (end - Nb)) { + wnew[i] = w[wi]; + wnew[i + 1] = w[wi + 3]; + wnew[i + 2] = w[wi + 2]; + wnew[i + 3] = w[wi + 1]; + } else { + // substitute each round key byte because the inverse-mix + // table will inverse-substitute it (effectively cancel the + // substitution because round key bytes aren't sub'd in + // decryption mode) and swap indexes 3 and 1 + for(var n = 0; n < Nb; ++n) { + tmp = w[wi + n]; + wnew[i + (3&-n)] = + m0[sbox[tmp >>> 24]] ^ + m1[sbox[tmp >>> 16 & 255]] ^ + m2[sbox[tmp >>> 8 & 255]] ^ + m3[sbox[tmp & 255]]; + } + } + } + w = wnew; + } + + return w; +} + +/** + * Updates a single block (16 bytes) using AES. The update will either + * encrypt or decrypt the block. + * + * @param w the key schedule. + * @param input the input block (an array of 32-bit words). + * @param output the updated output block. + * @param decrypt true to decrypt the block, false to encrypt it. + */ +function _updateBlock(w, input, output, decrypt) { + /* + Cipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)]) + begin + byte state[4,Nb] + state = in + AddRoundKey(state, w[0, Nb-1]) + for round = 1 step 1 to Nr-1 + SubBytes(state) + ShiftRows(state) + MixColumns(state) + AddRoundKey(state, w[round*Nb, (round+1)*Nb-1]) + end for + SubBytes(state) + ShiftRows(state) + AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) + out = state + end + + InvCipher(byte in[4*Nb], byte out[4*Nb], word w[Nb*(Nr+1)]) + begin + byte state[4,Nb] + state = in + AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) + for round = Nr-1 step -1 downto 1 + InvShiftRows(state) + InvSubBytes(state) + AddRoundKey(state, w[round*Nb, (round+1)*Nb-1]) + InvMixColumns(state) + end for + InvShiftRows(state) + InvSubBytes(state) + AddRoundKey(state, w[0, Nb-1]) + out = state + end + */ + + // Encrypt: AddRoundKey(state, w[0, Nb-1]) + // Decrypt: AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) + var Nr = w.length / 4 - 1; + var m0, m1, m2, m3, sub; + if(decrypt) { + m0 = imix[0]; + m1 = imix[1]; + m2 = imix[2]; + m3 = imix[3]; + sub = isbox; + } else { + m0 = mix[0]; + m1 = mix[1]; + m2 = mix[2]; + m3 = mix[3]; + sub = sbox; + } + var a, b, c, d, a2, b2, c2; + a = input[0] ^ w[0]; + b = input[decrypt ? 3 : 1] ^ w[1]; + c = input[2] ^ w[2]; + d = input[decrypt ? 1 : 3] ^ w[3]; + var i = 3; + + /* In order to share code we follow the encryption algorithm when both + encrypting and decrypting. To account for the changes required in the + decryption algorithm, we use different lookup tables when decrypting + and use a modified key schedule to account for the difference in the + order of transformations applied when performing rounds. We also get + key rounds in reverse order (relative to encryption). */ + for(var round = 1; round < Nr; ++round) { + /* As described above, we'll be using table lookups to perform the + column mixing. Each column is stored as a word in the state (the + array 'input' has one column as a word at each index). In order to + mix a column, we perform these transformations on each row in c, + which is 1 byte in each word. The new column for c0 is c'0: + + m0 m1 m2 m3 + r0,c'0 = 2*r0,c0 + 3*r1,c0 + 1*r2,c0 + 1*r3,c0 + r1,c'0 = 1*r0,c0 + 2*r1,c0 + 3*r2,c0 + 1*r3,c0 + r2,c'0 = 1*r0,c0 + 1*r1,c0 + 2*r2,c0 + 3*r3,c0 + r3,c'0 = 3*r0,c0 + 1*r1,c0 + 1*r2,c0 + 2*r3,c0 + + So using mix tables where c0 is a word with r0 being its upper + 8 bits and r3 being its lower 8 bits: + + m0[c0 >> 24] will yield this word: [2*r0,1*r0,1*r0,3*r0] + ... + m3[c0 & 255] will yield this word: [1*r3,1*r3,3*r3,2*r3] + + Therefore to mix the columns in each word in the state we + do the following (& 255 omitted for brevity): + c'0,r0 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3] + c'0,r1 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3] + c'0,r2 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3] + c'0,r3 = m0[c0 >> 24] ^ m1[c1 >> 16] ^ m2[c2 >> 8] ^ m3[c3] + + However, before mixing, the algorithm requires us to perform + ShiftRows(). The ShiftRows() transformation cyclically shifts the + last 3 rows of the state over different offsets. The first row + (r = 0) is not shifted. + + s'_r,c = s_r,(c + shift(r, Nb) mod Nb + for 0 < r < 4 and 0 <= c < Nb and + shift(1, 4) = 1 + shift(2, 4) = 2 + shift(3, 4) = 3. + + This causes the first byte in r = 1 to be moved to the end of + the row, the first 2 bytes in r = 2 to be moved to the end of + the row, the first 3 bytes in r = 3 to be moved to the end of + the row: + + r1: [c0 c1 c2 c3] => [c1 c2 c3 c0] + r2: [c0 c1 c2 c3] [c2 c3 c0 c1] + r3: [c0 c1 c2 c3] [c3 c0 c1 c2] + + We can make these substitutions inline with our column mixing to + generate an updated set of equations to produce each word in the + state (note the columns have changed positions): + + c0 c1 c2 c3 => c0 c1 c2 c3 + c0 c1 c2 c3 c1 c2 c3 c0 (cycled 1 byte) + c0 c1 c2 c3 c2 c3 c0 c1 (cycled 2 bytes) + c0 c1 c2 c3 c3 c0 c1 c2 (cycled 3 bytes) + + Therefore: + + c'0 = 2*r0,c0 + 3*r1,c1 + 1*r2,c2 + 1*r3,c3 + c'0 = 1*r0,c0 + 2*r1,c1 + 3*r2,c2 + 1*r3,c3 + c'0 = 1*r0,c0 + 1*r1,c1 + 2*r2,c2 + 3*r3,c3 + c'0 = 3*r0,c0 + 1*r1,c1 + 1*r2,c2 + 2*r3,c3 + + c'1 = 2*r0,c1 + 3*r1,c2 + 1*r2,c3 + 1*r3,c0 + c'1 = 1*r0,c1 + 2*r1,c2 + 3*r2,c3 + 1*r3,c0 + c'1 = 1*r0,c1 + 1*r1,c2 + 2*r2,c3 + 3*r3,c0 + c'1 = 3*r0,c1 + 1*r1,c2 + 1*r2,c3 + 2*r3,c0 + + ... and so forth for c'2 and c'3. The important distinction is + that the columns are cycling, with c0 being used with the m0 + map when calculating c0, but c1 being used with the m0 map when + calculating c1 ... and so forth. + + When performing the inverse we transform the mirror image and + skip the bottom row, instead of the top one, and move upwards: + + c3 c2 c1 c0 => c0 c3 c2 c1 (cycled 3 bytes) *same as encryption + c3 c2 c1 c0 c1 c0 c3 c2 (cycled 2 bytes) + c3 c2 c1 c0 c2 c1 c0 c3 (cycled 1 byte) *same as encryption + c3 c2 c1 c0 c3 c2 c1 c0 + + If you compare the resulting matrices for ShiftRows()+MixColumns() + and for InvShiftRows()+InvMixColumns() the 2nd and 4th columns are + different (in encrypt mode vs. decrypt mode). So in order to use + the same code to handle both encryption and decryption, we will + need to do some mapping. + + If in encryption mode we let a=c0, b=c1, c=c2, d=c3, and r be + a row number in the state, then the resulting matrix in encryption + mode for applying the above transformations would be: + + r1: a b c d + r2: b c d a + r3: c d a b + r4: d a b c + + If we did the same in decryption mode we would get: + + r1: a d c b + r2: b a d c + r3: c b a d + r4: d c b a + + If instead we swap d and b (set b=c3 and d=c1), then we get: + + r1: a b c d + r2: d a b c + r3: c d a b + r4: b c d a + + Now the 1st and 3rd rows are the same as the encryption matrix. All + we need to do then to make the mapping exactly the same is to swap + the 2nd and 4th rows when in decryption mode. To do this without + having to do it on each iteration, we swapped the 2nd and 4th rows + in the decryption key schedule. We also have to do the swap above + when we first pull in the input and when we set the final output. */ + a2 = + m0[a >>> 24] ^ + m1[b >>> 16 & 255] ^ + m2[c >>> 8 & 255] ^ + m3[d & 255] ^ w[++i]; + b2 = + m0[b >>> 24] ^ + m1[c >>> 16 & 255] ^ + m2[d >>> 8 & 255] ^ + m3[a & 255] ^ w[++i]; + c2 = + m0[c >>> 24] ^ + m1[d >>> 16 & 255] ^ + m2[a >>> 8 & 255] ^ + m3[b & 255] ^ w[++i]; + d = + m0[d >>> 24] ^ + m1[a >>> 16 & 255] ^ + m2[b >>> 8 & 255] ^ + m3[c & 255] ^ w[++i]; + a = a2; + b = b2; + c = c2; + } + + /* + Encrypt: + SubBytes(state) + ShiftRows(state) + AddRoundKey(state, w[Nr*Nb, (Nr+1)*Nb-1]) + + Decrypt: + InvShiftRows(state) + InvSubBytes(state) + AddRoundKey(state, w[0, Nb-1]) + */ + // Note: rows are shifted inline + output[0] = + (sub[a >>> 24] << 24) ^ + (sub[b >>> 16 & 255] << 16) ^ + (sub[c >>> 8 & 255] << 8) ^ + (sub[d & 255]) ^ w[++i]; + output[decrypt ? 3 : 1] = + (sub[b >>> 24] << 24) ^ + (sub[c >>> 16 & 255] << 16) ^ + (sub[d >>> 8 & 255] << 8) ^ + (sub[a & 255]) ^ w[++i]; + output[2] = + (sub[c >>> 24] << 24) ^ + (sub[d >>> 16 & 255] << 16) ^ + (sub[a >>> 8 & 255] << 8) ^ + (sub[b & 255]) ^ w[++i]; + output[decrypt ? 1 : 3] = + (sub[d >>> 24] << 24) ^ + (sub[a >>> 16 & 255] << 16) ^ + (sub[b >>> 8 & 255] << 8) ^ + (sub[c & 255]) ^ w[++i]; +} + +/** + * Deprecated. Instead, use: + * + * forge.cipher.createCipher('AES-', key); + * forge.cipher.createDecipher('AES-', key); + * + * Creates a deprecated AES cipher object. This object's mode will default to + * CBC (cipher-block-chaining). + * + * The key and iv may be given as a string of bytes, an array of bytes, a + * byte buffer, or an array of 32-bit words. + * + * @param options the options to use. + * key the symmetric key to use. + * output the buffer to write to. + * decrypt true for decryption, false for encryption. + * mode the cipher mode to use (default: 'CBC'). + * + * @return the cipher. + */ +function _createCipher(options) { + options = options || {}; + var mode = (options.mode || 'CBC').toUpperCase(); + var algorithm = 'AES-' + mode; + + var cipher; + if(options.decrypt) { + cipher = forge.cipher.createDecipher(algorithm, options.key); + } else { + cipher = forge.cipher.createCipher(algorithm, options.key); + } + + // backwards compatible start API + var start = cipher.start; + cipher.start = function(iv, options) { + // backwards compatibility: support second arg as output buffer + var output = null; + if(options instanceof forge.util.ByteBuffer) { + output = options; + options = {}; + } + options = options || {}; + options.output = output; + options.iv = iv; + start.call(cipher, options); + }; + + return cipher; +} diff --git a/node_modules/node-forge/lib/aesCipherSuites.js b/node_modules/node-forge/lib/aesCipherSuites.js new file mode 100644 index 0000000..fed60f3 --- /dev/null +++ b/node_modules/node-forge/lib/aesCipherSuites.js @@ -0,0 +1,282 @@ +/** + * A Javascript implementation of AES Cipher Suites for TLS. + * + * @author Dave Longley + * + * Copyright (c) 2009-2015 Digital Bazaar, Inc. + * + */ +var forge = require('./forge'); +require('./aes'); +require('./tls'); + +var tls = module.exports = forge.tls; + +/** + * Supported cipher suites. + */ +tls.CipherSuites['TLS_RSA_WITH_AES_128_CBC_SHA'] = { + id: [0x00, 0x2f], + name: 'TLS_RSA_WITH_AES_128_CBC_SHA', + initSecurityParameters: function(sp) { + sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes; + sp.cipher_type = tls.CipherType.block; + sp.enc_key_length = 16; + sp.block_length = 16; + sp.fixed_iv_length = 16; + sp.record_iv_length = 16; + sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1; + sp.mac_length = 20; + sp.mac_key_length = 20; + }, + initConnectionState: initConnectionState +}; +tls.CipherSuites['TLS_RSA_WITH_AES_256_CBC_SHA'] = { + id: [0x00, 0x35], + name: 'TLS_RSA_WITH_AES_256_CBC_SHA', + initSecurityParameters: function(sp) { + sp.bulk_cipher_algorithm = tls.BulkCipherAlgorithm.aes; + sp.cipher_type = tls.CipherType.block; + sp.enc_key_length = 32; + sp.block_length = 16; + sp.fixed_iv_length = 16; + sp.record_iv_length = 16; + sp.mac_algorithm = tls.MACAlgorithm.hmac_sha1; + sp.mac_length = 20; + sp.mac_key_length = 20; + }, + initConnectionState: initConnectionState +}; + +function initConnectionState(state, c, sp) { + var client = (c.entity === forge.tls.ConnectionEnd.client); + + // cipher setup + state.read.cipherState = { + init: false, + cipher: forge.cipher.createDecipher('AES-CBC', client ? + sp.keys.server_write_key : sp.keys.client_write_key), + iv: client ? sp.keys.server_write_IV : sp.keys.client_write_IV + }; + state.write.cipherState = { + init: false, + cipher: forge.cipher.createCipher('AES-CBC', client ? + sp.keys.client_write_key : sp.keys.server_write_key), + iv: client ? sp.keys.client_write_IV : sp.keys.server_write_IV + }; + state.read.cipherFunction = decrypt_aes_cbc_sha1; + state.write.cipherFunction = encrypt_aes_cbc_sha1; + + // MAC setup + state.read.macLength = state.write.macLength = sp.mac_length; + state.read.macFunction = state.write.macFunction = tls.hmac_sha1; +} + +/** + * Encrypts the TLSCompressed record into a TLSCipherText record using AES + * in CBC mode. + * + * @param record the TLSCompressed record to encrypt. + * @param s the ConnectionState to use. + * + * @return true on success, false on failure. + */ +function encrypt_aes_cbc_sha1(record, s) { + var rval = false; + + // append MAC to fragment, update sequence number + var mac = s.macFunction(s.macKey, s.sequenceNumber, record); + record.fragment.putBytes(mac); + s.updateSequenceNumber(); + + // TLS 1.1+ use an explicit IV every time to protect against CBC attacks + var iv; + if(record.version.minor === tls.Versions.TLS_1_0.minor) { + // use the pre-generated IV when initializing for TLS 1.0, otherwise use + // the residue from the previous encryption + iv = s.cipherState.init ? null : s.cipherState.iv; + } else { + iv = forge.random.getBytesSync(16); + } + + s.cipherState.init = true; + + // start cipher + var cipher = s.cipherState.cipher; + cipher.start({iv: iv}); + + // TLS 1.1+ write IV into output + if(record.version.minor >= tls.Versions.TLS_1_1.minor) { + cipher.output.putBytes(iv); + } + + // do encryption (default padding is appropriate) + cipher.update(record.fragment); + if(cipher.finish(encrypt_aes_cbc_sha1_padding)) { + // set record fragment to encrypted output + record.fragment = cipher.output; + record.length = record.fragment.length(); + rval = true; + } + + return rval; +} + +/** + * Handles padding for aes_cbc_sha1 in encrypt mode. + * + * @param blockSize the block size. + * @param input the input buffer. + * @param decrypt true in decrypt mode, false in encrypt mode. + * + * @return true on success, false on failure. + */ +function encrypt_aes_cbc_sha1_padding(blockSize, input, decrypt) { + /* The encrypted data length (TLSCiphertext.length) is one more than the sum + of SecurityParameters.block_length, TLSCompressed.length, + SecurityParameters.mac_length, and padding_length. + + The padding may be any length up to 255 bytes long, as long as it results in + the TLSCiphertext.length being an integral multiple of the block length. + Lengths longer than necessary might be desirable to frustrate attacks on a + protocol based on analysis of the lengths of exchanged messages. Each uint8 + in the padding data vector must be filled with the padding length value. + + The padding length should be such that the total size of the + GenericBlockCipher structure is a multiple of the cipher's block length. + Legal values range from zero to 255, inclusive. This length specifies the + length of the padding field exclusive of the padding_length field itself. + + This is slightly different from PKCS#7 because the padding value is 1 + less than the actual number of padding bytes if you include the + padding_length uint8 itself as a padding byte. */ + if(!decrypt) { + // get the number of padding bytes required to reach the blockSize and + // subtract 1 for the padding value (to make room for the padding_length + // uint8) + var padding = blockSize - (input.length() % blockSize); + input.fillWithByte(padding - 1, padding); + } + return true; +} + +/** + * Handles padding for aes_cbc_sha1 in decrypt mode. + * + * @param blockSize the block size. + * @param output the output buffer. + * @param decrypt true in decrypt mode, false in encrypt mode. + * + * @return true on success, false on failure. + */ +function decrypt_aes_cbc_sha1_padding(blockSize, output, decrypt) { + var rval = true; + if(decrypt) { + /* The last byte in the output specifies the number of padding bytes not + including itself. Each of the padding bytes has the same value as that + last byte (known as the padding_length). Here we check all padding + bytes to ensure they have the value of padding_length even if one of + them is bad in order to ward-off timing attacks. */ + var len = output.length(); + var paddingLength = output.last(); + for(var i = len - 1 - paddingLength; i < len - 1; ++i) { + rval = rval && (output.at(i) == paddingLength); + } + if(rval) { + // trim off padding bytes and last padding length byte + output.truncate(paddingLength + 1); + } + } + return rval; +} + +/** + * Decrypts a TLSCipherText record into a TLSCompressed record using + * AES in CBC mode. + * + * @param record the TLSCipherText record to decrypt. + * @param s the ConnectionState to use. + * + * @return true on success, false on failure. + */ +function decrypt_aes_cbc_sha1(record, s) { + var rval = false; + + var iv; + if(record.version.minor === tls.Versions.TLS_1_0.minor) { + // use pre-generated IV when initializing for TLS 1.0, otherwise use the + // residue from the previous decryption + iv = s.cipherState.init ? null : s.cipherState.iv; + } else { + // TLS 1.1+ use an explicit IV every time to protect against CBC attacks + // that is appended to the record fragment + iv = record.fragment.getBytes(16); + } + + s.cipherState.init = true; + + // start cipher + var cipher = s.cipherState.cipher; + cipher.start({iv: iv}); + + // do decryption + cipher.update(record.fragment); + rval = cipher.finish(decrypt_aes_cbc_sha1_padding); + + // even if decryption fails, keep going to minimize timing attacks + + // decrypted data: + // first (len - 20) bytes = application data + // last 20 bytes = MAC + var macLen = s.macLength; + + // create a random MAC to check against should the mac length check fail + // Note: do this regardless of the failure to keep timing consistent + var mac = forge.random.getBytesSync(macLen); + + // get fragment and mac + var len = cipher.output.length(); + if(len >= macLen) { + record.fragment = cipher.output.getBytes(len - macLen); + mac = cipher.output.getBytes(macLen); + } else { + // bad data, but get bytes anyway to try to keep timing consistent + record.fragment = cipher.output.getBytes(); + } + record.fragment = forge.util.createBuffer(record.fragment); + record.length = record.fragment.length(); + + // see if data integrity checks out, update sequence number + var mac2 = s.macFunction(s.macKey, s.sequenceNumber, record); + s.updateSequenceNumber(); + rval = compareMacs(s.macKey, mac, mac2) && rval; + return rval; +} + +/** + * Safely compare two MACs. This function will compare two MACs in a way + * that protects against timing attacks. + * + * TODO: Expose elsewhere as a utility API. + * + * See: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2011/february/double-hmac-verification/ + * + * @param key the MAC key to use. + * @param mac1 as a binary-encoded string of bytes. + * @param mac2 as a binary-encoded string of bytes. + * + * @return true if the MACs are the same, false if not. + */ +function compareMacs(key, mac1, mac2) { + var hmac = forge.hmac.create(); + + hmac.start('SHA1', key); + hmac.update(mac1); + mac1 = hmac.digest().getBytes(); + + hmac.start(null, null); + hmac.update(mac2); + mac2 = hmac.digest().getBytes(); + + return mac1 === mac2; +} diff --git a/node_modules/node-forge/lib/asn1-validator.js b/node_modules/node-forge/lib/asn1-validator.js new file mode 100644 index 0000000..2be3285 --- /dev/null +++ b/node_modules/node-forge/lib/asn1-validator.js @@ -0,0 +1,91 @@ +/** + * Copyright (c) 2019 Digital Bazaar, Inc. + */ + +var forge = require('./forge'); +require('./asn1'); +var asn1 = forge.asn1; + +exports.privateKeyValidator = { + // PrivateKeyInfo + name: 'PrivateKeyInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + // Version (INTEGER) + name: 'PrivateKeyInfo.version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyVersion' + }, { + // privateKeyAlgorithm + name: 'PrivateKeyInfo.privateKeyAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'AlgorithmIdentifier.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'privateKeyOid' + }] + }, { + // PrivateKey + name: 'PrivateKeyInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'privateKey' + }] +}; + +exports.publicKeyValidator = { + name: 'SubjectPublicKeyInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'subjectPublicKeyInfo', + value: [{ + name: 'SubjectPublicKeyInfo.AlgorithmIdentifier', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'AlgorithmIdentifier.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'publicKeyOid' + }] + }, + // capture group for ed25519PublicKey + { + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + composed: true, + captureBitStringValue: 'ed25519PublicKey' + } + // FIXME: this is capture group for rsaPublicKey, use it in this API or + // discard? + /* { + // subjectPublicKey + name: 'SubjectPublicKeyInfo.subjectPublicKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + value: [{ + // RSAPublicKey + name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + optional: true, + captureAsn1: 'rsaPublicKey' + }] + } */ + ] +}; diff --git a/node_modules/node-forge/lib/asn1.js b/node_modules/node-forge/lib/asn1.js new file mode 100644 index 0000000..e0fea0e --- /dev/null +++ b/node_modules/node-forge/lib/asn1.js @@ -0,0 +1,1408 @@ +/** + * Javascript implementation of Abstract Syntax Notation Number One. + * + * @author Dave Longley + * + * Copyright (c) 2010-2015 Digital Bazaar, Inc. + * + * An API for storing data using the Abstract Syntax Notation Number One + * format using DER (Distinguished Encoding Rules) encoding. This encoding is + * commonly used to store data for PKI, i.e. X.509 Certificates, and this + * implementation exists for that purpose. + * + * Abstract Syntax Notation Number One (ASN.1) is used to define the abstract + * syntax of information without restricting the way the information is encoded + * for transmission. It provides a standard that allows for open systems + * communication. ASN.1 defines the syntax of information data and a number of + * simple data types as well as a notation for describing them and specifying + * values for them. + * + * The RSA algorithm creates public and private keys that are often stored in + * X.509 or PKCS#X formats -- which use ASN.1 (encoded in DER format). This + * class provides the most basic functionality required to store and load DSA + * keys that are encoded according to ASN.1. + * + * The most common binary encodings for ASN.1 are BER (Basic Encoding Rules) + * and DER (Distinguished Encoding Rules). DER is just a subset of BER that + * has stricter requirements for how data must be encoded. + * + * Each ASN.1 structure has a tag (a byte identifying the ASN.1 structure type) + * and a byte array for the value of this ASN1 structure which may be data or a + * list of ASN.1 structures. + * + * Each ASN.1 structure using BER is (Tag-Length-Value): + * + * | byte 0 | bytes X | bytes Y | + * |--------|---------|---------- + * | tag | length | value | + * + * ASN.1 allows for tags to be of "High-tag-number form" which allows a tag to + * be two or more octets, but that is not supported by this class. A tag is + * only 1 byte. Bits 1-5 give the tag number (ie the data type within a + * particular 'class'), 6 indicates whether or not the ASN.1 value is + * constructed from other ASN.1 values, and bits 7 and 8 give the 'class'. If + * bits 7 and 8 are both zero, the class is UNIVERSAL. If only bit 7 is set, + * then the class is APPLICATION. If only bit 8 is set, then the class is + * CONTEXT_SPECIFIC. If both bits 7 and 8 are set, then the class is PRIVATE. + * The tag numbers for the data types for the class UNIVERSAL are listed below: + * + * UNIVERSAL 0 Reserved for use by the encoding rules + * UNIVERSAL 1 Boolean type + * UNIVERSAL 2 Integer type + * UNIVERSAL 3 Bitstring type + * UNIVERSAL 4 Octetstring type + * UNIVERSAL 5 Null type + * UNIVERSAL 6 Object identifier type + * UNIVERSAL 7 Object descriptor type + * UNIVERSAL 8 External type and Instance-of type + * UNIVERSAL 9 Real type + * UNIVERSAL 10 Enumerated type + * UNIVERSAL 11 Embedded-pdv type + * UNIVERSAL 12 UTF8String type + * UNIVERSAL 13 Relative object identifier type + * UNIVERSAL 14-15 Reserved for future editions + * UNIVERSAL 16 Sequence and Sequence-of types + * UNIVERSAL 17 Set and Set-of types + * UNIVERSAL 18-22, 25-30 Character string types + * UNIVERSAL 23-24 Time types + * + * The length of an ASN.1 structure is specified after the tag identifier. + * There is a definite form and an indefinite form. The indefinite form may + * be used if the encoding is constructed and not all immediately available. + * The indefinite form is encoded using a length byte with only the 8th bit + * set. The end of the constructed object is marked using end-of-contents + * octets (two zero bytes). + * + * The definite form looks like this: + * + * The length may take up 1 or more bytes, it depends on the length of the + * value of the ASN.1 structure. DER encoding requires that if the ASN.1 + * structure has a value that has a length greater than 127, more than 1 byte + * will be used to store its length, otherwise just one byte will be used. + * This is strict. + * + * In the case that the length of the ASN.1 value is less than 127, 1 octet + * (byte) is used to store the "short form" length. The 8th bit has a value of + * 0 indicating the length is "short form" and not "long form" and bits 7-1 + * give the length of the data. (The 8th bit is the left-most, most significant + * bit: also known as big endian or network format). + * + * In the case that the length of the ASN.1 value is greater than 127, 2 to + * 127 octets (bytes) are used to store the "long form" length. The first + * byte's 8th bit is set to 1 to indicate the length is "long form." Bits 7-1 + * give the number of additional octets. All following octets are in base 256 + * with the most significant digit first (typical big-endian binary unsigned + * integer storage). So, for instance, if the length of a value was 257, the + * first byte would be set to: + * + * 10000010 = 130 = 0x82. + * + * This indicates there are 2 octets (base 256) for the length. The second and + * third bytes (the octets just mentioned) would store the length in base 256: + * + * octet 2: 00000001 = 1 * 256^1 = 256 + * octet 3: 00000001 = 1 * 256^0 = 1 + * total = 257 + * + * The algorithm for converting a js integer value of 257 to base-256 is: + * + * var value = 257; + * var bytes = []; + * bytes[0] = (value >>> 8) & 0xFF; // most significant byte first + * bytes[1] = value & 0xFF; // least significant byte last + * + * On the ASN.1 UNIVERSAL Object Identifier (OID) type: + * + * An OID can be written like: "value1.value2.value3...valueN" + * + * The DER encoding rules: + * + * The first byte has the value 40 * value1 + value2. + * The following bytes, if any, encode the remaining values. Each value is + * encoded in base 128, most significant digit first (big endian), with as + * few digits as possible, and the most significant bit of each byte set + * to 1 except the last in each value's encoding. For example: Given the + * OID "1.2.840.113549", its DER encoding is (remember each byte except the + * last one in each encoding is OR'd with 0x80): + * + * byte 1: 40 * 1 + 2 = 42 = 0x2A. + * bytes 2-3: 128 * 6 + 72 = 840 = 6 72 = 6 72 = 0x0648 = 0x8648 + * bytes 4-6: 16384 * 6 + 128 * 119 + 13 = 6 119 13 = 0x06770D = 0x86F70D + * + * The final value is: 0x2A864886F70D. + * The full OID (including ASN.1 tag and length of 6 bytes) is: + * 0x06062A864886F70D + */ +var forge = require('./forge'); +require('./util'); +require('./oids'); + +/* ASN.1 API */ +var asn1 = module.exports = forge.asn1 = forge.asn1 || {}; + +/** + * ASN.1 classes. + */ +asn1.Class = { + UNIVERSAL: 0x00, + APPLICATION: 0x40, + CONTEXT_SPECIFIC: 0x80, + PRIVATE: 0xC0 +}; + +/** + * ASN.1 types. Not all types are supported by this implementation, only + * those necessary to implement a simple PKI are implemented. + */ +asn1.Type = { + NONE: 0, + BOOLEAN: 1, + INTEGER: 2, + BITSTRING: 3, + OCTETSTRING: 4, + NULL: 5, + OID: 6, + ODESC: 7, + EXTERNAL: 8, + REAL: 9, + ENUMERATED: 10, + EMBEDDED: 11, + UTF8: 12, + ROID: 13, + SEQUENCE: 16, + SET: 17, + PRINTABLESTRING: 19, + IA5STRING: 22, + UTCTIME: 23, + GENERALIZEDTIME: 24, + BMPSTRING: 30 +}; + +/** + * Creates a new asn1 object. + * + * @param tagClass the tag class for the object. + * @param type the data type (tag number) for the object. + * @param constructed true if the asn1 object is in constructed form. + * @param value the value for the object, if it is not constructed. + * @param [options] the options to use: + * [bitStringContents] the plain BIT STRING content including padding + * byte. + * + * @return the asn1 object. + */ +asn1.create = function(tagClass, type, constructed, value, options) { + /* An asn1 object has a tagClass, a type, a constructed flag, and a + value. The value's type depends on the constructed flag. If + constructed, it will contain a list of other asn1 objects. If not, + it will contain the ASN.1 value as an array of bytes formatted + according to the ASN.1 data type. */ + + // remove undefined values + if(forge.util.isArray(value)) { + var tmp = []; + for(var i = 0; i < value.length; ++i) { + if(value[i] !== undefined) { + tmp.push(value[i]); + } + } + value = tmp; + } + + var obj = { + tagClass: tagClass, + type: type, + constructed: constructed, + composed: constructed || forge.util.isArray(value), + value: value + }; + if(options && 'bitStringContents' in options) { + // TODO: copy byte buffer if it's a buffer not a string + obj.bitStringContents = options.bitStringContents; + // TODO: add readonly flag to avoid this overhead + // save copy to detect changes + obj.original = asn1.copy(obj); + } + return obj; +}; + +/** + * Copies an asn1 object. + * + * @param obj the asn1 object. + * @param [options] copy options: + * [excludeBitStringContents] true to not copy bitStringContents + * + * @return the a copy of the asn1 object. + */ +asn1.copy = function(obj, options) { + var copy; + + if(forge.util.isArray(obj)) { + copy = []; + for(var i = 0; i < obj.length; ++i) { + copy.push(asn1.copy(obj[i], options)); + } + return copy; + } + + if(typeof obj === 'string') { + // TODO: copy byte buffer if it's a buffer not a string + return obj; + } + + copy = { + tagClass: obj.tagClass, + type: obj.type, + constructed: obj.constructed, + composed: obj.composed, + value: asn1.copy(obj.value, options) + }; + if(options && !options.excludeBitStringContents) { + // TODO: copy byte buffer if it's a buffer not a string + copy.bitStringContents = obj.bitStringContents; + } + return copy; +}; + +/** + * Compares asn1 objects for equality. + * + * Note this function does not run in constant time. + * + * @param obj1 the first asn1 object. + * @param obj2 the second asn1 object. + * @param [options] compare options: + * [includeBitStringContents] true to compare bitStringContents + * + * @return true if the asn1 objects are equal. + */ +asn1.equals = function(obj1, obj2, options) { + if(forge.util.isArray(obj1)) { + if(!forge.util.isArray(obj2)) { + return false; + } + if(obj1.length !== obj2.length) { + return false; + } + for(var i = 0; i < obj1.length; ++i) { + if(!asn1.equals(obj1[i], obj2[i])) { + return false; + } + } + return true; + } + + if(typeof obj1 !== typeof obj2) { + return false; + } + + if(typeof obj1 === 'string') { + return obj1 === obj2; + } + + var equal = obj1.tagClass === obj2.tagClass && + obj1.type === obj2.type && + obj1.constructed === obj2.constructed && + obj1.composed === obj2.composed && + asn1.equals(obj1.value, obj2.value); + if(options && options.includeBitStringContents) { + equal = equal && (obj1.bitStringContents === obj2.bitStringContents); + } + + return equal; +}; + +/** + * Gets the length of a BER-encoded ASN.1 value. + * + * In case the length is not specified, undefined is returned. + * + * @param b the BER-encoded ASN.1 byte buffer, starting with the first + * length byte. + * + * @return the length of the BER-encoded ASN.1 value or undefined. + */ +asn1.getBerValueLength = function(b) { + // TODO: move this function and related DER/BER functions to a der.js + // file; better abstract ASN.1 away from der/ber. + var b2 = b.getByte(); + if(b2 === 0x80) { + return undefined; + } + + // see if the length is "short form" or "long form" (bit 8 set) + var length; + var longForm = b2 & 0x80; + if(!longForm) { + // length is just the first byte + length = b2; + } else { + // the number of bytes the length is specified in bits 7 through 1 + // and each length byte is in big-endian base-256 + length = b.getInt((b2 & 0x7F) << 3); + } + return length; +}; + +/** + * Check if the byte buffer has enough bytes. Throws an Error if not. + * + * @param bytes the byte buffer to parse from. + * @param remaining the bytes remaining in the current parsing state. + * @param n the number of bytes the buffer must have. + */ +function _checkBufferLength(bytes, remaining, n) { + if(n > remaining) { + var error = new Error('Too few bytes to parse DER.'); + error.available = bytes.length(); + error.remaining = remaining; + error.requested = n; + throw error; + } +} + +/** + * Gets the length of a BER-encoded ASN.1 value. + * + * In case the length is not specified, undefined is returned. + * + * @param bytes the byte buffer to parse from. + * @param remaining the bytes remaining in the current parsing state. + * + * @return the length of the BER-encoded ASN.1 value or undefined. + */ +var _getValueLength = function(bytes, remaining) { + // TODO: move this function and related DER/BER functions to a der.js + // file; better abstract ASN.1 away from der/ber. + // fromDer already checked that this byte exists + var b2 = bytes.getByte(); + remaining--; + if(b2 === 0x80) { + return undefined; + } + + // see if the length is "short form" or "long form" (bit 8 set) + var length; + var longForm = b2 & 0x80; + if(!longForm) { + // length is just the first byte + length = b2; + } else { + // the number of bytes the length is specified in bits 7 through 1 + // and each length byte is in big-endian base-256 + var longFormBytes = b2 & 0x7F; + _checkBufferLength(bytes, remaining, longFormBytes); + length = bytes.getInt(longFormBytes << 3); + } + // FIXME: this will only happen for 32 bit getInt with high bit set + if(length < 0) { + throw new Error('Negative length: ' + length); + } + return length; +}; + +/** + * Parses an asn1 object from a byte buffer in DER format. + * + * @param bytes the byte buffer to parse from. + * @param [strict] true to be strict when checking value lengths, false to + * allow truncated values (default: true). + * @param [options] object with options or boolean strict flag + * [strict] true to be strict when checking value lengths, false to + * allow truncated values (default: true). + * [decodeBitStrings] true to attempt to decode the content of + * BIT STRINGs (not OCTET STRINGs) using strict mode. Note that + * without schema support to understand the data context this can + * erroneously decode values that happen to be valid ASN.1. This + * flag will be deprecated or removed as soon as schema support is + * available. (default: true) + * + * @return the parsed asn1 object. + */ +asn1.fromDer = function(bytes, options) { + if(options === undefined) { + options = { + strict: true, + decodeBitStrings: true + }; + } + if(typeof options === 'boolean') { + options = { + strict: options, + decodeBitStrings: true + }; + } + if(!('strict' in options)) { + options.strict = true; + } + if(!('decodeBitStrings' in options)) { + options.decodeBitStrings = true; + } + + // wrap in buffer if needed + if(typeof bytes === 'string') { + bytes = forge.util.createBuffer(bytes); + } + + return _fromDer(bytes, bytes.length(), 0, options); +}; + +/** + * Internal function to parse an asn1 object from a byte buffer in DER format. + * + * @param bytes the byte buffer to parse from. + * @param remaining the number of bytes remaining for this chunk. + * @param depth the current parsing depth. + * @param options object with same options as fromDer(). + * + * @return the parsed asn1 object. + */ +function _fromDer(bytes, remaining, depth, options) { + // temporary storage for consumption calculations + var start; + + // minimum length for ASN.1 DER structure is 2 + _checkBufferLength(bytes, remaining, 2); + + // get the first byte + var b1 = bytes.getByte(); + // consumed one byte + remaining--; + + // get the tag class + var tagClass = (b1 & 0xC0); + + // get the type (bits 1-5) + var type = b1 & 0x1F; + + // get the variable value length and adjust remaining bytes + start = bytes.length(); + var length = _getValueLength(bytes, remaining); + remaining -= start - bytes.length(); + + // ensure there are enough bytes to get the value + if(length !== undefined && length > remaining) { + if(options.strict) { + var error = new Error('Too few bytes to read ASN.1 value.'); + error.available = bytes.length(); + error.remaining = remaining; + error.requested = length; + throw error; + } + // Note: be lenient with truncated values and use remaining state bytes + length = remaining; + } + + // value storage + var value; + // possible BIT STRING contents storage + var bitStringContents; + + // constructed flag is bit 6 (32 = 0x20) of the first byte + var constructed = ((b1 & 0x20) === 0x20); + if(constructed) { + // parse child asn1 objects from the value + value = []; + if(length === undefined) { + // asn1 object of indefinite length, read until end tag + for(;;) { + _checkBufferLength(bytes, remaining, 2); + if(bytes.bytes(2) === String.fromCharCode(0, 0)) { + bytes.getBytes(2); + remaining -= 2; + break; + } + start = bytes.length(); + value.push(_fromDer(bytes, remaining, depth + 1, options)); + remaining -= start - bytes.length(); + } + } else { + // parsing asn1 object of definite length + while(length > 0) { + start = bytes.length(); + value.push(_fromDer(bytes, length, depth + 1, options)); + remaining -= start - bytes.length(); + length -= start - bytes.length(); + } + } + } + + // if a BIT STRING, save the contents including padding + if(value === undefined && tagClass === asn1.Class.UNIVERSAL && + type === asn1.Type.BITSTRING) { + bitStringContents = bytes.bytes(length); + } + + // determine if a non-constructed value should be decoded as a composed + // value that contains other ASN.1 objects. BIT STRINGs (and OCTET STRINGs) + // can be used this way. + if(value === undefined && options.decodeBitStrings && + tagClass === asn1.Class.UNIVERSAL && + // FIXME: OCTET STRINGs not yet supported here + // .. other parts of forge expect to decode OCTET STRINGs manually + (type === asn1.Type.BITSTRING /*|| type === asn1.Type.OCTETSTRING*/) && + length > 1) { + // save read position + var savedRead = bytes.read; + var savedRemaining = remaining; + var unused = 0; + if(type === asn1.Type.BITSTRING) { + /* The first octet gives the number of bits by which the length of the + bit string is less than the next multiple of eight (this is called + the "number of unused bits"). + + The second and following octets give the value of the bit string + converted to an octet string. */ + _checkBufferLength(bytes, remaining, 1); + unused = bytes.getByte(); + remaining--; + } + // if all bits are used, maybe the BIT/OCTET STRING holds ASN.1 objs + if(unused === 0) { + try { + // attempt to parse child asn1 object from the value + // (stored in array to signal composed value) + start = bytes.length(); + var subOptions = { + // enforce strict mode to avoid parsing ASN.1 from plain data + verbose: options.verbose, + strict: true, + decodeBitStrings: true + }; + var composed = _fromDer(bytes, remaining, depth + 1, subOptions); + var used = start - bytes.length(); + remaining -= used; + if(type == asn1.Type.BITSTRING) { + used++; + } + + // if the data all decoded and the class indicates UNIVERSAL or + // CONTEXT_SPECIFIC then assume we've got an encapsulated ASN.1 object + var tc = composed.tagClass; + if(used === length && + (tc === asn1.Class.UNIVERSAL || tc === asn1.Class.CONTEXT_SPECIFIC)) { + value = [composed]; + } + } catch(ex) { + } + } + if(value === undefined) { + // restore read position + bytes.read = savedRead; + remaining = savedRemaining; + } + } + + if(value === undefined) { + // asn1 not constructed or composed, get raw value + // TODO: do DER to OID conversion and vice-versa in .toDer? + + if(length === undefined) { + if(options.strict) { + throw new Error('Non-constructed ASN.1 object of indefinite length.'); + } + // be lenient and use remaining state bytes + length = remaining; + } + + if(type === asn1.Type.BMPSTRING) { + value = ''; + for(; length > 0; length -= 2) { + _checkBufferLength(bytes, remaining, 2); + value += String.fromCharCode(bytes.getInt16()); + remaining -= 2; + } + } else { + value = bytes.getBytes(length); + } + } + + // add BIT STRING contents if available + var asn1Options = bitStringContents === undefined ? null : { + bitStringContents: bitStringContents + }; + + // create and return asn1 object + return asn1.create(tagClass, type, constructed, value, asn1Options); +} + +/** + * Converts the given asn1 object to a buffer of bytes in DER format. + * + * @param asn1 the asn1 object to convert to bytes. + * + * @return the buffer of bytes. + */ +asn1.toDer = function(obj) { + var bytes = forge.util.createBuffer(); + + // build the first byte + var b1 = obj.tagClass | obj.type; + + // for storing the ASN.1 value + var value = forge.util.createBuffer(); + + // use BIT STRING contents if available and data not changed + var useBitStringContents = false; + if('bitStringContents' in obj) { + useBitStringContents = true; + if(obj.original) { + useBitStringContents = asn1.equals(obj, obj.original); + } + } + + if(useBitStringContents) { + value.putBytes(obj.bitStringContents); + } else if(obj.composed) { + // if composed, use each child asn1 object's DER bytes as value + // turn on 6th bit (0x20 = 32) to indicate asn1 is constructed + // from other asn1 objects + if(obj.constructed) { + b1 |= 0x20; + } else { + // type is a bit string, add unused bits of 0x00 + value.putByte(0x00); + } + + // add all of the child DER bytes together + for(var i = 0; i < obj.value.length; ++i) { + if(obj.value[i] !== undefined) { + value.putBuffer(asn1.toDer(obj.value[i])); + } + } + } else { + // use asn1.value directly + if(obj.type === asn1.Type.BMPSTRING) { + for(var i = 0; i < obj.value.length; ++i) { + value.putInt16(obj.value.charCodeAt(i)); + } + } else { + // ensure integer is minimally-encoded + // TODO: should all leading bytes be stripped vs just one? + // .. ex '00 00 01' => '01'? + if(obj.type === asn1.Type.INTEGER && + obj.value.length > 1 && + // leading 0x00 for positive integer + ((obj.value.charCodeAt(0) === 0 && + (obj.value.charCodeAt(1) & 0x80) === 0) || + // leading 0xFF for negative integer + (obj.value.charCodeAt(0) === 0xFF && + (obj.value.charCodeAt(1) & 0x80) === 0x80))) { + value.putBytes(obj.value.substr(1)); + } else { + value.putBytes(obj.value); + } + } + } + + // add tag byte + bytes.putByte(b1); + + // use "short form" encoding + if(value.length() <= 127) { + // one byte describes the length + // bit 8 = 0 and bits 7-1 = length + bytes.putByte(value.length() & 0x7F); + } else { + // use "long form" encoding + // 2 to 127 bytes describe the length + // first byte: bit 8 = 1 and bits 7-1 = # of additional bytes + // other bytes: length in base 256, big-endian + var len = value.length(); + var lenBytes = ''; + do { + lenBytes += String.fromCharCode(len & 0xFF); + len = len >>> 8; + } while(len > 0); + + // set first byte to # bytes used to store the length and turn on + // bit 8 to indicate long-form length is used + bytes.putByte(lenBytes.length | 0x80); + + // concatenate length bytes in reverse since they were generated + // little endian and we need big endian + for(var i = lenBytes.length - 1; i >= 0; --i) { + bytes.putByte(lenBytes.charCodeAt(i)); + } + } + + // concatenate value bytes + bytes.putBuffer(value); + return bytes; +}; + +/** + * Converts an OID dot-separated string to a byte buffer. The byte buffer + * contains only the DER-encoded value, not any tag or length bytes. + * + * @param oid the OID dot-separated string. + * + * @return the byte buffer. + */ +asn1.oidToDer = function(oid) { + // split OID into individual values + var values = oid.split('.'); + var bytes = forge.util.createBuffer(); + + // first byte is 40 * value1 + value2 + bytes.putByte(40 * parseInt(values[0], 10) + parseInt(values[1], 10)); + // other bytes are each value in base 128 with 8th bit set except for + // the last byte for each value + var last, valueBytes, value, b; + for(var i = 2; i < values.length; ++i) { + // produce value bytes in reverse because we don't know how many + // bytes it will take to store the value + last = true; + valueBytes = []; + value = parseInt(values[i], 10); + do { + b = value & 0x7F; + value = value >>> 7; + // if value is not last, then turn on 8th bit + if(!last) { + b |= 0x80; + } + valueBytes.push(b); + last = false; + } while(value > 0); + + // add value bytes in reverse (needs to be in big endian) + for(var n = valueBytes.length - 1; n >= 0; --n) { + bytes.putByte(valueBytes[n]); + } + } + + return bytes; +}; + +/** + * Converts a DER-encoded byte buffer to an OID dot-separated string. The + * byte buffer should contain only the DER-encoded value, not any tag or + * length bytes. + * + * @param bytes the byte buffer. + * + * @return the OID dot-separated string. + */ +asn1.derToOid = function(bytes) { + var oid; + + // wrap in buffer if needed + if(typeof bytes === 'string') { + bytes = forge.util.createBuffer(bytes); + } + + // first byte is 40 * value1 + value2 + var b = bytes.getByte(); + oid = Math.floor(b / 40) + '.' + (b % 40); + + // other bytes are each value in base 128 with 8th bit set except for + // the last byte for each value + var value = 0; + while(bytes.length() > 0) { + b = bytes.getByte(); + value = value << 7; + // not the last byte for the value + if(b & 0x80) { + value += b & 0x7F; + } else { + // last byte + oid += '.' + (value + b); + value = 0; + } + } + + return oid; +}; + +/** + * Converts a UTCTime value to a date. + * + * Note: GeneralizedTime has 4 digits for the year and is used for X.509 + * dates past 2049. Parsing that structure hasn't been implemented yet. + * + * @param utc the UTCTime value to convert. + * + * @return the date. + */ +asn1.utcTimeToDate = function(utc) { + /* The following formats can be used: + + YYMMDDhhmmZ + YYMMDDhhmm+hh'mm' + YYMMDDhhmm-hh'mm' + YYMMDDhhmmssZ + YYMMDDhhmmss+hh'mm' + YYMMDDhhmmss-hh'mm' + + Where: + + YY is the least significant two digits of the year + MM is the month (01 to 12) + DD is the day (01 to 31) + hh is the hour (00 to 23) + mm are the minutes (00 to 59) + ss are the seconds (00 to 59) + Z indicates that local time is GMT, + indicates that local time is + later than GMT, and - indicates that local time is earlier than GMT + hh' is the absolute value of the offset from GMT in hours + mm' is the absolute value of the offset from GMT in minutes */ + var date = new Date(); + + // if YY >= 50 use 19xx, if YY < 50 use 20xx + var year = parseInt(utc.substr(0, 2), 10); + year = (year >= 50) ? 1900 + year : 2000 + year; + var MM = parseInt(utc.substr(2, 2), 10) - 1; // use 0-11 for month + var DD = parseInt(utc.substr(4, 2), 10); + var hh = parseInt(utc.substr(6, 2), 10); + var mm = parseInt(utc.substr(8, 2), 10); + var ss = 0; + + // not just YYMMDDhhmmZ + if(utc.length > 11) { + // get character after minutes + var c = utc.charAt(10); + var end = 10; + + // see if seconds are present + if(c !== '+' && c !== '-') { + // get seconds + ss = parseInt(utc.substr(10, 2), 10); + end += 2; + } + } + + // update date + date.setUTCFullYear(year, MM, DD); + date.setUTCHours(hh, mm, ss, 0); + + if(end) { + // get +/- after end of time + c = utc.charAt(end); + if(c === '+' || c === '-') { + // get hours+minutes offset + var hhoffset = parseInt(utc.substr(end + 1, 2), 10); + var mmoffset = parseInt(utc.substr(end + 4, 2), 10); + + // calculate offset in milliseconds + var offset = hhoffset * 60 + mmoffset; + offset *= 60000; + + // apply offset + if(c === '+') { + date.setTime(+date - offset); + } else { + date.setTime(+date + offset); + } + } + } + + return date; +}; + +/** + * Converts a GeneralizedTime value to a date. + * + * @param gentime the GeneralizedTime value to convert. + * + * @return the date. + */ +asn1.generalizedTimeToDate = function(gentime) { + /* The following formats can be used: + + YYYYMMDDHHMMSS + YYYYMMDDHHMMSS.fff + YYYYMMDDHHMMSSZ + YYYYMMDDHHMMSS.fffZ + YYYYMMDDHHMMSS+hh'mm' + YYYYMMDDHHMMSS.fff+hh'mm' + YYYYMMDDHHMMSS-hh'mm' + YYYYMMDDHHMMSS.fff-hh'mm' + + Where: + + YYYY is the year + MM is the month (01 to 12) + DD is the day (01 to 31) + hh is the hour (00 to 23) + mm are the minutes (00 to 59) + ss are the seconds (00 to 59) + .fff is the second fraction, accurate to three decimal places + Z indicates that local time is GMT, + indicates that local time is + later than GMT, and - indicates that local time is earlier than GMT + hh' is the absolute value of the offset from GMT in hours + mm' is the absolute value of the offset from GMT in minutes */ + var date = new Date(); + + var YYYY = parseInt(gentime.substr(0, 4), 10); + var MM = parseInt(gentime.substr(4, 2), 10) - 1; // use 0-11 for month + var DD = parseInt(gentime.substr(6, 2), 10); + var hh = parseInt(gentime.substr(8, 2), 10); + var mm = parseInt(gentime.substr(10, 2), 10); + var ss = parseInt(gentime.substr(12, 2), 10); + var fff = 0; + var offset = 0; + var isUTC = false; + + if(gentime.charAt(gentime.length - 1) === 'Z') { + isUTC = true; + } + + var end = gentime.length - 5, c = gentime.charAt(end); + if(c === '+' || c === '-') { + // get hours+minutes offset + var hhoffset = parseInt(gentime.substr(end + 1, 2), 10); + var mmoffset = parseInt(gentime.substr(end + 4, 2), 10); + + // calculate offset in milliseconds + offset = hhoffset * 60 + mmoffset; + offset *= 60000; + + // apply offset + if(c === '+') { + offset *= -1; + } + + isUTC = true; + } + + // check for second fraction + if(gentime.charAt(14) === '.') { + fff = parseFloat(gentime.substr(14), 10) * 1000; + } + + if(isUTC) { + date.setUTCFullYear(YYYY, MM, DD); + date.setUTCHours(hh, mm, ss, fff); + + // apply offset + date.setTime(+date + offset); + } else { + date.setFullYear(YYYY, MM, DD); + date.setHours(hh, mm, ss, fff); + } + + return date; +}; + +/** + * Converts a date to a UTCTime value. + * + * Note: GeneralizedTime has 4 digits for the year and is used for X.509 + * dates past 2049. Converting to a GeneralizedTime hasn't been + * implemented yet. + * + * @param date the date to convert. + * + * @return the UTCTime value. + */ +asn1.dateToUtcTime = function(date) { + // TODO: validate; currently assumes proper format + if(typeof date === 'string') { + return date; + } + + var rval = ''; + + // create format YYMMDDhhmmssZ + var format = []; + format.push(('' + date.getUTCFullYear()).substr(2)); + format.push('' + (date.getUTCMonth() + 1)); + format.push('' + date.getUTCDate()); + format.push('' + date.getUTCHours()); + format.push('' + date.getUTCMinutes()); + format.push('' + date.getUTCSeconds()); + + // ensure 2 digits are used for each format entry + for(var i = 0; i < format.length; ++i) { + if(format[i].length < 2) { + rval += '0'; + } + rval += format[i]; + } + rval += 'Z'; + + return rval; +}; + +/** + * Converts a date to a GeneralizedTime value. + * + * @param date the date to convert. + * + * @return the GeneralizedTime value as a string. + */ +asn1.dateToGeneralizedTime = function(date) { + // TODO: validate; currently assumes proper format + if(typeof date === 'string') { + return date; + } + + var rval = ''; + + // create format YYYYMMDDHHMMSSZ + var format = []; + format.push('' + date.getUTCFullYear()); + format.push('' + (date.getUTCMonth() + 1)); + format.push('' + date.getUTCDate()); + format.push('' + date.getUTCHours()); + format.push('' + date.getUTCMinutes()); + format.push('' + date.getUTCSeconds()); + + // ensure 2 digits are used for each format entry + for(var i = 0; i < format.length; ++i) { + if(format[i].length < 2) { + rval += '0'; + } + rval += format[i]; + } + rval += 'Z'; + + return rval; +}; + +/** + * Converts a javascript integer to a DER-encoded byte buffer to be used + * as the value for an INTEGER type. + * + * @param x the integer. + * + * @return the byte buffer. + */ +asn1.integerToDer = function(x) { + var rval = forge.util.createBuffer(); + if(x >= -0x80 && x < 0x80) { + return rval.putSignedInt(x, 8); + } + if(x >= -0x8000 && x < 0x8000) { + return rval.putSignedInt(x, 16); + } + if(x >= -0x800000 && x < 0x800000) { + return rval.putSignedInt(x, 24); + } + if(x >= -0x80000000 && x < 0x80000000) { + return rval.putSignedInt(x, 32); + } + var error = new Error('Integer too large; max is 32-bits.'); + error.integer = x; + throw error; +}; + +/** + * Converts a DER-encoded byte buffer to a javascript integer. This is + * typically used to decode the value of an INTEGER type. + * + * @param bytes the byte buffer. + * + * @return the integer. + */ +asn1.derToInteger = function(bytes) { + // wrap in buffer if needed + if(typeof bytes === 'string') { + bytes = forge.util.createBuffer(bytes); + } + + var n = bytes.length() * 8; + if(n > 32) { + throw new Error('Integer too large; max is 32-bits.'); + } + return bytes.getSignedInt(n); +}; + +/** + * Validates that the given ASN.1 object is at least a super set of the + * given ASN.1 structure. Only tag classes and types are checked. An + * optional map may also be provided to capture ASN.1 values while the + * structure is checked. + * + * To capture an ASN.1 value, set an object in the validator's 'capture' + * parameter to the key to use in the capture map. To capture the full + * ASN.1 object, specify 'captureAsn1'. To capture BIT STRING bytes, including + * the leading unused bits counter byte, specify 'captureBitStringContents'. + * To capture BIT STRING bytes, without the leading unused bits counter byte, + * specify 'captureBitStringValue'. + * + * Objects in the validator may set a field 'optional' to true to indicate + * that it isn't necessary to pass validation. + * + * @param obj the ASN.1 object to validate. + * @param v the ASN.1 structure validator. + * @param capture an optional map to capture values in. + * @param errors an optional array for storing validation errors. + * + * @return true on success, false on failure. + */ +asn1.validate = function(obj, v, capture, errors) { + var rval = false; + + // ensure tag class and type are the same if specified + if((obj.tagClass === v.tagClass || typeof(v.tagClass) === 'undefined') && + (obj.type === v.type || typeof(v.type) === 'undefined')) { + // ensure constructed flag is the same if specified + if(obj.constructed === v.constructed || + typeof(v.constructed) === 'undefined') { + rval = true; + + // handle sub values + if(v.value && forge.util.isArray(v.value)) { + var j = 0; + for(var i = 0; rval && i < v.value.length; ++i) { + rval = v.value[i].optional || false; + if(obj.value[j]) { + rval = asn1.validate(obj.value[j], v.value[i], capture, errors); + if(rval) { + ++j; + } else if(v.value[i].optional) { + rval = true; + } + } + if(!rval && errors) { + errors.push( + '[' + v.name + '] ' + + 'Tag class "' + v.tagClass + '", type "' + + v.type + '" expected value length "' + + v.value.length + '", got "' + + obj.value.length + '"'); + } + } + } + + if(rval && capture) { + if(v.capture) { + capture[v.capture] = obj.value; + } + if(v.captureAsn1) { + capture[v.captureAsn1] = obj; + } + if(v.captureBitStringContents && 'bitStringContents' in obj) { + capture[v.captureBitStringContents] = obj.bitStringContents; + } + if(v.captureBitStringValue && 'bitStringContents' in obj) { + var value; + if(obj.bitStringContents.length < 2) { + capture[v.captureBitStringValue] = ''; + } else { + // FIXME: support unused bits with data shifting + var unused = obj.bitStringContents.charCodeAt(0); + if(unused !== 0) { + throw new Error( + 'captureBitStringValue only supported for zero unused bits'); + } + capture[v.captureBitStringValue] = obj.bitStringContents.slice(1); + } + } + } + } else if(errors) { + errors.push( + '[' + v.name + '] ' + + 'Expected constructed "' + v.constructed + '", got "' + + obj.constructed + '"'); + } + } else if(errors) { + if(obj.tagClass !== v.tagClass) { + errors.push( + '[' + v.name + '] ' + + 'Expected tag class "' + v.tagClass + '", got "' + + obj.tagClass + '"'); + } + if(obj.type !== v.type) { + errors.push( + '[' + v.name + '] ' + + 'Expected type "' + v.type + '", got "' + obj.type + '"'); + } + } + return rval; +}; + +// regex for testing for non-latin characters +var _nonLatinRegex = /[^\\u0000-\\u00ff]/; + +/** + * Pretty prints an ASN.1 object to a string. + * + * @param obj the object to write out. + * @param level the level in the tree. + * @param indentation the indentation to use. + * + * @return the string. + */ +asn1.prettyPrint = function(obj, level, indentation) { + var rval = ''; + + // set default level and indentation + level = level || 0; + indentation = indentation || 2; + + // start new line for deep levels + if(level > 0) { + rval += '\n'; + } + + // create indent + var indent = ''; + for(var i = 0; i < level * indentation; ++i) { + indent += ' '; + } + + // print class:type + rval += indent + 'Tag: '; + switch(obj.tagClass) { + case asn1.Class.UNIVERSAL: + rval += 'Universal:'; + break; + case asn1.Class.APPLICATION: + rval += 'Application:'; + break; + case asn1.Class.CONTEXT_SPECIFIC: + rval += 'Context-Specific:'; + break; + case asn1.Class.PRIVATE: + rval += 'Private:'; + break; + } + + if(obj.tagClass === asn1.Class.UNIVERSAL) { + rval += obj.type; + + // known types + switch(obj.type) { + case asn1.Type.NONE: + rval += ' (None)'; + break; + case asn1.Type.BOOLEAN: + rval += ' (Boolean)'; + break; + case asn1.Type.INTEGER: + rval += ' (Integer)'; + break; + case asn1.Type.BITSTRING: + rval += ' (Bit string)'; + break; + case asn1.Type.OCTETSTRING: + rval += ' (Octet string)'; + break; + case asn1.Type.NULL: + rval += ' (Null)'; + break; + case asn1.Type.OID: + rval += ' (Object Identifier)'; + break; + case asn1.Type.ODESC: + rval += ' (Object Descriptor)'; + break; + case asn1.Type.EXTERNAL: + rval += ' (External or Instance of)'; + break; + case asn1.Type.REAL: + rval += ' (Real)'; + break; + case asn1.Type.ENUMERATED: + rval += ' (Enumerated)'; + break; + case asn1.Type.EMBEDDED: + rval += ' (Embedded PDV)'; + break; + case asn1.Type.UTF8: + rval += ' (UTF8)'; + break; + case asn1.Type.ROID: + rval += ' (Relative Object Identifier)'; + break; + case asn1.Type.SEQUENCE: + rval += ' (Sequence)'; + break; + case asn1.Type.SET: + rval += ' (Set)'; + break; + case asn1.Type.PRINTABLESTRING: + rval += ' (Printable String)'; + break; + case asn1.Type.IA5String: + rval += ' (IA5String (ASCII))'; + break; + case asn1.Type.UTCTIME: + rval += ' (UTC time)'; + break; + case asn1.Type.GENERALIZEDTIME: + rval += ' (Generalized time)'; + break; + case asn1.Type.BMPSTRING: + rval += ' (BMP String)'; + break; + } + } else { + rval += obj.type; + } + + rval += '\n'; + rval += indent + 'Constructed: ' + obj.constructed + '\n'; + + if(obj.composed) { + var subvalues = 0; + var sub = ''; + for(var i = 0; i < obj.value.length; ++i) { + if(obj.value[i] !== undefined) { + subvalues += 1; + sub += asn1.prettyPrint(obj.value[i], level + 1, indentation); + if((i + 1) < obj.value.length) { + sub += ','; + } + } + } + rval += indent + 'Sub values: ' + subvalues + sub; + } else { + rval += indent + 'Value: '; + if(obj.type === asn1.Type.OID) { + var oid = asn1.derToOid(obj.value); + rval += oid; + if(forge.pki && forge.pki.oids) { + if(oid in forge.pki.oids) { + rval += ' (' + forge.pki.oids[oid] + ') '; + } + } + } + if(obj.type === asn1.Type.INTEGER) { + try { + rval += asn1.derToInteger(obj.value); + } catch(ex) { + rval += '0x' + forge.util.bytesToHex(obj.value); + } + } else if(obj.type === asn1.Type.BITSTRING) { + // TODO: shift bits as needed to display without padding + if(obj.value.length > 1) { + // remove unused bits field + rval += '0x' + forge.util.bytesToHex(obj.value.slice(1)); + } else { + rval += '(none)'; + } + // show unused bit count + if(obj.value.length > 0) { + var unused = obj.value.charCodeAt(0); + if(unused == 1) { + rval += ' (1 unused bit shown)'; + } else if(unused > 1) { + rval += ' (' + unused + ' unused bits shown)'; + } + } + } else if(obj.type === asn1.Type.OCTETSTRING) { + if(!_nonLatinRegex.test(obj.value)) { + rval += '(' + obj.value + ') '; + } + rval += '0x' + forge.util.bytesToHex(obj.value); + } else if(obj.type === asn1.Type.UTF8) { + rval += forge.util.decodeUtf8(obj.value); + } else if(obj.type === asn1.Type.PRINTABLESTRING || + obj.type === asn1.Type.IA5String) { + rval += obj.value; + } else if(_nonLatinRegex.test(obj.value)) { + rval += '0x' + forge.util.bytesToHex(obj.value); + } else if(obj.value.length === 0) { + rval += '[null]'; + } else { + rval += obj.value; + } + } + + return rval; +}; diff --git a/node_modules/node-forge/lib/baseN.js b/node_modules/node-forge/lib/baseN.js new file mode 100644 index 0000000..824fa36 --- /dev/null +++ b/node_modules/node-forge/lib/baseN.js @@ -0,0 +1,186 @@ +/** + * Base-N/Base-X encoding/decoding functions. + * + * Original implementation from base-x: + * https://github.com/cryptocoinjs/base-x + * + * Which is MIT licensed: + * + * The MIT License (MIT) + * + * Copyright base-x contributors (c) 2016 + * + * 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. + */ +var api = {}; +module.exports = api; + +// baseN alphabet indexes +var _reverseAlphabets = {}; + +/** + * BaseN-encodes a Uint8Array using the given alphabet. + * + * @param input the Uint8Array to encode. + * @param maxline the maximum number of encoded characters per line to use, + * defaults to none. + * + * @return the baseN-encoded output string. + */ +api.encode = function(input, alphabet, maxline) { + if(typeof alphabet !== 'string') { + throw new TypeError('"alphabet" must be a string.'); + } + if(maxline !== undefined && typeof maxline !== 'number') { + throw new TypeError('"maxline" must be a number.'); + } + + var output = ''; + + if(!(input instanceof Uint8Array)) { + // assume forge byte buffer + output = _encodeWithByteBuffer(input, alphabet); + } else { + var i = 0; + var base = alphabet.length; + var first = alphabet.charAt(0); + var digits = [0]; + for(i = 0; i < input.length; ++i) { + for(var j = 0, carry = input[i]; j < digits.length; ++j) { + carry += digits[j] << 8; + digits[j] = carry % base; + carry = (carry / base) | 0; + } + + while(carry > 0) { + digits.push(carry % base); + carry = (carry / base) | 0; + } + } + + // deal with leading zeros + for(i = 0; input[i] === 0 && i < input.length - 1; ++i) { + output += first; + } + // convert digits to a string + for(i = digits.length - 1; i >= 0; --i) { + output += alphabet[digits[i]]; + } + } + + if(maxline) { + var regex = new RegExp('.{1,' + maxline + '}', 'g'); + output = output.match(regex).join('\r\n'); + } + + return output; +}; + +/** + * Decodes a baseN-encoded (using the given alphabet) string to a + * Uint8Array. + * + * @param input the baseN-encoded input string. + * + * @return the Uint8Array. + */ +api.decode = function(input, alphabet) { + if(typeof input !== 'string') { + throw new TypeError('"input" must be a string.'); + } + if(typeof alphabet !== 'string') { + throw new TypeError('"alphabet" must be a string.'); + } + + var table = _reverseAlphabets[alphabet]; + if(!table) { + // compute reverse alphabet + table = _reverseAlphabets[alphabet] = []; + for(var i = 0; i < alphabet.length; ++i) { + table[alphabet.charCodeAt(i)] = i; + } + } + + // remove whitespace characters + input = input.replace(/\s/g, ''); + + var base = alphabet.length; + var first = alphabet.charAt(0); + var bytes = [0]; + for(var i = 0; i < input.length; i++) { + var value = table[input.charCodeAt(i)]; + if(value === undefined) { + return; + } + + for(var j = 0, carry = value; j < bytes.length; ++j) { + carry += bytes[j] * base; + bytes[j] = carry & 0xff; + carry >>= 8; + } + + while(carry > 0) { + bytes.push(carry & 0xff); + carry >>= 8; + } + } + + // deal with leading zeros + for(var k = 0; input[k] === first && k < input.length - 1; ++k) { + bytes.push(0); + } + + if(typeof Buffer !== 'undefined') { + return Buffer.from(bytes.reverse()); + } + + return new Uint8Array(bytes.reverse()); +}; + +function _encodeWithByteBuffer(input, alphabet) { + var i = 0; + var base = alphabet.length; + var first = alphabet.charAt(0); + var digits = [0]; + for(i = 0; i < input.length(); ++i) { + for(var j = 0, carry = input.at(i); j < digits.length; ++j) { + carry += digits[j] << 8; + digits[j] = carry % base; + carry = (carry / base) | 0; + } + + while(carry > 0) { + digits.push(carry % base); + carry = (carry / base) | 0; + } + } + + var output = ''; + + // deal with leading zeros + for(i = 0; input.at(i) === 0 && i < input.length() - 1; ++i) { + output += first; + } + // convert digits to a string + for(i = digits.length - 1; i >= 0; --i) { + output += alphabet[digits[i]]; + } + + return output; +} diff --git a/node_modules/node-forge/lib/cipher.js b/node_modules/node-forge/lib/cipher.js new file mode 100644 index 0000000..f2c36e6 --- /dev/null +++ b/node_modules/node-forge/lib/cipher.js @@ -0,0 +1,230 @@ +/** + * Cipher base API. + * + * @author Dave Longley + * + * Copyright (c) 2010-2014 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./util'); + +module.exports = forge.cipher = forge.cipher || {}; + +// registered algorithms +forge.cipher.algorithms = forge.cipher.algorithms || {}; + +/** + * Creates a cipher object that can be used to encrypt data using the given + * algorithm and key. The algorithm may be provided as a string value for a + * previously registered algorithm or it may be given as a cipher algorithm + * API object. + * + * @param algorithm the algorithm to use, either a string or an algorithm API + * object. + * @param key the key to use, as a binary-encoded string of bytes or a + * byte buffer. + * + * @return the cipher. + */ +forge.cipher.createCipher = function(algorithm, key) { + var api = algorithm; + if(typeof api === 'string') { + api = forge.cipher.getAlgorithm(api); + if(api) { + api = api(); + } + } + if(!api) { + throw new Error('Unsupported algorithm: ' + algorithm); + } + + // assume block cipher + return new forge.cipher.BlockCipher({ + algorithm: api, + key: key, + decrypt: false + }); +}; + +/** + * Creates a decipher object that can be used to decrypt data using the given + * algorithm and key. The algorithm may be provided as a string value for a + * previously registered algorithm or it may be given as a cipher algorithm + * API object. + * + * @param algorithm the algorithm to use, either a string or an algorithm API + * object. + * @param key the key to use, as a binary-encoded string of bytes or a + * byte buffer. + * + * @return the cipher. + */ +forge.cipher.createDecipher = function(algorithm, key) { + var api = algorithm; + if(typeof api === 'string') { + api = forge.cipher.getAlgorithm(api); + if(api) { + api = api(); + } + } + if(!api) { + throw new Error('Unsupported algorithm: ' + algorithm); + } + + // assume block cipher + return new forge.cipher.BlockCipher({ + algorithm: api, + key: key, + decrypt: true + }); +}; + +/** + * Registers an algorithm by name. If the name was already registered, the + * algorithm API object will be overwritten. + * + * @param name the name of the algorithm. + * @param algorithm the algorithm API object. + */ +forge.cipher.registerAlgorithm = function(name, algorithm) { + name = name.toUpperCase(); + forge.cipher.algorithms[name] = algorithm; +}; + +/** + * Gets a registered algorithm by name. + * + * @param name the name of the algorithm. + * + * @return the algorithm, if found, null if not. + */ +forge.cipher.getAlgorithm = function(name) { + name = name.toUpperCase(); + if(name in forge.cipher.algorithms) { + return forge.cipher.algorithms[name]; + } + return null; +}; + +var BlockCipher = forge.cipher.BlockCipher = function(options) { + this.algorithm = options.algorithm; + this.mode = this.algorithm.mode; + this.blockSize = this.mode.blockSize; + this._finish = false; + this._input = null; + this.output = null; + this._op = options.decrypt ? this.mode.decrypt : this.mode.encrypt; + this._decrypt = options.decrypt; + this.algorithm.initialize(options); +}; + +/** + * Starts or restarts the encryption or decryption process, whichever + * was previously configured. + * + * For non-GCM mode, the IV may be a binary-encoded string of bytes, an array + * of bytes, a byte buffer, or an array of 32-bit integers. If the IV is in + * bytes, then it must be Nb (16) bytes in length. If the IV is given in as + * 32-bit integers, then it must be 4 integers long. + * + * Note: an IV is not required or used in ECB mode. + * + * For GCM-mode, the IV must be given as a binary-encoded string of bytes or + * a byte buffer. The number of bytes should be 12 (96 bits) as recommended + * by NIST SP-800-38D but another length may be given. + * + * @param options the options to use: + * iv the initialization vector to use as a binary-encoded string of + * bytes, null to reuse the last ciphered block from a previous + * update() (this "residue" method is for legacy support only). + * additionalData additional authentication data as a binary-encoded + * string of bytes, for 'GCM' mode, (default: none). + * tagLength desired length of authentication tag, in bits, for + * 'GCM' mode (0-128, default: 128). + * tag the authentication tag to check if decrypting, as a + * binary-encoded string of bytes. + * output the output the buffer to write to, null to create one. + */ +BlockCipher.prototype.start = function(options) { + options = options || {}; + var opts = {}; + for(var key in options) { + opts[key] = options[key]; + } + opts.decrypt = this._decrypt; + this._finish = false; + this._input = forge.util.createBuffer(); + this.output = options.output || forge.util.createBuffer(); + this.mode.start(opts); +}; + +/** + * Updates the next block according to the cipher mode. + * + * @param input the buffer to read from. + */ +BlockCipher.prototype.update = function(input) { + if(input) { + // input given, so empty it into the input buffer + this._input.putBuffer(input); + } + + // do cipher operation until it needs more input and not finished + while(!this._op.call(this.mode, this._input, this.output, this._finish) && + !this._finish) {} + + // free consumed memory from input buffer + this._input.compact(); +}; + +/** + * Finishes encrypting or decrypting. + * + * @param pad a padding function to use in CBC mode, null for default, + * signature(blockSize, buffer, decrypt). + * + * @return true if successful, false on error. + */ +BlockCipher.prototype.finish = function(pad) { + // backwards-compatibility w/deprecated padding API + // Note: will overwrite padding functions even after another start() call + if(pad && (this.mode.name === 'ECB' || this.mode.name === 'CBC')) { + this.mode.pad = function(input) { + return pad(this.blockSize, input, false); + }; + this.mode.unpad = function(output) { + return pad(this.blockSize, output, true); + }; + } + + // build options for padding and afterFinish functions + var options = {}; + options.decrypt = this._decrypt; + + // get # of bytes that won't fill a block + options.overflow = this._input.length() % this.blockSize; + + if(!this._decrypt && this.mode.pad) { + if(!this.mode.pad(this._input, options)) { + return false; + } + } + + // do final update + this._finish = true; + this.update(); + + if(this._decrypt && this.mode.unpad) { + if(!this.mode.unpad(this.output, options)) { + return false; + } + } + + if(this.mode.afterFinish) { + if(!this.mode.afterFinish(this.output, options)) { + return false; + } + } + + return true; +}; diff --git a/node_modules/node-forge/lib/cipherModes.js b/node_modules/node-forge/lib/cipherModes.js new file mode 100644 index 0000000..339915c --- /dev/null +++ b/node_modules/node-forge/lib/cipherModes.js @@ -0,0 +1,999 @@ +/** + * Supported cipher modes. + * + * @author Dave Longley + * + * Copyright (c) 2010-2014 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./util'); + +forge.cipher = forge.cipher || {}; + +// supported cipher modes +var modes = module.exports = forge.cipher.modes = forge.cipher.modes || {}; + +/** Electronic codebook (ECB) (Don't use this; it's not secure) **/ + +modes.ecb = function(options) { + options = options || {}; + this.name = 'ECB'; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = new Array(this._ints); + this._outBlock = new Array(this._ints); +}; + +modes.ecb.prototype.start = function(options) {}; + +modes.ecb.prototype.encrypt = function(input, output, finish) { + // not enough input to encrypt + if(input.length() < this.blockSize && !(finish && input.length() > 0)) { + return true; + } + + // get next block + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32(); + } + + // encrypt block + this.cipher.encrypt(this._inBlock, this._outBlock); + + // write output + for(var i = 0; i < this._ints; ++i) { + output.putInt32(this._outBlock[i]); + } +}; + +modes.ecb.prototype.decrypt = function(input, output, finish) { + // not enough input to decrypt + if(input.length() < this.blockSize && !(finish && input.length() > 0)) { + return true; + } + + // get next block + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32(); + } + + // decrypt block + this.cipher.decrypt(this._inBlock, this._outBlock); + + // write output + for(var i = 0; i < this._ints; ++i) { + output.putInt32(this._outBlock[i]); + } +}; + +modes.ecb.prototype.pad = function(input, options) { + // add PKCS#7 padding to block (each pad byte is the + // value of the number of pad bytes) + var padding = (input.length() === this.blockSize ? + this.blockSize : (this.blockSize - input.length())); + input.fillWithByte(padding, padding); + return true; +}; + +modes.ecb.prototype.unpad = function(output, options) { + // check for error: input data not a multiple of blockSize + if(options.overflow > 0) { + return false; + } + + // ensure padding byte count is valid + var len = output.length(); + var count = output.at(len - 1); + if(count > (this.blockSize << 2)) { + return false; + } + + // trim off padding bytes + output.truncate(count); + return true; +}; + +/** Cipher-block Chaining (CBC) **/ + +modes.cbc = function(options) { + options = options || {}; + this.name = 'CBC'; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = new Array(this._ints); + this._outBlock = new Array(this._ints); +}; + +modes.cbc.prototype.start = function(options) { + // Note: legacy support for using IV residue (has security flaws) + // if IV is null, reuse block from previous processing + if(options.iv === null) { + // must have a previous block + if(!this._prev) { + throw new Error('Invalid IV parameter.'); + } + this._iv = this._prev.slice(0); + } else if(!('iv' in options)) { + throw new Error('Invalid IV parameter.'); + } else { + // save IV as "previous" block + this._iv = transformIV(options.iv, this.blockSize); + this._prev = this._iv.slice(0); + } +}; + +modes.cbc.prototype.encrypt = function(input, output, finish) { + // not enough input to encrypt + if(input.length() < this.blockSize && !(finish && input.length() > 0)) { + return true; + } + + // get next block + // CBC XOR's IV (or previous block) with plaintext + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = this._prev[i] ^ input.getInt32(); + } + + // encrypt block + this.cipher.encrypt(this._inBlock, this._outBlock); + + // write output, save previous block + for(var i = 0; i < this._ints; ++i) { + output.putInt32(this._outBlock[i]); + } + this._prev = this._outBlock; +}; + +modes.cbc.prototype.decrypt = function(input, output, finish) { + // not enough input to decrypt + if(input.length() < this.blockSize && !(finish && input.length() > 0)) { + return true; + } + + // get next block + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32(); + } + + // decrypt block + this.cipher.decrypt(this._inBlock, this._outBlock); + + // write output, save previous ciphered block + // CBC XOR's IV (or previous block) with ciphertext + for(var i = 0; i < this._ints; ++i) { + output.putInt32(this._prev[i] ^ this._outBlock[i]); + } + this._prev = this._inBlock.slice(0); +}; + +modes.cbc.prototype.pad = function(input, options) { + // add PKCS#7 padding to block (each pad byte is the + // value of the number of pad bytes) + var padding = (input.length() === this.blockSize ? + this.blockSize : (this.blockSize - input.length())); + input.fillWithByte(padding, padding); + return true; +}; + +modes.cbc.prototype.unpad = function(output, options) { + // check for error: input data not a multiple of blockSize + if(options.overflow > 0) { + return false; + } + + // ensure padding byte count is valid + var len = output.length(); + var count = output.at(len - 1); + if(count > (this.blockSize << 2)) { + return false; + } + + // trim off padding bytes + output.truncate(count); + return true; +}; + +/** Cipher feedback (CFB) **/ + +modes.cfb = function(options) { + options = options || {}; + this.name = 'CFB'; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = null; + this._outBlock = new Array(this._ints); + this._partialBlock = new Array(this._ints); + this._partialOutput = forge.util.createBuffer(); + this._partialBytes = 0; +}; + +modes.cfb.prototype.start = function(options) { + if(!('iv' in options)) { + throw new Error('Invalid IV parameter.'); + } + // use IV as first input + this._iv = transformIV(options.iv, this.blockSize); + this._inBlock = this._iv.slice(0); + this._partialBytes = 0; +}; + +modes.cfb.prototype.encrypt = function(input, output, finish) { + // not enough input to encrypt + var inputLength = input.length(); + if(inputLength === 0) { + return true; + } + + // encrypt block + this.cipher.encrypt(this._inBlock, this._outBlock); + + // handle full block + if(this._partialBytes === 0 && inputLength >= this.blockSize) { + // XOR input with output, write input as output + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32() ^ this._outBlock[i]; + output.putInt32(this._inBlock[i]); + } + return; + } + + // handle partial block + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if(partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; + } + + // XOR input with output, write input as partial output + this._partialOutput.clear(); + for(var i = 0; i < this._ints; ++i) { + this._partialBlock[i] = input.getInt32() ^ this._outBlock[i]; + this._partialOutput.putInt32(this._partialBlock[i]); + } + + if(partialBytes > 0) { + // block still incomplete, restore input buffer + input.read -= this.blockSize; + } else { + // block complete, update input block + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = this._partialBlock[i]; + } + } + + // skip any previous partial bytes + if(this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); + } + + if(partialBytes > 0 && !finish) { + output.putBytes(this._partialOutput.getBytes( + partialBytes - this._partialBytes)); + this._partialBytes = partialBytes; + return true; + } + + output.putBytes(this._partialOutput.getBytes( + inputLength - this._partialBytes)); + this._partialBytes = 0; +}; + +modes.cfb.prototype.decrypt = function(input, output, finish) { + // not enough input to decrypt + var inputLength = input.length(); + if(inputLength === 0) { + return true; + } + + // encrypt block (CFB always uses encryption mode) + this.cipher.encrypt(this._inBlock, this._outBlock); + + // handle full block + if(this._partialBytes === 0 && inputLength >= this.blockSize) { + // XOR input with output, write input as output + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = input.getInt32(); + output.putInt32(this._inBlock[i] ^ this._outBlock[i]); + } + return; + } + + // handle partial block + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if(partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; + } + + // XOR input with output, write input as partial output + this._partialOutput.clear(); + for(var i = 0; i < this._ints; ++i) { + this._partialBlock[i] = input.getInt32(); + this._partialOutput.putInt32(this._partialBlock[i] ^ this._outBlock[i]); + } + + if(partialBytes > 0) { + // block still incomplete, restore input buffer + input.read -= this.blockSize; + } else { + // block complete, update input block + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = this._partialBlock[i]; + } + } + + // skip any previous partial bytes + if(this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); + } + + if(partialBytes > 0 && !finish) { + output.putBytes(this._partialOutput.getBytes( + partialBytes - this._partialBytes)); + this._partialBytes = partialBytes; + return true; + } + + output.putBytes(this._partialOutput.getBytes( + inputLength - this._partialBytes)); + this._partialBytes = 0; +}; + +/** Output feedback (OFB) **/ + +modes.ofb = function(options) { + options = options || {}; + this.name = 'OFB'; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = null; + this._outBlock = new Array(this._ints); + this._partialOutput = forge.util.createBuffer(); + this._partialBytes = 0; +}; + +modes.ofb.prototype.start = function(options) { + if(!('iv' in options)) { + throw new Error('Invalid IV parameter.'); + } + // use IV as first input + this._iv = transformIV(options.iv, this.blockSize); + this._inBlock = this._iv.slice(0); + this._partialBytes = 0; +}; + +modes.ofb.prototype.encrypt = function(input, output, finish) { + // not enough input to encrypt + var inputLength = input.length(); + if(input.length() === 0) { + return true; + } + + // encrypt block (OFB always uses encryption mode) + this.cipher.encrypt(this._inBlock, this._outBlock); + + // handle full block + if(this._partialBytes === 0 && inputLength >= this.blockSize) { + // XOR input with output and update next input + for(var i = 0; i < this._ints; ++i) { + output.putInt32(input.getInt32() ^ this._outBlock[i]); + this._inBlock[i] = this._outBlock[i]; + } + return; + } + + // handle partial block + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if(partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; + } + + // XOR input with output + this._partialOutput.clear(); + for(var i = 0; i < this._ints; ++i) { + this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); + } + + if(partialBytes > 0) { + // block still incomplete, restore input buffer + input.read -= this.blockSize; + } else { + // block complete, update input block + for(var i = 0; i < this._ints; ++i) { + this._inBlock[i] = this._outBlock[i]; + } + } + + // skip any previous partial bytes + if(this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); + } + + if(partialBytes > 0 && !finish) { + output.putBytes(this._partialOutput.getBytes( + partialBytes - this._partialBytes)); + this._partialBytes = partialBytes; + return true; + } + + output.putBytes(this._partialOutput.getBytes( + inputLength - this._partialBytes)); + this._partialBytes = 0; +}; + +modes.ofb.prototype.decrypt = modes.ofb.prototype.encrypt; + +/** Counter (CTR) **/ + +modes.ctr = function(options) { + options = options || {}; + this.name = 'CTR'; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = null; + this._outBlock = new Array(this._ints); + this._partialOutput = forge.util.createBuffer(); + this._partialBytes = 0; +}; + +modes.ctr.prototype.start = function(options) { + if(!('iv' in options)) { + throw new Error('Invalid IV parameter.'); + } + // use IV as first input + this._iv = transformIV(options.iv, this.blockSize); + this._inBlock = this._iv.slice(0); + this._partialBytes = 0; +}; + +modes.ctr.prototype.encrypt = function(input, output, finish) { + // not enough input to encrypt + var inputLength = input.length(); + if(inputLength === 0) { + return true; + } + + // encrypt block (CTR always uses encryption mode) + this.cipher.encrypt(this._inBlock, this._outBlock); + + // handle full block + if(this._partialBytes === 0 && inputLength >= this.blockSize) { + // XOR input with output + for(var i = 0; i < this._ints; ++i) { + output.putInt32(input.getInt32() ^ this._outBlock[i]); + } + } else { + // handle partial block + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if(partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; + } + + // XOR input with output + this._partialOutput.clear(); + for(var i = 0; i < this._ints; ++i) { + this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); + } + + if(partialBytes > 0) { + // block still incomplete, restore input buffer + input.read -= this.blockSize; + } + + // skip any previous partial bytes + if(this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); + } + + if(partialBytes > 0 && !finish) { + output.putBytes(this._partialOutput.getBytes( + partialBytes - this._partialBytes)); + this._partialBytes = partialBytes; + return true; + } + + output.putBytes(this._partialOutput.getBytes( + inputLength - this._partialBytes)); + this._partialBytes = 0; + } + + // block complete, increment counter (input block) + inc32(this._inBlock); +}; + +modes.ctr.prototype.decrypt = modes.ctr.prototype.encrypt; + +/** Galois/Counter Mode (GCM) **/ + +modes.gcm = function(options) { + options = options || {}; + this.name = 'GCM'; + this.cipher = options.cipher; + this.blockSize = options.blockSize || 16; + this._ints = this.blockSize / 4; + this._inBlock = new Array(this._ints); + this._outBlock = new Array(this._ints); + this._partialOutput = forge.util.createBuffer(); + this._partialBytes = 0; + + // R is actually this value concatenated with 120 more zero bits, but + // we only XOR against R so the other zeros have no effect -- we just + // apply this value to the first integer in a block + this._R = 0xE1000000; +}; + +modes.gcm.prototype.start = function(options) { + if(!('iv' in options)) { + throw new Error('Invalid IV parameter.'); + } + // ensure IV is a byte buffer + var iv = forge.util.createBuffer(options.iv); + + // no ciphered data processed yet + this._cipherLength = 0; + + // default additional data is none + var additionalData; + if('additionalData' in options) { + additionalData = forge.util.createBuffer(options.additionalData); + } else { + additionalData = forge.util.createBuffer(); + } + + // default tag length is 128 bits + if('tagLength' in options) { + this._tagLength = options.tagLength; + } else { + this._tagLength = 128; + } + + // if tag is given, ensure tag matches tag length + this._tag = null; + if(options.decrypt) { + // save tag to check later + this._tag = forge.util.createBuffer(options.tag).getBytes(); + if(this._tag.length !== (this._tagLength / 8)) { + throw new Error('Authentication tag does not match tag length.'); + } + } + + // create tmp storage for hash calculation + this._hashBlock = new Array(this._ints); + + // no tag generated yet + this.tag = null; + + // generate hash subkey + // (apply block cipher to "zero" block) + this._hashSubkey = new Array(this._ints); + this.cipher.encrypt([0, 0, 0, 0], this._hashSubkey); + + // generate table M + // use 4-bit tables (32 component decomposition of a 16 byte value) + // 8-bit tables take more space and are known to have security + // vulnerabilities (in native implementations) + this.componentBits = 4; + this._m = this.generateHashTable(this._hashSubkey, this.componentBits); + + // Note: support IV length different from 96 bits? (only supporting + // 96 bits is recommended by NIST SP-800-38D) + // generate J_0 + var ivLength = iv.length(); + if(ivLength === 12) { + // 96-bit IV + this._j0 = [iv.getInt32(), iv.getInt32(), iv.getInt32(), 1]; + } else { + // IV is NOT 96-bits + this._j0 = [0, 0, 0, 0]; + while(iv.length() > 0) { + this._j0 = this.ghash( + this._hashSubkey, this._j0, + [iv.getInt32(), iv.getInt32(), iv.getInt32(), iv.getInt32()]); + } + this._j0 = this.ghash( + this._hashSubkey, this._j0, [0, 0].concat(from64To32(ivLength * 8))); + } + + // generate ICB (initial counter block) + this._inBlock = this._j0.slice(0); + inc32(this._inBlock); + this._partialBytes = 0; + + // consume authentication data + additionalData = forge.util.createBuffer(additionalData); + // save additional data length as a BE 64-bit number + this._aDataLength = from64To32(additionalData.length() * 8); + // pad additional data to 128 bit (16 byte) block size + var overflow = additionalData.length() % this.blockSize; + if(overflow) { + additionalData.fillWithByte(0, this.blockSize - overflow); + } + this._s = [0, 0, 0, 0]; + while(additionalData.length() > 0) { + this._s = this.ghash(this._hashSubkey, this._s, [ + additionalData.getInt32(), + additionalData.getInt32(), + additionalData.getInt32(), + additionalData.getInt32() + ]); + } +}; + +modes.gcm.prototype.encrypt = function(input, output, finish) { + // not enough input to encrypt + var inputLength = input.length(); + if(inputLength === 0) { + return true; + } + + // encrypt block + this.cipher.encrypt(this._inBlock, this._outBlock); + + // handle full block + if(this._partialBytes === 0 && inputLength >= this.blockSize) { + // XOR input with output + for(var i = 0; i < this._ints; ++i) { + output.putInt32(this._outBlock[i] ^= input.getInt32()); + } + this._cipherLength += this.blockSize; + } else { + // handle partial block + var partialBytes = (this.blockSize - inputLength) % this.blockSize; + if(partialBytes > 0) { + partialBytes = this.blockSize - partialBytes; + } + + // XOR input with output + this._partialOutput.clear(); + for(var i = 0; i < this._ints; ++i) { + this._partialOutput.putInt32(input.getInt32() ^ this._outBlock[i]); + } + + if(partialBytes <= 0 || finish) { + // handle overflow prior to hashing + if(finish) { + // get block overflow + var overflow = inputLength % this.blockSize; + this._cipherLength += overflow; + // truncate for hash function + this._partialOutput.truncate(this.blockSize - overflow); + } else { + this._cipherLength += this.blockSize; + } + + // get output block for hashing + for(var i = 0; i < this._ints; ++i) { + this._outBlock[i] = this._partialOutput.getInt32(); + } + this._partialOutput.read -= this.blockSize; + } + + // skip any previous partial bytes + if(this._partialBytes > 0) { + this._partialOutput.getBytes(this._partialBytes); + } + + if(partialBytes > 0 && !finish) { + // block still incomplete, restore input buffer, get partial output, + // and return early + input.read -= this.blockSize; + output.putBytes(this._partialOutput.getBytes( + partialBytes - this._partialBytes)); + this._partialBytes = partialBytes; + return true; + } + + output.putBytes(this._partialOutput.getBytes( + inputLength - this._partialBytes)); + this._partialBytes = 0; + } + + // update hash block S + this._s = this.ghash(this._hashSubkey, this._s, this._outBlock); + + // increment counter (input block) + inc32(this._inBlock); +}; + +modes.gcm.prototype.decrypt = function(input, output, finish) { + // not enough input to decrypt + var inputLength = input.length(); + if(inputLength < this.blockSize && !(finish && inputLength > 0)) { + return true; + } + + // encrypt block (GCM always uses encryption mode) + this.cipher.encrypt(this._inBlock, this._outBlock); + + // increment counter (input block) + inc32(this._inBlock); + + // update hash block S + this._hashBlock[0] = input.getInt32(); + this._hashBlock[1] = input.getInt32(); + this._hashBlock[2] = input.getInt32(); + this._hashBlock[3] = input.getInt32(); + this._s = this.ghash(this._hashSubkey, this._s, this._hashBlock); + + // XOR hash input with output + for(var i = 0; i < this._ints; ++i) { + output.putInt32(this._outBlock[i] ^ this._hashBlock[i]); + } + + // increment cipher data length + if(inputLength < this.blockSize) { + this._cipherLength += inputLength % this.blockSize; + } else { + this._cipherLength += this.blockSize; + } +}; + +modes.gcm.prototype.afterFinish = function(output, options) { + var rval = true; + + // handle overflow + if(options.decrypt && options.overflow) { + output.truncate(this.blockSize - options.overflow); + } + + // handle authentication tag + this.tag = forge.util.createBuffer(); + + // concatenate additional data length with cipher length + var lengths = this._aDataLength.concat(from64To32(this._cipherLength * 8)); + + // include lengths in hash + this._s = this.ghash(this._hashSubkey, this._s, lengths); + + // do GCTR(J_0, S) + var tag = []; + this.cipher.encrypt(this._j0, tag); + for(var i = 0; i < this._ints; ++i) { + this.tag.putInt32(this._s[i] ^ tag[i]); + } + + // trim tag to length + this.tag.truncate(this.tag.length() % (this._tagLength / 8)); + + // check authentication tag + if(options.decrypt && this.tag.bytes() !== this._tag) { + rval = false; + } + + return rval; +}; + +/** + * See NIST SP-800-38D 6.3 (Algorithm 1). This function performs Galois + * field multiplication. The field, GF(2^128), is defined by the polynomial: + * + * x^128 + x^7 + x^2 + x + 1 + * + * Which is represented in little-endian binary form as: 11100001 (0xe1). When + * the value of a coefficient is 1, a bit is set. The value R, is the + * concatenation of this value and 120 zero bits, yielding a 128-bit value + * which matches the block size. + * + * This function will multiply two elements (vectors of bytes), X and Y, in + * the field GF(2^128). The result is initialized to zero. For each bit of + * X (out of 128), x_i, if x_i is set, then the result is multiplied (XOR'd) + * by the current value of Y. For each bit, the value of Y will be raised by + * a power of x (multiplied by the polynomial x). This can be achieved by + * shifting Y once to the right. If the current value of Y, prior to being + * multiplied by x, has 0 as its LSB, then it is a 127th degree polynomial. + * Otherwise, we must divide by R after shifting to find the remainder. + * + * @param x the first block to multiply by the second. + * @param y the second block to multiply by the first. + * + * @return the block result of the multiplication. + */ +modes.gcm.prototype.multiply = function(x, y) { + var z_i = [0, 0, 0, 0]; + var v_i = y.slice(0); + + // calculate Z_128 (block has 128 bits) + for(var i = 0; i < 128; ++i) { + // if x_i is 0, Z_{i+1} = Z_i (unchanged) + // else Z_{i+1} = Z_i ^ V_i + // get x_i by finding 32-bit int position, then left shift 1 by remainder + var x_i = x[(i / 32) | 0] & (1 << (31 - i % 32)); + if(x_i) { + z_i[0] ^= v_i[0]; + z_i[1] ^= v_i[1]; + z_i[2] ^= v_i[2]; + z_i[3] ^= v_i[3]; + } + + // if LSB(V_i) is 1, V_i = V_i >> 1 + // else V_i = (V_i >> 1) ^ R + this.pow(v_i, v_i); + } + + return z_i; +}; + +modes.gcm.prototype.pow = function(x, out) { + // if LSB(x) is 1, x = x >>> 1 + // else x = (x >>> 1) ^ R + var lsb = x[3] & 1; + + // always do x >>> 1: + // starting with the rightmost integer, shift each integer to the right + // one bit, pulling in the bit from the integer to the left as its top + // most bit (do this for the last 3 integers) + for(var i = 3; i > 0; --i) { + out[i] = (x[i] >>> 1) | ((x[i - 1] & 1) << 31); + } + // shift the first integer normally + out[0] = x[0] >>> 1; + + // if lsb was not set, then polynomial had a degree of 127 and doesn't + // need to divided; otherwise, XOR with R to find the remainder; we only + // need to XOR the first integer since R technically ends w/120 zero bits + if(lsb) { + out[0] ^= this._R; + } +}; + +modes.gcm.prototype.tableMultiply = function(x) { + // assumes 4-bit tables are used + var z = [0, 0, 0, 0]; + for(var i = 0; i < 32; ++i) { + var idx = (i / 8) | 0; + var x_i = (x[idx] >>> ((7 - (i % 8)) * 4)) & 0xF; + var ah = this._m[i][x_i]; + z[0] ^= ah[0]; + z[1] ^= ah[1]; + z[2] ^= ah[2]; + z[3] ^= ah[3]; + } + return z; +}; + +/** + * A continuing version of the GHASH algorithm that operates on a single + * block. The hash block, last hash value (Ym) and the new block to hash + * are given. + * + * @param h the hash block. + * @param y the previous value for Ym, use [0, 0, 0, 0] for a new hash. + * @param x the block to hash. + * + * @return the hashed value (Ym). + */ +modes.gcm.prototype.ghash = function(h, y, x) { + y[0] ^= x[0]; + y[1] ^= x[1]; + y[2] ^= x[2]; + y[3] ^= x[3]; + return this.tableMultiply(y); + //return this.multiply(y, h); +}; + +/** + * Precomputes a table for multiplying against the hash subkey. This + * mechanism provides a substantial speed increase over multiplication + * performed without a table. The table-based multiplication this table is + * for solves X * H by multiplying each component of X by H and then + * composing the results together using XOR. + * + * This function can be used to generate tables with different bit sizes + * for the components, however, this implementation assumes there are + * 32 components of X (which is a 16 byte vector), therefore each component + * takes 4-bits (so the table is constructed with bits=4). + * + * @param h the hash subkey. + * @param bits the bit size for a component. + */ +modes.gcm.prototype.generateHashTable = function(h, bits) { + // TODO: There are further optimizations that would use only the + // first table M_0 (or some variant) along with a remainder table; + // this can be explored in the future + var multiplier = 8 / bits; + var perInt = 4 * multiplier; + var size = 16 * multiplier; + var m = new Array(size); + for(var i = 0; i < size; ++i) { + var tmp = [0, 0, 0, 0]; + var idx = (i / perInt) | 0; + var shft = ((perInt - 1 - (i % perInt)) * bits); + tmp[idx] = (1 << (bits - 1)) << shft; + m[i] = this.generateSubHashTable(this.multiply(tmp, h), bits); + } + return m; +}; + +/** + * Generates a table for multiplying against the hash subkey for one + * particular component (out of all possible component values). + * + * @param mid the pre-multiplied value for the middle key of the table. + * @param bits the bit size for a component. + */ +modes.gcm.prototype.generateSubHashTable = function(mid, bits) { + // compute the table quickly by minimizing the number of + // POW operations -- they only need to be performed for powers of 2, + // all other entries can be composed from those powers using XOR + var size = 1 << bits; + var half = size >>> 1; + var m = new Array(size); + m[half] = mid.slice(0); + var i = half >>> 1; + while(i > 0) { + // raise m0[2 * i] and store in m0[i] + this.pow(m[2 * i], m[i] = []); + i >>= 1; + } + i = 2; + while(i < half) { + for(var j = 1; j < i; ++j) { + var m_i = m[i]; + var m_j = m[j]; + m[i + j] = [ + m_i[0] ^ m_j[0], + m_i[1] ^ m_j[1], + m_i[2] ^ m_j[2], + m_i[3] ^ m_j[3] + ]; + } + i *= 2; + } + m[0] = [0, 0, 0, 0]; + /* Note: We could avoid storing these by doing composition during multiply + calculate top half using composition by speed is preferred. */ + for(i = half + 1; i < size; ++i) { + var c = m[i ^ half]; + m[i] = [mid[0] ^ c[0], mid[1] ^ c[1], mid[2] ^ c[2], mid[3] ^ c[3]]; + } + return m; +}; + +/** Utility functions */ + +function transformIV(iv, blockSize) { + if(typeof iv === 'string') { + // convert iv string into byte buffer + iv = forge.util.createBuffer(iv); + } + + if(forge.util.isArray(iv) && iv.length > 4) { + // convert iv byte array into byte buffer + var tmp = iv; + iv = forge.util.createBuffer(); + for(var i = 0; i < tmp.length; ++i) { + iv.putByte(tmp[i]); + } + } + + if(iv.length() < blockSize) { + throw new Error( + 'Invalid IV length; got ' + iv.length() + + ' bytes and expected ' + blockSize + ' bytes.'); + } + + if(!forge.util.isArray(iv)) { + // convert iv byte buffer into 32-bit integer array + var ints = []; + var blocks = blockSize / 4; + for(var i = 0; i < blocks; ++i) { + ints.push(iv.getInt32()); + } + iv = ints; + } + + return iv; +} + +function inc32(block) { + // increment last 32 bits of block only + block[block.length - 1] = (block[block.length - 1] + 1) & 0xFFFFFFFF; +} + +function from64To32(num) { + // convert 64-bit number to two BE Int32s + return [(num / 0x100000000) | 0, num & 0xFFFFFFFF]; +} diff --git a/node_modules/node-forge/lib/debug.js b/node_modules/node-forge/lib/debug.js new file mode 100644 index 0000000..2675635 --- /dev/null +++ b/node_modules/node-forge/lib/debug.js @@ -0,0 +1,78 @@ +/** + * Debugging support for web applications. + * + * @author David I. Lehn + * + * Copyright 2008-2013 Digital Bazaar, Inc. + */ +var forge = require('./forge'); + +/* DEBUG API */ +module.exports = forge.debug = forge.debug || {}; + +// Private storage for debugging. +// Useful to expose data that is otherwise unviewable behind closures. +// NOTE: remember that this can hold references to data and cause leaks! +// format is "forge._debug.. = data" +// Example: +// (function() { +// var cat = 'forge.test.Test'; // debugging category +// var sState = {...}; // local state +// forge.debug.set(cat, 'sState', sState); +// })(); +forge.debug.storage = {}; + +/** + * Gets debug data. Omit name for all cat data Omit name and cat for + * all data. + * + * @param cat name of debugging category. + * @param name name of data to get (optional). + * @return object with requested debug data or undefined. + */ +forge.debug.get = function(cat, name) { + var rval; + if(typeof(cat) === 'undefined') { + rval = forge.debug.storage; + } else if(cat in forge.debug.storage) { + if(typeof(name) === 'undefined') { + rval = forge.debug.storage[cat]; + } else { + rval = forge.debug.storage[cat][name]; + } + } + return rval; +}; + +/** + * Sets debug data. + * + * @param cat name of debugging category. + * @param name name of data to set. + * @param data data to set. + */ +forge.debug.set = function(cat, name, data) { + if(!(cat in forge.debug.storage)) { + forge.debug.storage[cat] = {}; + } + forge.debug.storage[cat][name] = data; +}; + +/** + * Clears debug data. Omit name for all cat data. Omit name and cat for + * all data. + * + * @param cat name of debugging category. + * @param name name of data to clear or omit to clear entire category. + */ +forge.debug.clear = function(cat, name) { + if(typeof(cat) === 'undefined') { + forge.debug.storage = {}; + } else if(cat in forge.debug.storage) { + if(typeof(name) === 'undefined') { + delete forge.debug.storage[cat]; + } else { + delete forge.debug.storage[cat][name]; + } + } +}; diff --git a/node_modules/node-forge/lib/des.js b/node_modules/node-forge/lib/des.js new file mode 100644 index 0000000..ed8239a --- /dev/null +++ b/node_modules/node-forge/lib/des.js @@ -0,0 +1,496 @@ +/** + * DES (Data Encryption Standard) implementation. + * + * This implementation supports DES as well as 3DES-EDE in ECB and CBC mode. + * It is based on the BSD-licensed implementation by Paul Tero: + * + * Paul Tero, July 2001 + * http://www.tero.co.uk/des/ + * + * Optimised for performance with large blocks by + * Michael Hayworth, November 2001 + * http://www.netdealing.com + * + * THIS SOFTWARE IS PROVIDED "AS IS" AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + * + * @author Stefan Siegl + * @author Dave Longley + * + * Copyright (c) 2012 Stefan Siegl + * Copyright (c) 2012-2014 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./cipher'); +require('./cipherModes'); +require('./util'); + +/* DES API */ +module.exports = forge.des = forge.des || {}; + +/** + * Deprecated. Instead, use: + * + * var cipher = forge.cipher.createCipher('DES-', key); + * cipher.start({iv: iv}); + * + * Creates an DES cipher object to encrypt data using the given symmetric key. + * The output will be stored in the 'output' member of the returned cipher. + * + * The key and iv may be given as binary-encoded strings of bytes or + * byte buffers. + * + * @param key the symmetric key to use (64 or 192 bits). + * @param iv the initialization vector to use. + * @param output the buffer to write to, null to create one. + * @param mode the cipher mode to use (default: 'CBC' if IV is + * given, 'ECB' if null). + * + * @return the cipher. + */ +forge.des.startEncrypting = function(key, iv, output, mode) { + var cipher = _createCipher({ + key: key, + output: output, + decrypt: false, + mode: mode || (iv === null ? 'ECB' : 'CBC') + }); + cipher.start(iv); + return cipher; +}; + +/** + * Deprecated. Instead, use: + * + * var cipher = forge.cipher.createCipher('DES-', key); + * + * Creates an DES cipher object to encrypt data using the given symmetric key. + * + * The key may be given as a binary-encoded string of bytes or a byte buffer. + * + * @param key the symmetric key to use (64 or 192 bits). + * @param mode the cipher mode to use (default: 'CBC'). + * + * @return the cipher. + */ +forge.des.createEncryptionCipher = function(key, mode) { + return _createCipher({ + key: key, + output: null, + decrypt: false, + mode: mode + }); +}; + +/** + * Deprecated. Instead, use: + * + * var decipher = forge.cipher.createDecipher('DES-', key); + * decipher.start({iv: iv}); + * + * Creates an DES cipher object to decrypt data using the given symmetric key. + * The output will be stored in the 'output' member of the returned cipher. + * + * The key and iv may be given as binary-encoded strings of bytes or + * byte buffers. + * + * @param key the symmetric key to use (64 or 192 bits). + * @param iv the initialization vector to use. + * @param output the buffer to write to, null to create one. + * @param mode the cipher mode to use (default: 'CBC' if IV is + * given, 'ECB' if null). + * + * @return the cipher. + */ +forge.des.startDecrypting = function(key, iv, output, mode) { + var cipher = _createCipher({ + key: key, + output: output, + decrypt: true, + mode: mode || (iv === null ? 'ECB' : 'CBC') + }); + cipher.start(iv); + return cipher; +}; + +/** + * Deprecated. Instead, use: + * + * var decipher = forge.cipher.createDecipher('DES-', key); + * + * Creates an DES cipher object to decrypt data using the given symmetric key. + * + * The key may be given as a binary-encoded string of bytes or a byte buffer. + * + * @param key the symmetric key to use (64 or 192 bits). + * @param mode the cipher mode to use (default: 'CBC'). + * + * @return the cipher. + */ +forge.des.createDecryptionCipher = function(key, mode) { + return _createCipher({ + key: key, + output: null, + decrypt: true, + mode: mode + }); +}; + +/** + * Creates a new DES cipher algorithm object. + * + * @param name the name of the algorithm. + * @param mode the mode factory function. + * + * @return the DES algorithm object. + */ +forge.des.Algorithm = function(name, mode) { + var self = this; + self.name = name; + self.mode = new mode({ + blockSize: 8, + cipher: { + encrypt: function(inBlock, outBlock) { + return _updateBlock(self._keys, inBlock, outBlock, false); + }, + decrypt: function(inBlock, outBlock) { + return _updateBlock(self._keys, inBlock, outBlock, true); + } + } + }); + self._init = false; +}; + +/** + * Initializes this DES algorithm by expanding its key. + * + * @param options the options to use. + * key the key to use with this algorithm. + * decrypt true if the algorithm should be initialized for decryption, + * false for encryption. + */ +forge.des.Algorithm.prototype.initialize = function(options) { + if(this._init) { + return; + } + + var key = forge.util.createBuffer(options.key); + if(this.name.indexOf('3DES') === 0) { + if(key.length() !== 24) { + throw new Error('Invalid Triple-DES key size: ' + key.length() * 8); + } + } + + // do key expansion to 16 or 48 subkeys (single or triple DES) + this._keys = _createKeys(key); + this._init = true; +}; + +/** Register DES algorithms **/ + +registerAlgorithm('DES-ECB', forge.cipher.modes.ecb); +registerAlgorithm('DES-CBC', forge.cipher.modes.cbc); +registerAlgorithm('DES-CFB', forge.cipher.modes.cfb); +registerAlgorithm('DES-OFB', forge.cipher.modes.ofb); +registerAlgorithm('DES-CTR', forge.cipher.modes.ctr); + +registerAlgorithm('3DES-ECB', forge.cipher.modes.ecb); +registerAlgorithm('3DES-CBC', forge.cipher.modes.cbc); +registerAlgorithm('3DES-CFB', forge.cipher.modes.cfb); +registerAlgorithm('3DES-OFB', forge.cipher.modes.ofb); +registerAlgorithm('3DES-CTR', forge.cipher.modes.ctr); + +function registerAlgorithm(name, mode) { + var factory = function() { + return new forge.des.Algorithm(name, mode); + }; + forge.cipher.registerAlgorithm(name, factory); +} + +/** DES implementation **/ + +var spfunction1 = [0x1010400,0,0x10000,0x1010404,0x1010004,0x10404,0x4,0x10000,0x400,0x1010400,0x1010404,0x400,0x1000404,0x1010004,0x1000000,0x4,0x404,0x1000400,0x1000400,0x10400,0x10400,0x1010000,0x1010000,0x1000404,0x10004,0x1000004,0x1000004,0x10004,0,0x404,0x10404,0x1000000,0x10000,0x1010404,0x4,0x1010000,0x1010400,0x1000000,0x1000000,0x400,0x1010004,0x10000,0x10400,0x1000004,0x400,0x4,0x1000404,0x10404,0x1010404,0x10004,0x1010000,0x1000404,0x1000004,0x404,0x10404,0x1010400,0x404,0x1000400,0x1000400,0,0x10004,0x10400,0,0x1010004]; +var spfunction2 = [-0x7fef7fe0,-0x7fff8000,0x8000,0x108020,0x100000,0x20,-0x7fefffe0,-0x7fff7fe0,-0x7fffffe0,-0x7fef7fe0,-0x7fef8000,-0x80000000,-0x7fff8000,0x100000,0x20,-0x7fefffe0,0x108000,0x100020,-0x7fff7fe0,0,-0x80000000,0x8000,0x108020,-0x7ff00000,0x100020,-0x7fffffe0,0,0x108000,0x8020,-0x7fef8000,-0x7ff00000,0x8020,0,0x108020,-0x7fefffe0,0x100000,-0x7fff7fe0,-0x7ff00000,-0x7fef8000,0x8000,-0x7ff00000,-0x7fff8000,0x20,-0x7fef7fe0,0x108020,0x20,0x8000,-0x80000000,0x8020,-0x7fef8000,0x100000,-0x7fffffe0,0x100020,-0x7fff7fe0,-0x7fffffe0,0x100020,0x108000,0,-0x7fff8000,0x8020,-0x80000000,-0x7fefffe0,-0x7fef7fe0,0x108000]; +var spfunction3 = [0x208,0x8020200,0,0x8020008,0x8000200,0,0x20208,0x8000200,0x20008,0x8000008,0x8000008,0x20000,0x8020208,0x20008,0x8020000,0x208,0x8000000,0x8,0x8020200,0x200,0x20200,0x8020000,0x8020008,0x20208,0x8000208,0x20200,0x20000,0x8000208,0x8,0x8020208,0x200,0x8000000,0x8020200,0x8000000,0x20008,0x208,0x20000,0x8020200,0x8000200,0,0x200,0x20008,0x8020208,0x8000200,0x8000008,0x200,0,0x8020008,0x8000208,0x20000,0x8000000,0x8020208,0x8,0x20208,0x20200,0x8000008,0x8020000,0x8000208,0x208,0x8020000,0x20208,0x8,0x8020008,0x20200]; +var spfunction4 = [0x802001,0x2081,0x2081,0x80,0x802080,0x800081,0x800001,0x2001,0,0x802000,0x802000,0x802081,0x81,0,0x800080,0x800001,0x1,0x2000,0x800000,0x802001,0x80,0x800000,0x2001,0x2080,0x800081,0x1,0x2080,0x800080,0x2000,0x802080,0x802081,0x81,0x800080,0x800001,0x802000,0x802081,0x81,0,0,0x802000,0x2080,0x800080,0x800081,0x1,0x802001,0x2081,0x2081,0x80,0x802081,0x81,0x1,0x2000,0x800001,0x2001,0x802080,0x800081,0x2001,0x2080,0x800000,0x802001,0x80,0x800000,0x2000,0x802080]; +var spfunction5 = [0x100,0x2080100,0x2080000,0x42000100,0x80000,0x100,0x40000000,0x2080000,0x40080100,0x80000,0x2000100,0x40080100,0x42000100,0x42080000,0x80100,0x40000000,0x2000000,0x40080000,0x40080000,0,0x40000100,0x42080100,0x42080100,0x2000100,0x42080000,0x40000100,0,0x42000000,0x2080100,0x2000000,0x42000000,0x80100,0x80000,0x42000100,0x100,0x2000000,0x40000000,0x2080000,0x42000100,0x40080100,0x2000100,0x40000000,0x42080000,0x2080100,0x40080100,0x100,0x2000000,0x42080000,0x42080100,0x80100,0x42000000,0x42080100,0x2080000,0,0x40080000,0x42000000,0x80100,0x2000100,0x40000100,0x80000,0,0x40080000,0x2080100,0x40000100]; +var spfunction6 = [0x20000010,0x20400000,0x4000,0x20404010,0x20400000,0x10,0x20404010,0x400000,0x20004000,0x404010,0x400000,0x20000010,0x400010,0x20004000,0x20000000,0x4010,0,0x400010,0x20004010,0x4000,0x404000,0x20004010,0x10,0x20400010,0x20400010,0,0x404010,0x20404000,0x4010,0x404000,0x20404000,0x20000000,0x20004000,0x10,0x20400010,0x404000,0x20404010,0x400000,0x4010,0x20000010,0x400000,0x20004000,0x20000000,0x4010,0x20000010,0x20404010,0x404000,0x20400000,0x404010,0x20404000,0,0x20400010,0x10,0x4000,0x20400000,0x404010,0x4000,0x400010,0x20004010,0,0x20404000,0x20000000,0x400010,0x20004010]; +var spfunction7 = [0x200000,0x4200002,0x4000802,0,0x800,0x4000802,0x200802,0x4200800,0x4200802,0x200000,0,0x4000002,0x2,0x4000000,0x4200002,0x802,0x4000800,0x200802,0x200002,0x4000800,0x4000002,0x4200000,0x4200800,0x200002,0x4200000,0x800,0x802,0x4200802,0x200800,0x2,0x4000000,0x200800,0x4000000,0x200800,0x200000,0x4000802,0x4000802,0x4200002,0x4200002,0x2,0x200002,0x4000000,0x4000800,0x200000,0x4200800,0x802,0x200802,0x4200800,0x802,0x4000002,0x4200802,0x4200000,0x200800,0,0x2,0x4200802,0,0x200802,0x4200000,0x800,0x4000002,0x4000800,0x800,0x200002]; +var spfunction8 = [0x10001040,0x1000,0x40000,0x10041040,0x10000000,0x10001040,0x40,0x10000000,0x40040,0x10040000,0x10041040,0x41000,0x10041000,0x41040,0x1000,0x40,0x10040000,0x10000040,0x10001000,0x1040,0x41000,0x40040,0x10040040,0x10041000,0x1040,0,0,0x10040040,0x10000040,0x10001000,0x41040,0x40000,0x41040,0x40000,0x10041000,0x1000,0x40,0x10040040,0x1000,0x41040,0x10001000,0x40,0x10000040,0x10040000,0x10040040,0x10000000,0x40000,0x10001040,0,0x10041040,0x40040,0x10000040,0x10040000,0x10001000,0x10001040,0,0x10041040,0x41000,0x41000,0x1040,0x1040,0x40040,0x10000000,0x10041000]; + +/** + * Create necessary sub keys. + * + * @param key the 64-bit or 192-bit key. + * + * @return the expanded keys. + */ +function _createKeys(key) { + var pc2bytes0 = [0,0x4,0x20000000,0x20000004,0x10000,0x10004,0x20010000,0x20010004,0x200,0x204,0x20000200,0x20000204,0x10200,0x10204,0x20010200,0x20010204], + pc2bytes1 = [0,0x1,0x100000,0x100001,0x4000000,0x4000001,0x4100000,0x4100001,0x100,0x101,0x100100,0x100101,0x4000100,0x4000101,0x4100100,0x4100101], + pc2bytes2 = [0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808,0,0x8,0x800,0x808,0x1000000,0x1000008,0x1000800,0x1000808], + pc2bytes3 = [0,0x200000,0x8000000,0x8200000,0x2000,0x202000,0x8002000,0x8202000,0x20000,0x220000,0x8020000,0x8220000,0x22000,0x222000,0x8022000,0x8222000], + pc2bytes4 = [0,0x40000,0x10,0x40010,0,0x40000,0x10,0x40010,0x1000,0x41000,0x1010,0x41010,0x1000,0x41000,0x1010,0x41010], + pc2bytes5 = [0,0x400,0x20,0x420,0,0x400,0x20,0x420,0x2000000,0x2000400,0x2000020,0x2000420,0x2000000,0x2000400,0x2000020,0x2000420], + pc2bytes6 = [0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002,0,0x10000000,0x80000,0x10080000,0x2,0x10000002,0x80002,0x10080002], + pc2bytes7 = [0,0x10000,0x800,0x10800,0x20000000,0x20010000,0x20000800,0x20010800,0x20000,0x30000,0x20800,0x30800,0x20020000,0x20030000,0x20020800,0x20030800], + pc2bytes8 = [0,0x40000,0,0x40000,0x2,0x40002,0x2,0x40002,0x2000000,0x2040000,0x2000000,0x2040000,0x2000002,0x2040002,0x2000002,0x2040002], + pc2bytes9 = [0,0x10000000,0x8,0x10000008,0,0x10000000,0x8,0x10000008,0x400,0x10000400,0x408,0x10000408,0x400,0x10000400,0x408,0x10000408], + pc2bytes10 = [0,0x20,0,0x20,0x100000,0x100020,0x100000,0x100020,0x2000,0x2020,0x2000,0x2020,0x102000,0x102020,0x102000,0x102020], + pc2bytes11 = [0,0x1000000,0x200,0x1000200,0x200000,0x1200000,0x200200,0x1200200,0x4000000,0x5000000,0x4000200,0x5000200,0x4200000,0x5200000,0x4200200,0x5200200], + pc2bytes12 = [0,0x1000,0x8000000,0x8001000,0x80000,0x81000,0x8080000,0x8081000,0x10,0x1010,0x8000010,0x8001010,0x80010,0x81010,0x8080010,0x8081010], + pc2bytes13 = [0,0x4,0x100,0x104,0,0x4,0x100,0x104,0x1,0x5,0x101,0x105,0x1,0x5,0x101,0x105]; + + // how many iterations (1 for des, 3 for triple des) + // changed by Paul 16/6/2007 to use Triple DES for 9+ byte keys + var iterations = key.length() > 8 ? 3 : 1; + + // stores the return keys + var keys = []; + + // now define the left shifts which need to be done + var shifts = [0, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0]; + + var n = 0, tmp; + for(var j = 0; j < iterations; j++) { + var left = key.getInt32(); + var right = key.getInt32(); + + tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f; + right ^= tmp; + left ^= (tmp << 4); + + tmp = ((right >>> -16) ^ left) & 0x0000ffff; + left ^= tmp; + right ^= (tmp << -16); + + tmp = ((left >>> 2) ^ right) & 0x33333333; + right ^= tmp; + left ^= (tmp << 2); + + tmp = ((right >>> -16) ^ left) & 0x0000ffff; + left ^= tmp; + right ^= (tmp << -16); + + tmp = ((left >>> 1) ^ right) & 0x55555555; + right ^= tmp; + left ^= (tmp << 1); + + tmp = ((right >>> 8) ^ left) & 0x00ff00ff; + left ^= tmp; + right ^= (tmp << 8); + + tmp = ((left >>> 1) ^ right) & 0x55555555; + right ^= tmp; + left ^= (tmp << 1); + + // right needs to be shifted and OR'd with last four bits of left + tmp = (left << 8) | ((right >>> 20) & 0x000000f0); + + // left needs to be put upside down + left = ((right << 24) | ((right << 8) & 0xff0000) | + ((right >>> 8) & 0xff00) | ((right >>> 24) & 0xf0)); + right = tmp; + + // now go through and perform these shifts on the left and right keys + for(var i = 0; i < shifts.length; ++i) { + //shift the keys either one or two bits to the left + if(shifts[i]) { + left = (left << 2) | (left >>> 26); + right = (right << 2) | (right >>> 26); + } else { + left = (left << 1) | (left >>> 27); + right = (right << 1) | (right >>> 27); + } + left &= -0xf; + right &= -0xf; + + // now apply PC-2, in such a way that E is easier when encrypting or + // decrypting this conversion will look like PC-2 except only the last 6 + // bits of each byte are used rather than 48 consecutive bits and the + // order of lines will be according to how the S selection functions will + // be applied: S2, S4, S6, S8, S1, S3, S5, S7 + var lefttmp = ( + pc2bytes0[left >>> 28] | pc2bytes1[(left >>> 24) & 0xf] | + pc2bytes2[(left >>> 20) & 0xf] | pc2bytes3[(left >>> 16) & 0xf] | + pc2bytes4[(left >>> 12) & 0xf] | pc2bytes5[(left >>> 8) & 0xf] | + pc2bytes6[(left >>> 4) & 0xf]); + var righttmp = ( + pc2bytes7[right >>> 28] | pc2bytes8[(right >>> 24) & 0xf] | + pc2bytes9[(right >>> 20) & 0xf] | pc2bytes10[(right >>> 16) & 0xf] | + pc2bytes11[(right >>> 12) & 0xf] | pc2bytes12[(right >>> 8) & 0xf] | + pc2bytes13[(right >>> 4) & 0xf]); + tmp = ((righttmp >>> 16) ^ lefttmp) & 0x0000ffff; + keys[n++] = lefttmp ^ tmp; + keys[n++] = righttmp ^ (tmp << 16); + } + } + + return keys; +} + +/** + * Updates a single block (1 byte) using DES. The update will either + * encrypt or decrypt the block. + * + * @param keys the expanded keys. + * @param input the input block (an array of 32-bit words). + * @param output the updated output block. + * @param decrypt true to decrypt the block, false to encrypt it. + */ +function _updateBlock(keys, input, output, decrypt) { + // set up loops for single or triple DES + var iterations = keys.length === 32 ? 3 : 9; + var looping; + if(iterations === 3) { + looping = decrypt ? [30, -2, -2] : [0, 32, 2]; + } else { + looping = (decrypt ? + [94, 62, -2, 32, 64, 2, 30, -2, -2] : + [0, 32, 2, 62, 30, -2, 64, 96, 2]); + } + + var tmp; + + var left = input[0]; + var right = input[1]; + + // first each 64 bit chunk of the message must be permuted according to IP + tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f; + right ^= tmp; + left ^= (tmp << 4); + + tmp = ((left >>> 16) ^ right) & 0x0000ffff; + right ^= tmp; + left ^= (tmp << 16); + + tmp = ((right >>> 2) ^ left) & 0x33333333; + left ^= tmp; + right ^= (tmp << 2); + + tmp = ((right >>> 8) ^ left) & 0x00ff00ff; + left ^= tmp; + right ^= (tmp << 8); + + tmp = ((left >>> 1) ^ right) & 0x55555555; + right ^= tmp; + left ^= (tmp << 1); + + // rotate left 1 bit + left = ((left << 1) | (left >>> 31)); + right = ((right << 1) | (right >>> 31)); + + for(var j = 0; j < iterations; j += 3) { + var endloop = looping[j + 1]; + var loopinc = looping[j + 2]; + + // now go through and perform the encryption or decryption + for(var i = looping[j]; i != endloop; i += loopinc) { + var right1 = right ^ keys[i]; + var right2 = ((right >>> 4) | (right << 28)) ^ keys[i + 1]; + + // passing these bytes through the S selection functions + tmp = left; + left = right; + right = tmp ^ ( + spfunction2[(right1 >>> 24) & 0x3f] | + spfunction4[(right1 >>> 16) & 0x3f] | + spfunction6[(right1 >>> 8) & 0x3f] | + spfunction8[right1 & 0x3f] | + spfunction1[(right2 >>> 24) & 0x3f] | + spfunction3[(right2 >>> 16) & 0x3f] | + spfunction5[(right2 >>> 8) & 0x3f] | + spfunction7[right2 & 0x3f]); + } + // unreverse left and right + tmp = left; + left = right; + right = tmp; + } + + // rotate right 1 bit + left = ((left >>> 1) | (left << 31)); + right = ((right >>> 1) | (right << 31)); + + // now perform IP-1, which is IP in the opposite direction + tmp = ((left >>> 1) ^ right) & 0x55555555; + right ^= tmp; + left ^= (tmp << 1); + + tmp = ((right >>> 8) ^ left) & 0x00ff00ff; + left ^= tmp; + right ^= (tmp << 8); + + tmp = ((right >>> 2) ^ left) & 0x33333333; + left ^= tmp; + right ^= (tmp << 2); + + tmp = ((left >>> 16) ^ right) & 0x0000ffff; + right ^= tmp; + left ^= (tmp << 16); + + tmp = ((left >>> 4) ^ right) & 0x0f0f0f0f; + right ^= tmp; + left ^= (tmp << 4); + + output[0] = left; + output[1] = right; +} + +/** + * Deprecated. Instead, use: + * + * forge.cipher.createCipher('DES-', key); + * forge.cipher.createDecipher('DES-', key); + * + * Creates a deprecated DES cipher object. This object's mode will default to + * CBC (cipher-block-chaining). + * + * The key may be given as a binary-encoded string of bytes or a byte buffer. + * + * @param options the options to use. + * key the symmetric key to use (64 or 192 bits). + * output the buffer to write to. + * decrypt true for decryption, false for encryption. + * mode the cipher mode to use (default: 'CBC'). + * + * @return the cipher. + */ +function _createCipher(options) { + options = options || {}; + var mode = (options.mode || 'CBC').toUpperCase(); + var algorithm = 'DES-' + mode; + + var cipher; + if(options.decrypt) { + cipher = forge.cipher.createDecipher(algorithm, options.key); + } else { + cipher = forge.cipher.createCipher(algorithm, options.key); + } + + // backwards compatible start API + var start = cipher.start; + cipher.start = function(iv, options) { + // backwards compatibility: support second arg as output buffer + var output = null; + if(options instanceof forge.util.ByteBuffer) { + output = options; + options = {}; + } + options = options || {}; + options.output = output; + options.iv = iv; + start.call(cipher, options); + }; + + return cipher; +} diff --git a/node_modules/node-forge/lib/ed25519.js b/node_modules/node-forge/lib/ed25519.js new file mode 100644 index 0000000..f3e6faa --- /dev/null +++ b/node_modules/node-forge/lib/ed25519.js @@ -0,0 +1,1072 @@ +/** + * JavaScript implementation of Ed25519. + * + * Copyright (c) 2017-2019 Digital Bazaar, Inc. + * + * This implementation is based on the most excellent TweetNaCl which is + * in the public domain. Many thanks to its contributors: + * + * https://github.com/dchest/tweetnacl-js + */ +var forge = require('./forge'); +require('./jsbn'); +require('./random'); +require('./sha512'); +require('./util'); +var asn1Validator = require('./asn1-validator'); +var publicKeyValidator = asn1Validator.publicKeyValidator; +var privateKeyValidator = asn1Validator.privateKeyValidator; + +if(typeof BigInteger === 'undefined') { + var BigInteger = forge.jsbn.BigInteger; +} + +var ByteBuffer = forge.util.ByteBuffer; +var NativeBuffer = typeof Buffer === 'undefined' ? Uint8Array : Buffer; + +/* + * Ed25519 algorithms, see RFC 8032: + * https://tools.ietf.org/html/rfc8032 + */ +forge.pki = forge.pki || {}; +module.exports = forge.pki.ed25519 = forge.ed25519 = forge.ed25519 || {}; +var ed25519 = forge.ed25519; + +ed25519.constants = {}; +ed25519.constants.PUBLIC_KEY_BYTE_LENGTH = 32; +ed25519.constants.PRIVATE_KEY_BYTE_LENGTH = 64; +ed25519.constants.SEED_BYTE_LENGTH = 32; +ed25519.constants.SIGN_BYTE_LENGTH = 64; +ed25519.constants.HASH_BYTE_LENGTH = 64; + +ed25519.generateKeyPair = function(options) { + options = options || {}; + var seed = options.seed; + if(seed === undefined) { + // generate seed + seed = forge.random.getBytesSync(ed25519.constants.SEED_BYTE_LENGTH); + } else if(typeof seed === 'string') { + if(seed.length !== ed25519.constants.SEED_BYTE_LENGTH) { + throw new TypeError( + '"seed" must be ' + ed25519.constants.SEED_BYTE_LENGTH + + ' bytes in length.'); + } + } else if(!(seed instanceof Uint8Array)) { + throw new TypeError( + '"seed" must be a node.js Buffer, Uint8Array, or a binary string.'); + } + + seed = messageToNativeBuffer({message: seed, encoding: 'binary'}); + + var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); + var sk = new NativeBuffer(ed25519.constants.PRIVATE_KEY_BYTE_LENGTH); + for(var i = 0; i < 32; ++i) { + sk[i] = seed[i]; + } + crypto_sign_keypair(pk, sk); + return {publicKey: pk, privateKey: sk}; +}; + +/** + * Converts a private key from a RFC8410 ASN.1 encoding. + * + * @param obj - The asn1 representation of a private key. + * + * @returns {Object} keyInfo - The key information. + * @returns {Buffer|Uint8Array} keyInfo.privateKeyBytes - 32 private key bytes. + */ +ed25519.privateKeyFromAsn1 = function(obj) { + var capture = {}; + var errors = []; + var valid = forge.asn1.validate(obj, privateKeyValidator, capture, errors); + if(!valid) { + var error = new Error('Invalid Key.'); + error.errors = errors; + throw error; + } + var oid = forge.asn1.derToOid(capture.privateKeyOid); + var ed25519Oid = forge.oids.EdDSA25519; + if(oid !== ed25519Oid) { + throw new Error('Invalid OID "' + oid + '"; OID must be "' + + ed25519Oid + '".'); + } + var privateKey = capture.privateKey; + // manually extract the private key bytes from nested octet string, see FIXME: + // https://github.com/digitalbazaar/forge/blob/master/lib/asn1.js#L542 + var privateKeyBytes = messageToNativeBuffer({ + message: forge.asn1.fromDer(privateKey).value, + encoding: 'binary' + }); + // TODO: RFC8410 specifies a format for encoding the public key bytes along + // with the private key bytes. `publicKeyBytes` can be returned in the + // future. https://tools.ietf.org/html/rfc8410#section-10.3 + return {privateKeyBytes: privateKeyBytes}; +}; + +/** + * Converts a public key from a RFC8410 ASN.1 encoding. + * + * @param obj - The asn1 representation of a public key. + * + * @return {Buffer|Uint8Array} - 32 public key bytes. + */ +ed25519.publicKeyFromAsn1 = function(obj) { + // get SubjectPublicKeyInfo + var capture = {}; + var errors = []; + var valid = forge.asn1.validate(obj, publicKeyValidator, capture, errors); + if(!valid) { + var error = new Error('Invalid Key.'); + error.errors = errors; + throw error; + } + var oid = forge.asn1.derToOid(capture.publicKeyOid); + var ed25519Oid = forge.oids.EdDSA25519; + if(oid !== ed25519Oid) { + throw new Error('Invalid OID "' + oid + '"; OID must be "' + + ed25519Oid + '".'); + } + var publicKeyBytes = capture.ed25519PublicKey; + if(publicKeyBytes.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) { + throw new Error('Key length is invalid.'); + } + return messageToNativeBuffer({ + message: publicKeyBytes, + encoding: 'binary' + }); +}; + +ed25519.publicKeyFromPrivateKey = function(options) { + options = options || {}; + var privateKey = messageToNativeBuffer({ + message: options.privateKey, encoding: 'binary' + }); + if(privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) { + throw new TypeError( + '"options.privateKey" must have a byte length of ' + + ed25519.constants.PRIVATE_KEY_BYTE_LENGTH); + } + + var pk = new NativeBuffer(ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); + for(var i = 0; i < pk.length; ++i) { + pk[i] = privateKey[32 + i]; + } + return pk; +}; + +ed25519.sign = function(options) { + options = options || {}; + var msg = messageToNativeBuffer(options); + var privateKey = messageToNativeBuffer({ + message: options.privateKey, + encoding: 'binary' + }); + if(privateKey.length === ed25519.constants.SEED_BYTE_LENGTH) { + var keyPair = ed25519.generateKeyPair({seed: privateKey}); + privateKey = keyPair.privateKey; + } else if(privateKey.length !== ed25519.constants.PRIVATE_KEY_BYTE_LENGTH) { + throw new TypeError( + '"options.privateKey" must have a byte length of ' + + ed25519.constants.SEED_BYTE_LENGTH + ' or ' + + ed25519.constants.PRIVATE_KEY_BYTE_LENGTH); + } + + var signedMsg = new NativeBuffer( + ed25519.constants.SIGN_BYTE_LENGTH + msg.length); + crypto_sign(signedMsg, msg, msg.length, privateKey); + + var sig = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH); + for(var i = 0; i < sig.length; ++i) { + sig[i] = signedMsg[i]; + } + return sig; +}; + +ed25519.verify = function(options) { + options = options || {}; + var msg = messageToNativeBuffer(options); + if(options.signature === undefined) { + throw new TypeError( + '"options.signature" must be a node.js Buffer, a Uint8Array, a forge ' + + 'ByteBuffer, or a binary string.'); + } + var sig = messageToNativeBuffer({ + message: options.signature, + encoding: 'binary' + }); + if(sig.length !== ed25519.constants.SIGN_BYTE_LENGTH) { + throw new TypeError( + '"options.signature" must have a byte length of ' + + ed25519.constants.SIGN_BYTE_LENGTH); + } + var publicKey = messageToNativeBuffer({ + message: options.publicKey, + encoding: 'binary' + }); + if(publicKey.length !== ed25519.constants.PUBLIC_KEY_BYTE_LENGTH) { + throw new TypeError( + '"options.publicKey" must have a byte length of ' + + ed25519.constants.PUBLIC_KEY_BYTE_LENGTH); + } + + var sm = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length); + var m = new NativeBuffer(ed25519.constants.SIGN_BYTE_LENGTH + msg.length); + var i; + for(i = 0; i < ed25519.constants.SIGN_BYTE_LENGTH; ++i) { + sm[i] = sig[i]; + } + for(i = 0; i < msg.length; ++i) { + sm[i + ed25519.constants.SIGN_BYTE_LENGTH] = msg[i]; + } + return (crypto_sign_open(m, sm, sm.length, publicKey) >= 0); +}; + +function messageToNativeBuffer(options) { + var message = options.message; + if(message instanceof Uint8Array || message instanceof NativeBuffer) { + return message; + } + + var encoding = options.encoding; + if(message === undefined) { + if(options.md) { + // TODO: more rigorous validation that `md` is a MessageDigest + message = options.md.digest().getBytes(); + encoding = 'binary'; + } else { + throw new TypeError('"options.message" or "options.md" not specified.'); + } + } + + if(typeof message === 'string' && !encoding) { + throw new TypeError('"options.encoding" must be "binary" or "utf8".'); + } + + if(typeof message === 'string') { + if(typeof Buffer !== 'undefined') { + return Buffer.from(message, encoding); + } + message = new ByteBuffer(message, encoding); + } else if(!(message instanceof ByteBuffer)) { + throw new TypeError( + '"options.message" must be a node.js Buffer, a Uint8Array, a forge ' + + 'ByteBuffer, or a string with "options.encoding" specifying its ' + + 'encoding.'); + } + + // convert to native buffer + var buffer = new NativeBuffer(message.length()); + for(var i = 0; i < buffer.length; ++i) { + buffer[i] = message.at(i); + } + return buffer; +} + +var gf0 = gf(); +var gf1 = gf([1]); +var D = gf([ + 0x78a3, 0x1359, 0x4dca, 0x75eb, 0xd8ab, 0x4141, 0x0a4d, 0x0070, + 0xe898, 0x7779, 0x4079, 0x8cc7, 0xfe73, 0x2b6f, 0x6cee, 0x5203]); +var D2 = gf([ + 0xf159, 0x26b2, 0x9b94, 0xebd6, 0xb156, 0x8283, 0x149a, 0x00e0, + 0xd130, 0xeef3, 0x80f2, 0x198e, 0xfce7, 0x56df, 0xd9dc, 0x2406]); +var X = gf([ + 0xd51a, 0x8f25, 0x2d60, 0xc956, 0xa7b2, 0x9525, 0xc760, 0x692c, + 0xdc5c, 0xfdd6, 0xe231, 0xc0a4, 0x53fe, 0xcd6e, 0x36d3, 0x2169]); +var Y = gf([ + 0x6658, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, + 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666, 0x6666]); +var L = new Float64Array([ + 0xed, 0xd3, 0xf5, 0x5c, 0x1a, 0x63, 0x12, 0x58, + 0xd6, 0x9c, 0xf7, 0xa2, 0xde, 0xf9, 0xde, 0x14, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x10]); +var I = gf([ + 0xa0b0, 0x4a0e, 0x1b27, 0xc4ee, 0xe478, 0xad2f, 0x1806, 0x2f43, + 0xd7a7, 0x3dfb, 0x0099, 0x2b4d, 0xdf0b, 0x4fc1, 0x2480, 0x2b83]); + +// TODO: update forge buffer implementation to use `Buffer` or `Uint8Array`, +// whichever is available, to improve performance +function sha512(msg, msgLen) { + // Note: `out` and `msg` are NativeBuffer + var md = forge.md.sha512.create(); + var buffer = new ByteBuffer(msg); + md.update(buffer.getBytes(msgLen), 'binary'); + var hash = md.digest().getBytes(); + if(typeof Buffer !== 'undefined') { + return Buffer.from(hash, 'binary'); + } + var out = new NativeBuffer(ed25519.constants.HASH_BYTE_LENGTH); + for(var i = 0; i < 64; ++i) { + out[i] = hash.charCodeAt(i); + } + return out; +} + +function crypto_sign_keypair(pk, sk) { + var p = [gf(), gf(), gf(), gf()]; + var i; + + var d = sha512(sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + + scalarbase(p, d); + pack(pk, p); + + for(i = 0; i < 32; ++i) { + sk[i + 32] = pk[i]; + } + return 0; +} + +// Note: difference from C - smlen returned, not passed as argument. +function crypto_sign(sm, m, n, sk) { + var i, j, x = new Float64Array(64); + var p = [gf(), gf(), gf(), gf()]; + + var d = sha512(sk, 32); + d[0] &= 248; + d[31] &= 127; + d[31] |= 64; + + var smlen = n + 64; + for(i = 0; i < n; ++i) { + sm[64 + i] = m[i]; + } + for(i = 0; i < 32; ++i) { + sm[32 + i] = d[32 + i]; + } + + var r = sha512(sm.subarray(32), n + 32); + reduce(r); + scalarbase(p, r); + pack(sm, p); + + for(i = 32; i < 64; ++i) { + sm[i] = sk[i]; + } + var h = sha512(sm, n + 64); + reduce(h); + + for(i = 32; i < 64; ++i) { + x[i] = 0; + } + for(i = 0; i < 32; ++i) { + x[i] = r[i]; + } + for(i = 0; i < 32; ++i) { + for(j = 0; j < 32; j++) { + x[i + j] += h[i] * d[j]; + } + } + + modL(sm.subarray(32), x); + return smlen; +} + +function crypto_sign_open(m, sm, n, pk) { + var i, mlen; + var t = new NativeBuffer(32); + var p = [gf(), gf(), gf(), gf()], + q = [gf(), gf(), gf(), gf()]; + + mlen = -1; + if(n < 64) { + return -1; + } + + if(unpackneg(q, pk)) { + return -1; + } + + for(i = 0; i < n; ++i) { + m[i] = sm[i]; + } + for(i = 0; i < 32; ++i) { + m[i + 32] = pk[i]; + } + var h = sha512(m, n); + reduce(h); + scalarmult(p, q, h); + + scalarbase(q, sm.subarray(32)); + add(p, q); + pack(t, p); + + n -= 64; + if(crypto_verify_32(sm, 0, t, 0)) { + for(i = 0; i < n; ++i) { + m[i] = 0; + } + return -1; + } + + for(i = 0; i < n; ++i) { + m[i] = sm[i + 64]; + } + mlen = n; + return mlen; +} + +function modL(r, x) { + var carry, i, j, k; + for(i = 63; i >= 32; --i) { + carry = 0; + for(j = i - 32, k = i - 12; j < k; ++j) { + x[j] += carry - 16 * x[i] * L[j - (i - 32)]; + carry = (x[j] + 128) >> 8; + x[j] -= carry * 256; + } + x[j] += carry; + x[i] = 0; + } + carry = 0; + for(j = 0; j < 32; ++j) { + x[j] += carry - (x[31] >> 4) * L[j]; + carry = x[j] >> 8; + x[j] &= 255; + } + for(j = 0; j < 32; ++j) { + x[j] -= carry * L[j]; + } + for(i = 0; i < 32; ++i) { + x[i + 1] += x[i] >> 8; + r[i] = x[i] & 255; + } +} + +function reduce(r) { + var x = new Float64Array(64); + for(var i = 0; i < 64; ++i) { + x[i] = r[i]; + r[i] = 0; + } + modL(r, x); +} + +function add(p, q) { + var a = gf(), b = gf(), c = gf(), + d = gf(), e = gf(), f = gf(), + g = gf(), h = gf(), t = gf(); + + Z(a, p[1], p[0]); + Z(t, q[1], q[0]); + M(a, a, t); + A(b, p[0], p[1]); + A(t, q[0], q[1]); + M(b, b, t); + M(c, p[3], q[3]); + M(c, c, D2); + M(d, p[2], q[2]); + A(d, d, d); + Z(e, b, a); + Z(f, d, c); + A(g, d, c); + A(h, b, a); + + M(p[0], e, f); + M(p[1], h, g); + M(p[2], g, f); + M(p[3], e, h); +} + +function cswap(p, q, b) { + for(var i = 0; i < 4; ++i) { + sel25519(p[i], q[i], b); + } +} + +function pack(r, p) { + var tx = gf(), ty = gf(), zi = gf(); + inv25519(zi, p[2]); + M(tx, p[0], zi); + M(ty, p[1], zi); + pack25519(r, ty); + r[31] ^= par25519(tx) << 7; +} + +function pack25519(o, n) { + var i, j, b; + var m = gf(), t = gf(); + for(i = 0; i < 16; ++i) { + t[i] = n[i]; + } + car25519(t); + car25519(t); + car25519(t); + for(j = 0; j < 2; ++j) { + m[0] = t[0] - 0xffed; + for(i = 1; i < 15; ++i) { + m[i] = t[i] - 0xffff - ((m[i - 1] >> 16) & 1); + m[i-1] &= 0xffff; + } + m[15] = t[15] - 0x7fff - ((m[14] >> 16) & 1); + b = (m[15] >> 16) & 1; + m[14] &= 0xffff; + sel25519(t, m, 1 - b); + } + for (i = 0; i < 16; i++) { + o[2 * i] = t[i] & 0xff; + o[2 * i + 1] = t[i] >> 8; + } +} + +function unpackneg(r, p) { + var t = gf(), chk = gf(), num = gf(), + den = gf(), den2 = gf(), den4 = gf(), + den6 = gf(); + + set25519(r[2], gf1); + unpack25519(r[1], p); + S(num, r[1]); + M(den, num, D); + Z(num, num, r[2]); + A(den, r[2], den); + + S(den2, den); + S(den4, den2); + M(den6, den4, den2); + M(t, den6, num); + M(t, t, den); + + pow2523(t, t); + M(t, t, num); + M(t, t, den); + M(t, t, den); + M(r[0], t, den); + + S(chk, r[0]); + M(chk, chk, den); + if(neq25519(chk, num)) { + M(r[0], r[0], I); + } + + S(chk, r[0]); + M(chk, chk, den); + if(neq25519(chk, num)) { + return -1; + } + + if(par25519(r[0]) === (p[31] >> 7)) { + Z(r[0], gf0, r[0]); + } + + M(r[3], r[0], r[1]); + return 0; +} + +function unpack25519(o, n) { + var i; + for(i = 0; i < 16; ++i) { + o[i] = n[2 * i] + (n[2 * i + 1] << 8); + } + o[15] &= 0x7fff; +} + +function pow2523(o, i) { + var c = gf(); + var a; + for(a = 0; a < 16; ++a) { + c[a] = i[a]; + } + for(a = 250; a >= 0; --a) { + S(c, c); + if(a !== 1) { + M(c, c, i); + } + } + for(a = 0; a < 16; ++a) { + o[a] = c[a]; + } +} + +function neq25519(a, b) { + var c = new NativeBuffer(32); + var d = new NativeBuffer(32); + pack25519(c, a); + pack25519(d, b); + return crypto_verify_32(c, 0, d, 0); +} + +function crypto_verify_32(x, xi, y, yi) { + return vn(x, xi, y, yi, 32); +} + +function vn(x, xi, y, yi, n) { + var i, d = 0; + for(i = 0; i < n; ++i) { + d |= x[xi + i] ^ y[yi + i]; + } + return (1 & ((d - 1) >>> 8)) - 1; +} + +function par25519(a) { + var d = new NativeBuffer(32); + pack25519(d, a); + return d[0] & 1; +} + +function scalarmult(p, q, s) { + var b, i; + set25519(p[0], gf0); + set25519(p[1], gf1); + set25519(p[2], gf1); + set25519(p[3], gf0); + for(i = 255; i >= 0; --i) { + b = (s[(i / 8)|0] >> (i & 7)) & 1; + cswap(p, q, b); + add(q, p); + add(p, p); + cswap(p, q, b); + } +} + +function scalarbase(p, s) { + var q = [gf(), gf(), gf(), gf()]; + set25519(q[0], X); + set25519(q[1], Y); + set25519(q[2], gf1); + M(q[3], X, Y); + scalarmult(p, q, s); +} + +function set25519(r, a) { + var i; + for(i = 0; i < 16; i++) { + r[i] = a[i] | 0; + } +} + +function inv25519(o, i) { + var c = gf(); + var a; + for(a = 0; a < 16; ++a) { + c[a] = i[a]; + } + for(a = 253; a >= 0; --a) { + S(c, c); + if(a !== 2 && a !== 4) { + M(c, c, i); + } + } + for(a = 0; a < 16; ++a) { + o[a] = c[a]; + } +} + +function car25519(o) { + var i, v, c = 1; + for(i = 0; i < 16; ++i) { + v = o[i] + c + 65535; + c = Math.floor(v / 65536); + o[i] = v - c * 65536; + } + o[0] += c - 1 + 37 * (c - 1); +} + +function sel25519(p, q, b) { + var t, c = ~(b - 1); + for(var i = 0; i < 16; ++i) { + t = c & (p[i] ^ q[i]); + p[i] ^= t; + q[i] ^= t; + } +} + +function gf(init) { + var i, r = new Float64Array(16); + if(init) { + for(i = 0; i < init.length; ++i) { + r[i] = init[i]; + } + } + return r; +} + +function A(o, a, b) { + for(var i = 0; i < 16; ++i) { + o[i] = a[i] + b[i]; + } +} + +function Z(o, a, b) { + for(var i = 0; i < 16; ++i) { + o[i] = a[i] - b[i]; + } +} + +function S(o, a) { + M(o, a, a); +} + +function M(o, a, b) { + var v, c, + t0 = 0, t1 = 0, t2 = 0, t3 = 0, t4 = 0, t5 = 0, t6 = 0, t7 = 0, + t8 = 0, t9 = 0, t10 = 0, t11 = 0, t12 = 0, t13 = 0, t14 = 0, t15 = 0, + t16 = 0, t17 = 0, t18 = 0, t19 = 0, t20 = 0, t21 = 0, t22 = 0, t23 = 0, + t24 = 0, t25 = 0, t26 = 0, t27 = 0, t28 = 0, t29 = 0, t30 = 0, + b0 = b[0], + b1 = b[1], + b2 = b[2], + b3 = b[3], + b4 = b[4], + b5 = b[5], + b6 = b[6], + b7 = b[7], + b8 = b[8], + b9 = b[9], + b10 = b[10], + b11 = b[11], + b12 = b[12], + b13 = b[13], + b14 = b[14], + b15 = b[15]; + + v = a[0]; + t0 += v * b0; + t1 += v * b1; + t2 += v * b2; + t3 += v * b3; + t4 += v * b4; + t5 += v * b5; + t6 += v * b6; + t7 += v * b7; + t8 += v * b8; + t9 += v * b9; + t10 += v * b10; + t11 += v * b11; + t12 += v * b12; + t13 += v * b13; + t14 += v * b14; + t15 += v * b15; + v = a[1]; + t1 += v * b0; + t2 += v * b1; + t3 += v * b2; + t4 += v * b3; + t5 += v * b4; + t6 += v * b5; + t7 += v * b6; + t8 += v * b7; + t9 += v * b8; + t10 += v * b9; + t11 += v * b10; + t12 += v * b11; + t13 += v * b12; + t14 += v * b13; + t15 += v * b14; + t16 += v * b15; + v = a[2]; + t2 += v * b0; + t3 += v * b1; + t4 += v * b2; + t5 += v * b3; + t6 += v * b4; + t7 += v * b5; + t8 += v * b6; + t9 += v * b7; + t10 += v * b8; + t11 += v * b9; + t12 += v * b10; + t13 += v * b11; + t14 += v * b12; + t15 += v * b13; + t16 += v * b14; + t17 += v * b15; + v = a[3]; + t3 += v * b0; + t4 += v * b1; + t5 += v * b2; + t6 += v * b3; + t7 += v * b4; + t8 += v * b5; + t9 += v * b6; + t10 += v * b7; + t11 += v * b8; + t12 += v * b9; + t13 += v * b10; + t14 += v * b11; + t15 += v * b12; + t16 += v * b13; + t17 += v * b14; + t18 += v * b15; + v = a[4]; + t4 += v * b0; + t5 += v * b1; + t6 += v * b2; + t7 += v * b3; + t8 += v * b4; + t9 += v * b5; + t10 += v * b6; + t11 += v * b7; + t12 += v * b8; + t13 += v * b9; + t14 += v * b10; + t15 += v * b11; + t16 += v * b12; + t17 += v * b13; + t18 += v * b14; + t19 += v * b15; + v = a[5]; + t5 += v * b0; + t6 += v * b1; + t7 += v * b2; + t8 += v * b3; + t9 += v * b4; + t10 += v * b5; + t11 += v * b6; + t12 += v * b7; + t13 += v * b8; + t14 += v * b9; + t15 += v * b10; + t16 += v * b11; + t17 += v * b12; + t18 += v * b13; + t19 += v * b14; + t20 += v * b15; + v = a[6]; + t6 += v * b0; + t7 += v * b1; + t8 += v * b2; + t9 += v * b3; + t10 += v * b4; + t11 += v * b5; + t12 += v * b6; + t13 += v * b7; + t14 += v * b8; + t15 += v * b9; + t16 += v * b10; + t17 += v * b11; + t18 += v * b12; + t19 += v * b13; + t20 += v * b14; + t21 += v * b15; + v = a[7]; + t7 += v * b0; + t8 += v * b1; + t9 += v * b2; + t10 += v * b3; + t11 += v * b4; + t12 += v * b5; + t13 += v * b6; + t14 += v * b7; + t15 += v * b8; + t16 += v * b9; + t17 += v * b10; + t18 += v * b11; + t19 += v * b12; + t20 += v * b13; + t21 += v * b14; + t22 += v * b15; + v = a[8]; + t8 += v * b0; + t9 += v * b1; + t10 += v * b2; + t11 += v * b3; + t12 += v * b4; + t13 += v * b5; + t14 += v * b6; + t15 += v * b7; + t16 += v * b8; + t17 += v * b9; + t18 += v * b10; + t19 += v * b11; + t20 += v * b12; + t21 += v * b13; + t22 += v * b14; + t23 += v * b15; + v = a[9]; + t9 += v * b0; + t10 += v * b1; + t11 += v * b2; + t12 += v * b3; + t13 += v * b4; + t14 += v * b5; + t15 += v * b6; + t16 += v * b7; + t17 += v * b8; + t18 += v * b9; + t19 += v * b10; + t20 += v * b11; + t21 += v * b12; + t22 += v * b13; + t23 += v * b14; + t24 += v * b15; + v = a[10]; + t10 += v * b0; + t11 += v * b1; + t12 += v * b2; + t13 += v * b3; + t14 += v * b4; + t15 += v * b5; + t16 += v * b6; + t17 += v * b7; + t18 += v * b8; + t19 += v * b9; + t20 += v * b10; + t21 += v * b11; + t22 += v * b12; + t23 += v * b13; + t24 += v * b14; + t25 += v * b15; + v = a[11]; + t11 += v * b0; + t12 += v * b1; + t13 += v * b2; + t14 += v * b3; + t15 += v * b4; + t16 += v * b5; + t17 += v * b6; + t18 += v * b7; + t19 += v * b8; + t20 += v * b9; + t21 += v * b10; + t22 += v * b11; + t23 += v * b12; + t24 += v * b13; + t25 += v * b14; + t26 += v * b15; + v = a[12]; + t12 += v * b0; + t13 += v * b1; + t14 += v * b2; + t15 += v * b3; + t16 += v * b4; + t17 += v * b5; + t18 += v * b6; + t19 += v * b7; + t20 += v * b8; + t21 += v * b9; + t22 += v * b10; + t23 += v * b11; + t24 += v * b12; + t25 += v * b13; + t26 += v * b14; + t27 += v * b15; + v = a[13]; + t13 += v * b0; + t14 += v * b1; + t15 += v * b2; + t16 += v * b3; + t17 += v * b4; + t18 += v * b5; + t19 += v * b6; + t20 += v * b7; + t21 += v * b8; + t22 += v * b9; + t23 += v * b10; + t24 += v * b11; + t25 += v * b12; + t26 += v * b13; + t27 += v * b14; + t28 += v * b15; + v = a[14]; + t14 += v * b0; + t15 += v * b1; + t16 += v * b2; + t17 += v * b3; + t18 += v * b4; + t19 += v * b5; + t20 += v * b6; + t21 += v * b7; + t22 += v * b8; + t23 += v * b9; + t24 += v * b10; + t25 += v * b11; + t26 += v * b12; + t27 += v * b13; + t28 += v * b14; + t29 += v * b15; + v = a[15]; + t15 += v * b0; + t16 += v * b1; + t17 += v * b2; + t18 += v * b3; + t19 += v * b4; + t20 += v * b5; + t21 += v * b6; + t22 += v * b7; + t23 += v * b8; + t24 += v * b9; + t25 += v * b10; + t26 += v * b11; + t27 += v * b12; + t28 += v * b13; + t29 += v * b14; + t30 += v * b15; + + t0 += 38 * t16; + t1 += 38 * t17; + t2 += 38 * t18; + t3 += 38 * t19; + t4 += 38 * t20; + t5 += 38 * t21; + t6 += 38 * t22; + t7 += 38 * t23; + t8 += 38 * t24; + t9 += 38 * t25; + t10 += 38 * t26; + t11 += 38 * t27; + t12 += 38 * t28; + t13 += 38 * t29; + t14 += 38 * t30; + // t15 left as is + + // first car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); + + // second car + c = 1; + v = t0 + c + 65535; c = Math.floor(v / 65536); t0 = v - c * 65536; + v = t1 + c + 65535; c = Math.floor(v / 65536); t1 = v - c * 65536; + v = t2 + c + 65535; c = Math.floor(v / 65536); t2 = v - c * 65536; + v = t3 + c + 65535; c = Math.floor(v / 65536); t3 = v - c * 65536; + v = t4 + c + 65535; c = Math.floor(v / 65536); t4 = v - c * 65536; + v = t5 + c + 65535; c = Math.floor(v / 65536); t5 = v - c * 65536; + v = t6 + c + 65535; c = Math.floor(v / 65536); t6 = v - c * 65536; + v = t7 + c + 65535; c = Math.floor(v / 65536); t7 = v - c * 65536; + v = t8 + c + 65535; c = Math.floor(v / 65536); t8 = v - c * 65536; + v = t9 + c + 65535; c = Math.floor(v / 65536); t9 = v - c * 65536; + v = t10 + c + 65535; c = Math.floor(v / 65536); t10 = v - c * 65536; + v = t11 + c + 65535; c = Math.floor(v / 65536); t11 = v - c * 65536; + v = t12 + c + 65535; c = Math.floor(v / 65536); t12 = v - c * 65536; + v = t13 + c + 65535; c = Math.floor(v / 65536); t13 = v - c * 65536; + v = t14 + c + 65535; c = Math.floor(v / 65536); t14 = v - c * 65536; + v = t15 + c + 65535; c = Math.floor(v / 65536); t15 = v - c * 65536; + t0 += c-1 + 37 * (c-1); + + o[ 0] = t0; + o[ 1] = t1; + o[ 2] = t2; + o[ 3] = t3; + o[ 4] = t4; + o[ 5] = t5; + o[ 6] = t6; + o[ 7] = t7; + o[ 8] = t8; + o[ 9] = t9; + o[10] = t10; + o[11] = t11; + o[12] = t12; + o[13] = t13; + o[14] = t14; + o[15] = t15; +} diff --git a/node_modules/node-forge/lib/forge.js b/node_modules/node-forge/lib/forge.js new file mode 100644 index 0000000..2e243a9 --- /dev/null +++ b/node_modules/node-forge/lib/forge.js @@ -0,0 +1,13 @@ +/** + * Node.js module for Forge. + * + * @author Dave Longley + * + * Copyright 2011-2016 Digital Bazaar, Inc. + */ +module.exports = { + // default options + options: { + usePureJavaScript: false + } +}; diff --git a/node_modules/node-forge/lib/form.js b/node_modules/node-forge/lib/form.js new file mode 100644 index 0000000..4d7843a --- /dev/null +++ b/node_modules/node-forge/lib/form.js @@ -0,0 +1,149 @@ +/** + * Functions for manipulating web forms. + * + * @author David I. Lehn + * @author Dave Longley + * @author Mike Johnson + * + * Copyright (c) 2011-2014 Digital Bazaar, Inc. All rights reserved. + */ +var forge = require('./forge'); + +/* Form API */ +var form = module.exports = forge.form = forge.form || {}; + +(function($) { + +/** + * Regex for parsing a single name property (handles array brackets). + */ +var _regex = /([^\[]*?)\[(.*?)\]/g; + +/** + * Parses a single name property into an array with the name and any + * array indices. + * + * @param name the name to parse. + * + * @return the array of the name and its array indices in order. + */ +var _parseName = function(name) { + var rval = []; + + var matches; + while(!!(matches = _regex.exec(name))) { + if(matches[1].length > 0) { + rval.push(matches[1]); + } + if(matches.length >= 2) { + rval.push(matches[2]); + } + } + if(rval.length === 0) { + rval.push(name); + } + + return rval; +}; + +/** + * Adds a field from the given form to the given object. + * + * @param obj the object. + * @param names the field as an array of object property names. + * @param value the value of the field. + * @param dict a dictionary of names to replace. + */ +var _addField = function(obj, names, value, dict) { + // combine array names that fall within square brackets + var tmp = []; + for(var i = 0; i < names.length; ++i) { + // check name for starting square bracket but no ending one + var name = names[i]; + if(name.indexOf('[') !== -1 && name.indexOf(']') === -1 && + i < names.length - 1) { + do { + name += '.' + names[++i]; + } while(i < names.length - 1 && names[i].indexOf(']') === -1); + } + tmp.push(name); + } + names = tmp; + + // split out array indexes + var tmp = []; + $.each(names, function(n, name) { + tmp = tmp.concat(_parseName(name)); + }); + names = tmp; + + // iterate over object property names until value is set + $.each(names, function(n, name) { + // do dictionary name replacement + if(dict && name.length !== 0 && name in dict) { + name = dict[name]; + } + + // blank name indicates appending to an array, set name to + // new last index of array + if(name.length === 0) { + name = obj.length; + } + + // value already exists, append value + if(obj[name]) { + // last name in the field + if(n == names.length - 1) { + // more than one value, so convert into an array + if(!$.isArray(obj[name])) { + obj[name] = [obj[name]]; + } + obj[name].push(value); + } else { + // not last name, go deeper into object + obj = obj[name]; + } + } else if(n == names.length - 1) { + // new value, last name in the field, set value + obj[name] = value; + } else { + // new value, not last name, go deeper + // get next name + var next = names[n + 1]; + + // blank next value indicates array-appending, so create array + if(next.length === 0) { + obj[name] = []; + } else { + // if next name is a number create an array, otherwise a map + var isNum = ((next - 0) == next && next.length > 0); + obj[name] = isNum ? [] : {}; + } + obj = obj[name]; + } + }); +}; + +/** + * Serializes a form to a JSON object. Object properties will be separated + * using the given separator (defaults to '.') and by square brackets. + * + * @param input the jquery form to serialize. + * @param sep the object-property separator (defaults to '.'). + * @param dict a dictionary of names to replace (name=replace). + * + * @return the JSON-serialized form. + */ +form.serialize = function(input, sep, dict) { + var rval = {}; + + // add all fields in the form to the object + sep = sep || '.'; + $.each(input.serializeArray(), function() { + _addField(rval, this.name.split(sep), this.value || '', dict); + }); + + return rval; +}; + +})(jQuery); diff --git a/node_modules/node-forge/lib/hmac.js b/node_modules/node-forge/lib/hmac.js new file mode 100644 index 0000000..b155f24 --- /dev/null +++ b/node_modules/node-forge/lib/hmac.js @@ -0,0 +1,146 @@ +/** + * Hash-based Message Authentication Code implementation. Requires a message + * digest object that can be obtained, for example, from forge.md.sha1 or + * forge.md.md5. + * + * @author Dave Longley + * + * Copyright (c) 2010-2012 Digital Bazaar, Inc. All rights reserved. + */ +var forge = require('./forge'); +require('./md'); +require('./util'); + +/* HMAC API */ +var hmac = module.exports = forge.hmac = forge.hmac || {}; + +/** + * Creates an HMAC object that uses the given message digest object. + * + * @return an HMAC object. + */ +hmac.create = function() { + // the hmac key to use + var _key = null; + + // the message digest to use + var _md = null; + + // the inner padding + var _ipadding = null; + + // the outer padding + var _opadding = null; + + // hmac context + var ctx = {}; + + /** + * Starts or restarts the HMAC with the given key and message digest. + * + * @param md the message digest to use, null to reuse the previous one, + * a string to use builtin 'sha1', 'md5', 'sha256'. + * @param key the key to use as a string, array of bytes, byte buffer, + * or null to reuse the previous key. + */ + ctx.start = function(md, key) { + if(md !== null) { + if(typeof md === 'string') { + // create builtin message digest + md = md.toLowerCase(); + if(md in forge.md.algorithms) { + _md = forge.md.algorithms[md].create(); + } else { + throw new Error('Unknown hash algorithm "' + md + '"'); + } + } else { + // store message digest + _md = md; + } + } + + if(key === null) { + // reuse previous key + key = _key; + } else { + if(typeof key === 'string') { + // convert string into byte buffer + key = forge.util.createBuffer(key); + } else if(forge.util.isArray(key)) { + // convert byte array into byte buffer + var tmp = key; + key = forge.util.createBuffer(); + for(var i = 0; i < tmp.length; ++i) { + key.putByte(tmp[i]); + } + } + + // if key is longer than blocksize, hash it + var keylen = key.length(); + if(keylen > _md.blockLength) { + _md.start(); + _md.update(key.bytes()); + key = _md.digest(); + } + + // mix key into inner and outer padding + // ipadding = [0x36 * blocksize] ^ key + // opadding = [0x5C * blocksize] ^ key + _ipadding = forge.util.createBuffer(); + _opadding = forge.util.createBuffer(); + keylen = key.length(); + for(var i = 0; i < keylen; ++i) { + var tmp = key.at(i); + _ipadding.putByte(0x36 ^ tmp); + _opadding.putByte(0x5C ^ tmp); + } + + // if key is shorter than blocksize, add additional padding + if(keylen < _md.blockLength) { + var tmp = _md.blockLength - keylen; + for(var i = 0; i < tmp; ++i) { + _ipadding.putByte(0x36); + _opadding.putByte(0x5C); + } + } + _key = key; + _ipadding = _ipadding.bytes(); + _opadding = _opadding.bytes(); + } + + // digest is done like so: hash(opadding | hash(ipadding | message)) + + // prepare to do inner hash + // hash(ipadding | message) + _md.start(); + _md.update(_ipadding); + }; + + /** + * Updates the HMAC with the given message bytes. + * + * @param bytes the bytes to update with. + */ + ctx.update = function(bytes) { + _md.update(bytes); + }; + + /** + * Produces the Message Authentication Code (MAC). + * + * @return a byte buffer containing the digest value. + */ + ctx.getMac = function() { + // digest is done like so: hash(opadding | hash(ipadding | message)) + // here we do the outer hashing + var inner = _md.digest().bytes(); + _md.start(); + _md.update(_opadding); + _md.update(inner); + return _md.digest(); + }; + // alias for getMac + ctx.digest = ctx.getMac; + + return ctx; +}; diff --git a/node_modules/node-forge/lib/http.js b/node_modules/node-forge/lib/http.js new file mode 100644 index 0000000..1dcb0a6 --- /dev/null +++ b/node_modules/node-forge/lib/http.js @@ -0,0 +1,1364 @@ +/** + * HTTP client-side implementation that uses forge.net sockets. + * + * @author Dave Longley + * + * Copyright (c) 2010-2014 Digital Bazaar, Inc. All rights reserved. + */ +var forge = require('./forge'); +require('./debug'); +require('./tls'); +require('./util'); + +// define http namespace +var http = module.exports = forge.http = forge.http || {}; + +// logging category +var cat = 'forge.http'; + +// add array of clients to debug storage +if(forge.debug) { + forge.debug.set('forge.http', 'clients', []); +} + +// normalizes an http header field name +var _normalize = function(name) { + return name.toLowerCase().replace(/(^.)|(-.)/g, + function(a) {return a.toUpperCase();}); +}; + +/** + * Gets the local storage ID for the given client. + * + * @param client the client to get the local storage ID for. + * + * @return the local storage ID to use. + */ +var _getStorageId = function(client) { + // TODO: include browser in ID to avoid sharing cookies between + // browsers (if this is undesirable) + // navigator.userAgent + return 'forge.http.' + + client.url.scheme + '.' + + client.url.host + '.' + + client.url.port; +}; + +/** + * Loads persistent cookies from disk for the given client. + * + * @param client the client. + */ +var _loadCookies = function(client) { + if(client.persistCookies) { + try { + var cookies = forge.util.getItem( + client.socketPool.flashApi, + _getStorageId(client), 'cookies'); + client.cookies = cookies || {}; + } catch(ex) { + // no flash storage available, just silently fail + // TODO: i assume we want this logged somewhere or + // should it actually generate an error + //forge.log.error(cat, ex); + } + } +}; + +/** + * Saves persistent cookies on disk for the given client. + * + * @param client the client. + */ +var _saveCookies = function(client) { + if(client.persistCookies) { + try { + forge.util.setItem( + client.socketPool.flashApi, + _getStorageId(client), 'cookies', client.cookies); + } catch(ex) { + // no flash storage available, just silently fail + // TODO: i assume we want this logged somewhere or + // should it actually generate an error + //forge.log.error(cat, ex); + } + } + + // FIXME: remove me + _loadCookies(client); +}; + +/** + * Clears persistent cookies on disk for the given client. + * + * @param client the client. + */ +var _clearCookies = function(client) { + if(client.persistCookies) { + try { + // only thing stored is 'cookies', so clear whole storage + forge.util.clearItems( + client.socketPool.flashApi, + _getStorageId(client)); + } catch(ex) { + // no flash storage available, just silently fail + // TODO: i assume we want this logged somewhere or + // should it actually generate an error + //forge.log.error(cat, ex); + } + } +}; + +/** + * Connects and sends a request. + * + * @param client the http client. + * @param socket the socket to use. + */ +var _doRequest = function(client, socket) { + if(socket.isConnected()) { + // already connected + socket.options.request.connectTime = +new Date(); + socket.connected({ + type: 'connect', + id: socket.id + }); + } else { + // connect + socket.options.request.connectTime = +new Date(); + socket.connect({ + host: client.url.host, + port: client.url.port, + policyPort: client.policyPort, + policyUrl: client.policyUrl + }); + } +}; + +/** + * Handles the next request or marks a socket as idle. + * + * @param client the http client. + * @param socket the socket. + */ +var _handleNextRequest = function(client, socket) { + // clear buffer + socket.buffer.clear(); + + // get pending request + var pending = null; + while(pending === null && client.requests.length > 0) { + pending = client.requests.shift(); + if(pending.request.aborted) { + pending = null; + } + } + + // mark socket idle if no pending requests + if(pending === null) { + if(socket.options !== null) { + socket.options = null; + } + client.idle.push(socket); + } else { + // handle pending request, allow 1 retry + socket.retries = 1; + socket.options = pending; + _doRequest(client, socket); + } +}; + +/** + * Sets up a socket for use with an http client. + * + * @param client the parent http client. + * @param socket the socket to set up. + * @param tlsOptions if the socket must use TLS, the TLS options. + */ +var _initSocket = function(client, socket, tlsOptions) { + // no socket options yet + socket.options = null; + + // set up handlers + socket.connected = function(e) { + // socket primed by caching TLS session, handle next request + if(socket.options === null) { + _handleNextRequest(client, socket); + } else { + // socket in use + var request = socket.options.request; + request.connectTime = +new Date() - request.connectTime; + e.socket = socket; + socket.options.connected(e); + if(request.aborted) { + socket.close(); + } else { + var out = request.toString(); + if(request.body) { + out += request.body; + } + request.time = +new Date(); + socket.send(out); + request.time = +new Date() - request.time; + socket.options.response.time = +new Date(); + socket.sending = true; + } + } + }; + socket.closed = function(e) { + if(socket.sending) { + socket.sending = false; + if(socket.retries > 0) { + --socket.retries; + _doRequest(client, socket); + } else { + // error, closed during send + socket.error({ + id: socket.id, + type: 'ioError', + message: 'Connection closed during send. Broken pipe.', + bytesAvailable: 0 + }); + } + } else { + // handle unspecified content-length transfer + var response = socket.options.response; + if(response.readBodyUntilClose) { + response.time = +new Date() - response.time; + response.bodyReceived = true; + socket.options.bodyReady({ + request: socket.options.request, + response: response, + socket: socket + }); + } + socket.options.closed(e); + _handleNextRequest(client, socket); + } + }; + socket.data = function(e) { + socket.sending = false; + var request = socket.options.request; + if(request.aborted) { + socket.close(); + } else { + // receive all bytes available + var response = socket.options.response; + var bytes = socket.receive(e.bytesAvailable); + if(bytes !== null) { + // receive header and then body + socket.buffer.putBytes(bytes); + if(!response.headerReceived) { + response.readHeader(socket.buffer); + if(response.headerReceived) { + socket.options.headerReady({ + request: socket.options.request, + response: response, + socket: socket + }); + } + } + if(response.headerReceived && !response.bodyReceived) { + response.readBody(socket.buffer); + } + if(response.bodyReceived) { + socket.options.bodyReady({ + request: socket.options.request, + response: response, + socket: socket + }); + // close connection if requested or by default on http/1.0 + var value = response.getField('Connection') || ''; + if(value.indexOf('close') != -1 || + (response.version === 'HTTP/1.0' && + response.getField('Keep-Alive') === null)) { + socket.close(); + } else { + _handleNextRequest(client, socket); + } + } + } + } + }; + socket.error = function(e) { + // do error callback, include request + socket.options.error({ + type: e.type, + message: e.message, + request: socket.options.request, + response: socket.options.response, + socket: socket + }); + socket.close(); + }; + + // wrap socket for TLS + if(tlsOptions) { + socket = forge.tls.wrapSocket({ + sessionId: null, + sessionCache: {}, + caStore: tlsOptions.caStore, + cipherSuites: tlsOptions.cipherSuites, + socket: socket, + virtualHost: tlsOptions.virtualHost, + verify: tlsOptions.verify, + getCertificate: tlsOptions.getCertificate, + getPrivateKey: tlsOptions.getPrivateKey, + getSignature: tlsOptions.getSignature, + deflate: tlsOptions.deflate || null, + inflate: tlsOptions.inflate || null + }); + + socket.options = null; + socket.buffer = forge.util.createBuffer(); + client.sockets.push(socket); + if(tlsOptions.prime) { + // prime socket by connecting and caching TLS session, will do + // next request from there + socket.connect({ + host: client.url.host, + port: client.url.port, + policyPort: client.policyPort, + policyUrl: client.policyUrl + }); + } else { + // do not prime socket, just add as idle + client.idle.push(socket); + } + } else { + // no need to prime non-TLS sockets + socket.buffer = forge.util.createBuffer(); + client.sockets.push(socket); + client.idle.push(socket); + } +}; + +/** + * Checks to see if the given cookie has expired. If the cookie's max-age + * plus its created time is less than the time now, it has expired, unless + * its max-age is set to -1 which indicates it will never expire. + * + * @param cookie the cookie to check. + * + * @return true if it has expired, false if not. + */ +var _hasCookieExpired = function(cookie) { + var rval = false; + + if(cookie.maxAge !== -1) { + var now = _getUtcTime(new Date()); + var expires = cookie.created + cookie.maxAge; + if(expires <= now) { + rval = true; + } + } + + return rval; +}; + +/** + * Adds cookies in the given client to the given request. + * + * @param client the client. + * @param request the request. + */ +var _writeCookies = function(client, request) { + var expired = []; + var url = client.url; + var cookies = client.cookies; + for(var name in cookies) { + // get cookie paths + var paths = cookies[name]; + for(var p in paths) { + var cookie = paths[p]; + if(_hasCookieExpired(cookie)) { + // store for clean up + expired.push(cookie); + } else if(request.path.indexOf(cookie.path) === 0) { + // path or path's ancestor must match cookie.path + request.addCookie(cookie); + } + } + } + + // clean up expired cookies + for(var i = 0; i < expired.length; ++i) { + var cookie = expired[i]; + client.removeCookie(cookie.name, cookie.path); + } +}; + +/** + * Gets cookies from the given response and adds the to the given client. + * + * @param client the client. + * @param response the response. + */ +var _readCookies = function(client, response) { + var cookies = response.getCookies(); + for(var i = 0; i < cookies.length; ++i) { + try { + client.setCookie(cookies[i]); + } catch(ex) { + // ignore failure to add other-domain, etc. cookies + } + } +}; + +/** + * Creates an http client that uses forge.net sockets as a backend and + * forge.tls for security. + * + * @param options: + * url: the url to connect to (scheme://host:port). + * socketPool: the flash socket pool to use. + * policyPort: the flash policy port to use (if other than the + * socket pool default), use 0 for flash default. + * policyUrl: the flash policy file URL to use (if provided will + * be used instead of a policy port). + * connections: number of connections to use to handle requests. + * caCerts: an array of certificates to trust for TLS, certs may + * be PEM-formatted or cert objects produced via forge.pki. + * cipherSuites: an optional array of cipher suites to use, + * see forge.tls.CipherSuites. + * virtualHost: the virtual server name to use in a TLS SNI + * extension, if not provided the url host will be used. + * verify: a custom TLS certificate verify callback to use. + * getCertificate: an optional callback used to get a client-side + * certificate (see forge.tls for details). + * getPrivateKey: an optional callback used to get a client-side + * private key (see forge.tls for details). + * getSignature: an optional callback used to get a client-side + * signature (see forge.tls for details). + * persistCookies: true to use persistent cookies via flash local + * storage, false to only keep cookies in javascript. + * primeTlsSockets: true to immediately connect TLS sockets on + * their creation so that they will cache TLS sessions for reuse. + * + * @return the client. + */ +http.createClient = function(options) { + // create CA store to share with all TLS connections + var caStore = null; + if(options.caCerts) { + caStore = forge.pki.createCaStore(options.caCerts); + } + + // get scheme, host, and port from url + options.url = (options.url || + window.location.protocol + '//' + window.location.host); + var url = http.parseUrl(options.url); + if(!url) { + var error = new Error('Invalid url.'); + error.details = {url: options.url}; + throw error; + } + + // default to 1 connection + options.connections = options.connections || 1; + + // create client + var sp = options.socketPool; + var client = { + // url + url: url, + // socket pool + socketPool: sp, + // the policy port to use + policyPort: options.policyPort, + // policy url to use + policyUrl: options.policyUrl, + // queue of requests to service + requests: [], + // all sockets + sockets: [], + // idle sockets + idle: [], + // whether or not the connections are secure + secure: (url.scheme === 'https'), + // cookie jar (key'd off of name and then path, there is only 1 domain + // and one setting for secure per client so name+path is unique) + cookies: {}, + // default to flash storage of cookies + persistCookies: (typeof(options.persistCookies) === 'undefined') ? + true : options.persistCookies + }; + + // add client to debug storage + if(forge.debug) { + forge.debug.get('forge.http', 'clients').push(client); + } + + // load cookies from disk + _loadCookies(client); + + /** + * A default certificate verify function that checks a certificate common + * name against the client's URL host. + * + * @param c the TLS connection. + * @param verified true if cert is verified, otherwise alert number. + * @param depth the chain depth. + * @param certs the cert chain. + * + * @return true if verified and the common name matches the host, error + * otherwise. + */ + var _defaultCertificateVerify = function(c, verified, depth, certs) { + if(depth === 0 && verified === true) { + // compare common name to url host + var cn = certs[depth].subject.getField('CN'); + if(cn === null || client.url.host !== cn.value) { + verified = { + message: 'Certificate common name does not match url host.' + }; + } + } + return verified; + }; + + // determine if TLS is used + var tlsOptions = null; + if(client.secure) { + tlsOptions = { + caStore: caStore, + cipherSuites: options.cipherSuites || null, + virtualHost: options.virtualHost || url.host, + verify: options.verify || _defaultCertificateVerify, + getCertificate: options.getCertificate || null, + getPrivateKey: options.getPrivateKey || null, + getSignature: options.getSignature || null, + prime: options.primeTlsSockets || false + }; + + // if socket pool uses a flash api, then add deflate support to TLS + if(sp.flashApi !== null) { + tlsOptions.deflate = function(bytes) { + // strip 2 byte zlib header and 4 byte trailer + return forge.util.deflate(sp.flashApi, bytes, true); + }; + tlsOptions.inflate = function(bytes) { + return forge.util.inflate(sp.flashApi, bytes, true); + }; + } + } + + // create and initialize sockets + for(var i = 0; i < options.connections; ++i) { + _initSocket(client, sp.createSocket(), tlsOptions); + } + + /** + * Sends a request. A method 'abort' will be set on the request that + * can be called to attempt to abort the request. + * + * @param options: + * request: the request to send. + * connected: a callback for when the connection is open. + * closed: a callback for when the connection is closed. + * headerReady: a callback for when the response header arrives. + * bodyReady: a callback for when the response body arrives. + * error: a callback for if an error occurs. + */ + client.send = function(options) { + // add host header if not set + if(options.request.getField('Host') === null) { + options.request.setField('Host', client.url.fullHost); + } + + // set default dummy handlers + var opts = {}; + opts.request = options.request; + opts.connected = options.connected || function() {}; + opts.closed = options.close || function() {}; + opts.headerReady = function(e) { + // read cookies + _readCookies(client, e.response); + if(options.headerReady) { + options.headerReady(e); + } + }; + opts.bodyReady = options.bodyReady || function() {}; + opts.error = options.error || function() {}; + + // create response + opts.response = http.createResponse(); + opts.response.time = 0; + opts.response.flashApi = client.socketPool.flashApi; + opts.request.flashApi = client.socketPool.flashApi; + + // create abort function + opts.request.abort = function() { + // set aborted, clear handlers + opts.request.aborted = true; + opts.connected = function() {}; + opts.closed = function() {}; + opts.headerReady = function() {}; + opts.bodyReady = function() {}; + opts.error = function() {}; + }; + + // add cookies to request + _writeCookies(client, opts.request); + + // queue request options if there are no idle sockets + if(client.idle.length === 0) { + client.requests.push(opts); + } else { + // use an idle socket, prefer an idle *connected* socket first + var socket = null; + var len = client.idle.length; + for(var i = 0; socket === null && i < len; ++i) { + socket = client.idle[i]; + if(socket.isConnected()) { + client.idle.splice(i, 1); + } else { + socket = null; + } + } + // no connected socket available, get unconnected socket + if(socket === null) { + socket = client.idle.pop(); + } + socket.options = opts; + _doRequest(client, socket); + } + }; + + /** + * Destroys this client. + */ + client.destroy = function() { + // clear pending requests, close and destroy sockets + client.requests = []; + for(var i = 0; i < client.sockets.length; ++i) { + client.sockets[i].close(); + client.sockets[i].destroy(); + } + client.socketPool = null; + client.sockets = []; + client.idle = []; + }; + + /** + * Sets a cookie for use with all connections made by this client. Any + * cookie with the same name will be replaced. If the cookie's value + * is undefined, null, or the blank string, the cookie will be removed. + * + * If the cookie's domain doesn't match this client's url host or the + * cookie's secure flag doesn't match this client's url scheme, then + * setting the cookie will fail with an exception. + * + * @param cookie the cookie with parameters: + * name: the name of the cookie. + * value: the value of the cookie. + * comment: an optional comment string. + * maxAge: the age of the cookie in seconds relative to created time. + * secure: true if the cookie must be sent over a secure protocol. + * httpOnly: true to restrict access to the cookie from javascript + * (inaffective since the cookies are stored in javascript). + * path: the path for the cookie. + * domain: optional domain the cookie belongs to (must start with dot). + * version: optional version of the cookie. + * created: creation time, in UTC seconds, of the cookie. + */ + client.setCookie = function(cookie) { + var rval; + if(typeof(cookie.name) !== 'undefined') { + if(cookie.value === null || typeof(cookie.value) === 'undefined' || + cookie.value === '') { + // remove cookie + rval = client.removeCookie(cookie.name, cookie.path); + } else { + // set cookie defaults + cookie.comment = cookie.comment || ''; + cookie.maxAge = cookie.maxAge || 0; + cookie.secure = (typeof(cookie.secure) === 'undefined') ? + true : cookie.secure; + cookie.httpOnly = cookie.httpOnly || true; + cookie.path = cookie.path || '/'; + cookie.domain = cookie.domain || null; + cookie.version = cookie.version || null; + cookie.created = _getUtcTime(new Date()); + + // do secure check + if(cookie.secure !== client.secure) { + var error = new Error('Http client url scheme is incompatible ' + + 'with cookie secure flag.'); + error.url = client.url; + error.cookie = cookie; + throw error; + } + // make sure url host is within cookie.domain + if(!http.withinCookieDomain(client.url, cookie)) { + var error = new Error('Http client url scheme is incompatible ' + + 'with cookie secure flag.'); + error.url = client.url; + error.cookie = cookie; + throw error; + } + + // add new cookie + if(!(cookie.name in client.cookies)) { + client.cookies[cookie.name] = {}; + } + client.cookies[cookie.name][cookie.path] = cookie; + rval = true; + + // save cookies + _saveCookies(client); + } + } + + return rval; + }; + + /** + * Gets a cookie by its name. + * + * @param name the name of the cookie to retrieve. + * @param path an optional path for the cookie (if there are multiple + * cookies with the same name but different paths). + * + * @return the cookie or null if not found. + */ + client.getCookie = function(name, path) { + var rval = null; + if(name in client.cookies) { + var paths = client.cookies[name]; + + // get path-specific cookie + if(path) { + if(path in paths) { + rval = paths[path]; + } + } else { + // get first cookie + for(var p in paths) { + rval = paths[p]; + break; + } + } + } + return rval; + }; + + /** + * Removes a cookie. + * + * @param name the name of the cookie to remove. + * @param path an optional path for the cookie (if there are multiple + * cookies with the same name but different paths). + * + * @return true if a cookie was removed, false if not. + */ + client.removeCookie = function(name, path) { + var rval = false; + if(name in client.cookies) { + // delete the specific path + if(path) { + var paths = client.cookies[name]; + if(path in paths) { + rval = true; + delete client.cookies[name][path]; + // clean up entry if empty + var empty = true; + for(var i in client.cookies[name]) { + empty = false; + break; + } + if(empty) { + delete client.cookies[name]; + } + } + } else { + // delete all cookies with the given name + rval = true; + delete client.cookies[name]; + } + } + if(rval) { + // save cookies + _saveCookies(client); + } + return rval; + }; + + /** + * Clears all cookies stored in this client. + */ + client.clearCookies = function() { + client.cookies = {}; + _clearCookies(client); + }; + + if(forge.log) { + forge.log.debug('forge.http', 'created client', options); + } + + return client; +}; + +/** + * Trims the whitespace off of the beginning and end of a string. + * + * @param str the string to trim. + * + * @return the trimmed string. + */ +var _trimString = function(str) { + return str.replace(/^\s*/, '').replace(/\s*$/, ''); +}; + +/** + * Creates an http header object. + * + * @return the http header object. + */ +var _createHeader = function() { + var header = { + fields: {}, + setField: function(name, value) { + // normalize field name, trim value + header.fields[_normalize(name)] = [_trimString('' + value)]; + }, + appendField: function(name, value) { + name = _normalize(name); + if(!(name in header.fields)) { + header.fields[name] = []; + } + header.fields[name].push(_trimString('' + value)); + }, + getField: function(name, index) { + var rval = null; + name = _normalize(name); + if(name in header.fields) { + index = index || 0; + rval = header.fields[name][index]; + } + return rval; + } + }; + return header; +}; + +/** + * Gets the time in utc seconds given a date. + * + * @param d the date to use. + * + * @return the time in utc seconds. + */ +var _getUtcTime = function(d) { + var utc = +d + d.getTimezoneOffset() * 60000; + return Math.floor(+new Date() / 1000); +}; + +/** + * Creates an http request. + * + * @param options: + * version: the version. + * method: the method. + * path: the path. + * body: the body. + * headers: custom header fields to add, + * eg: [{'Content-Length': 0}]. + * + * @return the http request. + */ +http.createRequest = function(options) { + options = options || {}; + var request = _createHeader(); + request.version = options.version || 'HTTP/1.1'; + request.method = options.method || null; + request.path = options.path || null; + request.body = options.body || null; + request.bodyDeflated = false; + request.flashApi = null; + + // add custom headers + var headers = options.headers || []; + if(!forge.util.isArray(headers)) { + headers = [headers]; + } + for(var i = 0; i < headers.length; ++i) { + for(var name in headers[i]) { + request.appendField(name, headers[i][name]); + } + } + + /** + * Adds a cookie to the request 'Cookie' header. + * + * @param cookie a cookie to add. + */ + request.addCookie = function(cookie) { + var value = ''; + var field = request.getField('Cookie'); + if(field !== null) { + // separate cookies by semi-colons + value = field + '; '; + } + + // get current time in utc seconds + var now = _getUtcTime(new Date()); + + // output cookie name and value + value += cookie.name + '=' + cookie.value; + request.setField('Cookie', value); + }; + + /** + * Converts an http request into a string that can be sent as an + * HTTP request. Does not include any data. + * + * @return the string representation of the request. + */ + request.toString = function() { + /* Sample request header: + GET /some/path/?query HTTP/1.1 + Host: www.someurl.com + Connection: close + Accept-Encoding: deflate + Accept: image/gif, text/html + User-Agent: Mozilla 4.0 + */ + + // set default headers + if(request.getField('User-Agent') === null) { + request.setField('User-Agent', 'forge.http 1.0'); + } + if(request.getField('Accept') === null) { + request.setField('Accept', '*/*'); + } + if(request.getField('Connection') === null) { + request.setField('Connection', 'keep-alive'); + request.setField('Keep-Alive', '115'); + } + + // add Accept-Encoding if not specified + if(request.flashApi !== null && + request.getField('Accept-Encoding') === null) { + request.setField('Accept-Encoding', 'deflate'); + } + + // if the body isn't null, deflate it if its larger than 100 bytes + if(request.flashApi !== null && request.body !== null && + request.getField('Content-Encoding') === null && + !request.bodyDeflated && request.body.length > 100) { + // use flash to compress data + request.body = forge.util.deflate(request.flashApi, request.body); + request.bodyDeflated = true; + request.setField('Content-Encoding', 'deflate'); + request.setField('Content-Length', request.body.length); + } else if(request.body !== null) { + // set content length for body + request.setField('Content-Length', request.body.length); + } + + // build start line + var rval = + request.method.toUpperCase() + ' ' + request.path + ' ' + + request.version + '\r\n'; + + // add each header + for(var name in request.fields) { + var fields = request.fields[name]; + for(var i = 0; i < fields.length; ++i) { + rval += name + ': ' + fields[i] + '\r\n'; + } + } + // final terminating CRLF + rval += '\r\n'; + + return rval; + }; + + return request; +}; + +/** + * Creates an empty http response header. + * + * @return the empty http response header. + */ +http.createResponse = function() { + // private vars + var _first = true; + var _chunkSize = 0; + var _chunksFinished = false; + + // create response + var response = _createHeader(); + response.version = null; + response.code = 0; + response.message = null; + response.body = null; + response.headerReceived = false; + response.bodyReceived = false; + response.flashApi = null; + + /** + * Reads a line that ends in CRLF from a byte buffer. + * + * @param b the byte buffer. + * + * @return the line or null if none was found. + */ + var _readCrlf = function(b) { + var line = null; + var i = b.data.indexOf('\r\n', b.read); + if(i != -1) { + // read line, skip CRLF + line = b.getBytes(i - b.read); + b.getBytes(2); + } + return line; + }; + + /** + * Parses a header field and appends it to the response. + * + * @param line the header field line. + */ + var _parseHeader = function(line) { + var tmp = line.indexOf(':'); + var name = line.substring(0, tmp++); + response.appendField( + name, (tmp < line.length) ? line.substring(tmp) : ''); + }; + + /** + * Reads an http response header from a buffer of bytes. + * + * @param b the byte buffer to parse the header from. + * + * @return true if the whole header was read, false if not. + */ + response.readHeader = function(b) { + // read header lines (each ends in CRLF) + var line = ''; + while(!response.headerReceived && line !== null) { + line = _readCrlf(b); + if(line !== null) { + // parse first line + if(_first) { + _first = false; + var tmp = line.split(' '); + if(tmp.length >= 3) { + response.version = tmp[0]; + response.code = parseInt(tmp[1], 10); + response.message = tmp.slice(2).join(' '); + } else { + // invalid header + var error = new Error('Invalid http response header.'); + error.details = {'line': line}; + throw error; + } + } else if(line.length === 0) { + // handle final line, end of header + response.headerReceived = true; + } else { + _parseHeader(line); + } + } + } + + return response.headerReceived; + }; + + /** + * Reads some chunked http response entity-body from the given buffer of + * bytes. + * + * @param b the byte buffer to read from. + * + * @return true if the whole body was read, false if not. + */ + var _readChunkedBody = function(b) { + /* Chunked transfer-encoding sends data in a series of chunks, + followed by a set of 0-N http trailers. + The format is as follows: + + chunk-size (in hex) CRLF + chunk data (with "chunk-size" many bytes) CRLF + ... (N many chunks) + chunk-size (of 0 indicating the last chunk) CRLF + N many http trailers followed by CRLF + blank line + CRLF (terminates the trailers) + + If there are no http trailers, then after the chunk-size of 0, + there is still a single CRLF (indicating the blank line + CRLF + that terminates the trailers). In other words, you always terminate + the trailers with blank line + CRLF, regardless of 0-N trailers. */ + + /* From RFC-2616, section 3.6.1, here is the pseudo-code for + implementing chunked transfer-encoding: + + length := 0 + read chunk-size, chunk-extension (if any) and CRLF + while (chunk-size > 0) { + read chunk-data and CRLF + append chunk-data to entity-body + length := length + chunk-size + read chunk-size and CRLF + } + read entity-header + while (entity-header not empty) { + append entity-header to existing header fields + read entity-header + } + Content-Length := length + Remove "chunked" from Transfer-Encoding + */ + + var line = ''; + while(line !== null && b.length() > 0) { + // if in the process of reading a chunk + if(_chunkSize > 0) { + // if there are not enough bytes to read chunk and its + // trailing CRLF, we must wait for more data to be received + if(_chunkSize + 2 > b.length()) { + break; + } + + // read chunk data, skip CRLF + response.body += b.getBytes(_chunkSize); + b.getBytes(2); + _chunkSize = 0; + } else if(!_chunksFinished) { + // more chunks, read next chunk-size line + line = _readCrlf(b); + if(line !== null) { + // parse chunk-size (ignore any chunk extension) + _chunkSize = parseInt(line.split(';', 1)[0], 16); + _chunksFinished = (_chunkSize === 0); + } + } else { + // chunks finished, read next trailer + line = _readCrlf(b); + while(line !== null) { + if(line.length > 0) { + // parse trailer + _parseHeader(line); + // read next trailer + line = _readCrlf(b); + } else { + // body received + response.bodyReceived = true; + line = null; + } + } + } + } + + return response.bodyReceived; + }; + + /** + * Reads an http response body from a buffer of bytes. + * + * @param b the byte buffer to read from. + * + * @return true if the whole body was read, false if not. + */ + response.readBody = function(b) { + var contentLength = response.getField('Content-Length'); + var transferEncoding = response.getField('Transfer-Encoding'); + if(contentLength !== null) { + contentLength = parseInt(contentLength); + } + + // read specified length + if(contentLength !== null && contentLength >= 0) { + response.body = response.body || ''; + response.body += b.getBytes(contentLength); + response.bodyReceived = (response.body.length === contentLength); + } else if(transferEncoding !== null) { + // read chunked encoding + if(transferEncoding.indexOf('chunked') != -1) { + response.body = response.body || ''; + _readChunkedBody(b); + } else { + var error = new Error('Unknown Transfer-Encoding.'); + error.details = {'transferEncoding': transferEncoding}; + throw error; + } + } else if((contentLength !== null && contentLength < 0) || + (contentLength === null && + response.getField('Content-Type') !== null)) { + // read all data in the buffer + response.body = response.body || ''; + response.body += b.getBytes(); + response.readBodyUntilClose = true; + } else { + // no body + response.body = null; + response.bodyReceived = true; + } + + if(response.bodyReceived) { + response.time = +new Date() - response.time; + } + + if(response.flashApi !== null && + response.bodyReceived && response.body !== null && + response.getField('Content-Encoding') === 'deflate') { + // inflate using flash api + response.body = forge.util.inflate( + response.flashApi, response.body); + } + + return response.bodyReceived; + }; + + /** + * Parses an array of cookies from the 'Set-Cookie' field, if present. + * + * @return the array of cookies. + */ + response.getCookies = function() { + var rval = []; + + // get Set-Cookie field + if('Set-Cookie' in response.fields) { + var field = response.fields['Set-Cookie']; + + // get current local time in seconds + var now = +new Date() / 1000; + + // regex for parsing 'name1=value1; name2=value2; name3' + var regex = /\s*([^=]*)=?([^;]*)(;|$)/g; + + // examples: + // Set-Cookie: cookie1_name=cookie1_value; max-age=0; path=/ + // Set-Cookie: c2=v2; expires=Thu, 21-Aug-2008 23:47:25 GMT; path=/ + for(var i = 0; i < field.length; ++i) { + var fv = field[i]; + var m; + regex.lastIndex = 0; + var first = true; + var cookie = {}; + do { + m = regex.exec(fv); + if(m !== null) { + var name = _trimString(m[1]); + var value = _trimString(m[2]); + + // cookie_name=value + if(first) { + cookie.name = name; + cookie.value = value; + first = false; + } else { + // property_name=value + name = name.toLowerCase(); + switch(name) { + case 'expires': + // replace hyphens w/spaces so date will parse + value = value.replace(/-/g, ' '); + var secs = Date.parse(value) / 1000; + cookie.maxAge = Math.max(0, secs - now); + break; + case 'max-age': + cookie.maxAge = parseInt(value, 10); + break; + case 'secure': + cookie.secure = true; + break; + case 'httponly': + cookie.httpOnly = true; + break; + default: + if(name !== '') { + cookie[name] = value; + } + } + } + } + } while(m !== null && m[0] !== ''); + rval.push(cookie); + } + } + + return rval; + }; + + /** + * Converts an http response into a string that can be sent as an + * HTTP response. Does not include any data. + * + * @return the string representation of the response. + */ + response.toString = function() { + /* Sample response header: + HTTP/1.0 200 OK + Host: www.someurl.com + Connection: close + */ + + // build start line + var rval = + response.version + ' ' + response.code + ' ' + response.message + '\r\n'; + + // add each header + for(var name in response.fields) { + var fields = response.fields[name]; + for(var i = 0; i < fields.length; ++i) { + rval += name + ': ' + fields[i] + '\r\n'; + } + } + // final terminating CRLF + rval += '\r\n'; + + return rval; + }; + + return response; +}; + +/** + * Parses the scheme, host, and port from an http(s) url. + * + * @param str the url string. + * + * @return the parsed url object or null if the url is invalid. + */ +http.parseUrl = forge.util.parseUrl; + +/** + * Returns true if the given url is within the given cookie's domain. + * + * @param url the url to check. + * @param cookie the cookie or cookie domain to check. + */ +http.withinCookieDomain = function(url, cookie) { + var rval = false; + + // cookie may be null, a cookie object, or a domain string + var domain = (cookie === null || typeof cookie === 'string') ? + cookie : cookie.domain; + + // any domain will do + if(domain === null) { + rval = true; + } else if(domain.charAt(0) === '.') { + // ensure domain starts with a '.' + // parse URL as necessary + if(typeof url === 'string') { + url = http.parseUrl(url); + } + + // add '.' to front of URL host to match against domain + var host = '.' + url.host; + + // if the host ends with domain then it falls within it + var idx = host.lastIndexOf(domain); + if(idx !== -1 && (idx + domain.length === host.length)) { + rval = true; + } + } + + return rval; +}; diff --git a/node_modules/node-forge/lib/index.all.js b/node_modules/node-forge/lib/index.all.js new file mode 100644 index 0000000..22ba72b --- /dev/null +++ b/node_modules/node-forge/lib/index.all.js @@ -0,0 +1,16 @@ +/** + * Node.js module for Forge with extra utils and networking. + * + * @author Dave Longley + * + * Copyright 2011-2016 Digital Bazaar, Inc. + */ +module.exports = require('./forge'); +// require core forge +require('./index'); +// additional utils and networking support +require('./form'); +require('./socket'); +require('./tlssocket'); +require('./http'); +require('./xhr'); diff --git a/node_modules/node-forge/lib/index.js b/node_modules/node-forge/lib/index.js new file mode 100644 index 0000000..ea8c14c --- /dev/null +++ b/node_modules/node-forge/lib/index.js @@ -0,0 +1,35 @@ +/** + * Node.js module for Forge. + * + * @author Dave Longley + * + * Copyright 2011-2016 Digital Bazaar, Inc. + */ +module.exports = require('./forge'); +require('./aes'); +require('./aesCipherSuites'); +require('./asn1'); +require('./cipher'); +require('./debug'); +require('./des'); +require('./ed25519'); +require('./hmac'); +require('./kem'); +require('./log'); +require('./md.all'); +require('./mgf1'); +require('./pbkdf2'); +require('./pem'); +require('./pkcs1'); +require('./pkcs12'); +require('./pkcs7'); +require('./pki'); +require('./prime'); +require('./prng'); +require('./pss'); +require('./random'); +require('./rc2'); +require('./ssh'); +require('./task'); +require('./tls'); +require('./util'); diff --git a/node_modules/node-forge/lib/jsbn.js b/node_modules/node-forge/lib/jsbn.js new file mode 100644 index 0000000..11f965c --- /dev/null +++ b/node_modules/node-forge/lib/jsbn.js @@ -0,0 +1,1264 @@ +// Copyright (c) 2005 Tom Wu +// All Rights Reserved. +// See "LICENSE" for details. + +// Basic JavaScript BN library - subset useful for RSA encryption. + +/* +Licensing (LICENSE) +------------------- + +This software is covered under the following copyright: +*/ +/* + * 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. + */ +/* +Address all questions regarding this license to: + + Tom Wu + tjw@cs.Stanford.EDU +*/ +var forge = require('./forge'); + +module.exports = forge.jsbn = forge.jsbn || {}; + +// Bits per digit +var dbits; + +// JavaScript engine analysis +var canary = 0xdeadbeefcafe; +var j_lm = ((canary&0xffffff)==0xefcafe); + +// (public) Constructor +function BigInteger(a,b,c) { + this.data = []; + if(a != null) + if("number" == typeof a) this.fromNumber(a,b,c); + else if(b == null && "string" != typeof a) this.fromString(a,256); + else this.fromString(a,b); +} +forge.jsbn.BigInteger = BigInteger; + +// return new, unset BigInteger +function nbi() { return new BigInteger(null); } + +// 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.data[i++]+w.data[j]+c; + c = Math.floor(v/0x4000000); + w.data[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.data[i]&0x7fff; + var h = this.data[i++]>>15; + var m = xh*l+h*xl; + l = xl*l+((m&0x7fff)<<15)+w.data[j]+(c&0x3fffffff); + c = (l>>>30)+(m>>>15)+xh*h+(c>>>30); + w.data[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.data[i]&0x3fff; + var h = this.data[i++]>>14; + var m = xh*l+h*xl; + l = xl*l+((m&0x3fff)<<14)+w.data[j]+c; + c = (l>>28)+(m>>14)+xh*h; + w.data[j++] = l&0xfffffff; + } + return c; +} + +// node.js (no browser) +if(typeof(navigator) === 'undefined') +{ + BigInteger.prototype.am = am3; + dbits = 28; +} else if(j_lm && (navigator.appName == "Microsoft Internet Explorer")) { + BigInteger.prototype.am = am2; + dbits = 30; +} else if(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<= 0; --i) r.data[i] = this.data[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.data[0] = x; + else if(x < -1) this.data[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 == 256) k = 8; // byte array + else if(b == 2) k = 1; + else if(b == 32) k = 5; + else if(b == 4) k = 2; + else { this.fromRadix(s,b); return; } + this.t = 0; + this.s = 0; + var i = s.length, mi = false, sh = 0; + while(--i >= 0) { + var x = (k==8)?s[i]&0xff:intAt(s,i); + if(x < 0) { + if(s.charAt(i) == "-") mi = true; + continue; + } + mi = false; + if(sh == 0) + this.data[this.t++] = x; + else if(sh+k > this.DB) { + this.data[this.t-1] |= (x&((1<<(this.DB-sh))-1))<>(this.DB-sh)); + } else + this.data[this.t-1] |= x<= this.DB) sh -= this.DB; + } + if(k == 8 && (s[0]&0x80) != 0) { + this.s = -1; + if(sh > 0) this.data[this.t-1] |= ((1<<(this.DB-sh))-1)< 0 && this.data[this.t-1] == c) --this.t; +} + +// (public) return string representation in given radix +function bnToString(b) { + if(this.s < 0) return "-"+this.negate().toString(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 return this.toRadix(b); + var km = (1< 0) { + if(p < this.DB && (d = this.data[i]>>p) > 0) { m = true; r = int2char(d); } + while(i >= 0) { + if(p < k) { + d = (this.data[i]&((1<>(p+=this.DB-k); + } else { + d = (this.data[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.data[i]-a.data[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.data[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.data[i+n] = this.data[i]; + for(i = n-1; i >= 0; --i) r.data[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.data[i-n] = this.data[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<= 0; --i) { + r.data[i+ds+1] = (this.data[i]>>cbs)|c; + c = (this.data[i]&bm)<= 0; --i) r.data[i] = 0; + r.data[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; + for(var i = ds+1; i < this.t; ++i) { + r.data[i-ds-1] |= (this.data[i]&bm)<>bs; + } + if(bs > 0) r.data[this.t-ds-1] |= (this.s&bm)<>= this.DB; + } + if(a.t < this.t) { + c -= a.s; + while(i < this.t) { + c += this.data[i]; + r.data[i++] = c&this.DM; + c >>= this.DB; + } + c += this.s; + } else { + c += this.s; + while(i < a.t) { + c -= a.data[i]; + r.data[i++] = c&this.DM; + c >>= this.DB; + } + c -= a.s; + } + r.s = (c<0)?-1:0; + if(c < -1) r.data[i++] = this.DV+c; + else if(c > 0) r.data[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.data[i] = 0; + for(i = 0; i < y.t; ++i) r.data[i+x.t] = x.am(0,y.data[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.data[i] = 0; + for(i = 0; i < x.t-1; ++i) { + var c = x.am(i,x.data[i],r,2*i,0,1); + if((r.data[i+x.t]+=x.am(i+1,2*x.data[i],r,2*i+1,c,x.t-i-1)) >= x.DV) { + r.data[i+x.t] -= x.DV; + r.data[i+x.t+1] = 1; + } + } + if(r.t > 0) r.data[r.t-1] += x.am(i,x.data[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.data[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.data[ys-1]; + if(y0 == 0) return; + var yt = y0*(1<1)?y.data[ys-2]>>this.F2:0); + var d1 = this.FV/yt, d2 = (1<= 0) { + r.data[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.data[y.t++] = 0; + while(--j >= 0) { + // Estimate quotient digit + var qd = (r.data[--i]==y0)?this.DM:Math.floor(r.data[i]*d1+(r.data[i-1]+e)*d2); + if((r.data[i]+=y.am(0,qd,r,j,0,ys)) < qd) { // Try it out + y.dlShiftTo(j,t); + r.subTo(t,r); + while(r.data[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; +} + +// Modular reduction using "classic" algorithm +function Classic(m) { this.m = m; } +function cConvert(x) { + if(x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m); + else return x; +} +function cRevert(x) { return x; } +function cReduce(x) { x.divRemTo(this.m,null,x); } +function cMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } +function cSqrTo(x,r) { x.squareTo(r); this.reduce(r); } + +Classic.prototype.convert = cConvert; +Classic.prototype.revert = cRevert; +Classic.prototype.reduce = cReduce; +Classic.prototype.mulTo = cMulTo; +Classic.prototype.sqrTo = cSqrTo; + +// (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.data[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; +} + +// 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.data[x.t++] = 0; + for(var i = 0; i < this.m.t; ++i) { + // faster way of calculating u0 = x.data[i]*mp mod DV + var j = x.data[i]&0x7fff; + var u0 = (j*this.mpl+(((j*this.mph+(x.data[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.data[j] += this.m.am(0,u0,x,i,0,this.m.t); + // propagate carry + while(x.data[j] >= x.DV) { x.data[j] -= x.DV; x.data[++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; + +// (protected) true iff this is even +function bnpIsEven() { return ((this.t>0)?(this.data[0]&1):this.s) == 0; } + +// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) +function bnpExp(e,z) { + if(e > 0xffffffff || e < 1) return BigInteger.ONE; + var r = nbi(), r2 = nbi(), g = z.convert(this), i = nbits(e)-1; + g.copyTo(r); + while(--i >= 0) { + z.sqrTo(r,r2); + if((e&(1< 0) z.mulTo(r2,g,r); + else { var t = r; r = r2; r2 = t; } + } + return z.revert(r); +} + +// (public) this^e % m, 0 <= e < 2^32 +function bnModPowInt(e,m) { + var z; + if(e < 256 || m.isEven()) z = new Classic(m); else z = new Montgomery(m); + return this.exp(e,z); +} + +// 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.isEven = bnpIsEven; +BigInteger.prototype.exp = bnpExp; + +// 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.modPowInt = bnModPowInt; + +// "constants" +BigInteger.ZERO = nbv(0); +BigInteger.ONE = nbv(1); + +// jsbn2 lib + +//Copyright (c) 2005-2009 Tom Wu +//All Rights Reserved. +//See "LICENSE" for details (See jsbn.js for LICENSE). + +//Extended JavaScript BN functions, required for RSA private ops. + +//Version 1.1: new BigInteger("0", 10) returns "proper" zero + +//(public) +function bnClone() { var r = nbi(); this.copyTo(r); return r; } + +//(public) return value as integer +function bnIntValue() { +if(this.s < 0) { + if(this.t == 1) return this.data[0]-this.DV; + else if(this.t == 0) return -1; +} else if(this.t == 1) return this.data[0]; +else if(this.t == 0) return 0; +// assumes 16 < DB < 32 +return ((this.data[1]&((1<<(32-this.DB))-1))<>24; } + +//(public) return value as short (assumes DB>=16) +function bnShortValue() { return (this.t==0)?this.s:(this.data[0]<<16)>>16; } + +//(protected) return x s.t. r^x < DV +function bnpChunkSize(r) { return Math.floor(Math.LN2*this.DB/Math.log(r)); } + +//(public) 0 if this == 0, 1 if this > 0 +function bnSigNum() { +if(this.s < 0) return -1; +else if(this.t <= 0 || (this.t == 1 && this.data[0] <= 0)) return 0; +else return 1; +} + +//(protected) convert to radix string +function bnpToRadix(b) { +if(b == null) b = 10; +if(this.signum() == 0 || b < 2 || b > 36) return "0"; +var cs = this.chunkSize(b); +var a = Math.pow(b,cs); +var d = nbv(a), y = nbi(), z = nbi(), r = ""; +this.divRemTo(d,y,z); +while(y.signum() > 0) { + r = (a+z.intValue()).toString(b).substr(1) + r; + y.divRemTo(d,y,z); +} +return z.intValue().toString(b) + r; +} + +//(protected) convert from radix string +function bnpFromRadix(s,b) { +this.fromInt(0); +if(b == null) b = 10; +var cs = this.chunkSize(b); +var d = Math.pow(b,cs), mi = false, j = 0, w = 0; +for(var i = 0; i < s.length; ++i) { + var x = intAt(s,i); + if(x < 0) { + if(s.charAt(i) == "-" && this.signum() == 0) mi = true; + continue; + } + w = b*w+x; + if(++j >= cs) { + this.dMultiply(d); + this.dAddOffset(w,0); + j = 0; + w = 0; + } +} +if(j > 0) { + this.dMultiply(Math.pow(b,j)); + this.dAddOffset(w,0); +} +if(mi) BigInteger.ZERO.subTo(this,this); +} + +//(protected) alternate constructor +function bnpFromNumber(a,b,c) { +if("number" == typeof b) { + // new BigInteger(int,int,RNG) + if(a < 2) this.fromInt(1); + else { + this.fromNumber(a,c); + if(!this.testBit(a-1)) // force MSB set + this.bitwiseTo(BigInteger.ONE.shiftLeft(a-1),op_or,this); + if(this.isEven()) this.dAddOffset(1,0); // force odd + while(!this.isProbablePrime(b)) { + this.dAddOffset(2,0); + if(this.bitLength() > a) this.subTo(BigInteger.ONE.shiftLeft(a-1),this); + } + } +} else { + // new BigInteger(int,RNG) + var x = new Array(), t = a&7; + x.length = (a>>3)+1; + b.nextBytes(x); + if(t > 0) x[0] &= ((1< 0) { + if(p < this.DB && (d = this.data[i]>>p) != (this.s&this.DM)>>p) + r[k++] = d|(this.s<<(this.DB-p)); + while(i >= 0) { + if(p < 8) { + d = (this.data[i]&((1<>(p+=this.DB-8); + } else { + d = (this.data[i]>>(p-=8))&0xff; + if(p <= 0) { p += this.DB; --i; } + } + if((d&0x80) != 0) d |= -256; + if(k == 0 && (this.s&0x80) != (d&0x80)) ++k; + if(k > 0 || d != this.s) r[k++] = d; + } +} +return r; +} + +function bnEquals(a) { return(this.compareTo(a)==0); } +function bnMin(a) { return(this.compareTo(a)<0)?this:a; } +function bnMax(a) { return(this.compareTo(a)>0)?this:a; } + +//(protected) r = this op a (bitwise) +function bnpBitwiseTo(a,op,r) { +var i, f, m = Math.min(a.t,this.t); +for(i = 0; i < m; ++i) r.data[i] = op(this.data[i],a.data[i]); +if(a.t < this.t) { + f = a.s&this.DM; + for(i = m; i < this.t; ++i) r.data[i] = op(this.data[i],f); + r.t = this.t; +} else { + f = this.s&this.DM; + for(i = m; i < a.t; ++i) r.data[i] = op(f,a.data[i]); + r.t = a.t; +} +r.s = op(this.s,a.s); +r.clamp(); +} + +//(public) this & a +function op_and(x,y) { return x&y; } +function bnAnd(a) { var r = nbi(); this.bitwiseTo(a,op_and,r); return r; } + +//(public) this | a +function op_or(x,y) { return x|y; } +function bnOr(a) { var r = nbi(); this.bitwiseTo(a,op_or,r); return r; } + +//(public) this ^ a +function op_xor(x,y) { return x^y; } +function bnXor(a) { var r = nbi(); this.bitwiseTo(a,op_xor,r); return r; } + +//(public) this & ~a +function op_andnot(x,y) { return x&~y; } +function bnAndNot(a) { var r = nbi(); this.bitwiseTo(a,op_andnot,r); return r; } + +//(public) ~this +function bnNot() { +var r = nbi(); +for(var i = 0; i < this.t; ++i) r.data[i] = this.DM&~this.data[i]; +r.t = this.t; +r.s = ~this.s; +return r; +} + +//(public) this << n +function bnShiftLeft(n) { +var r = nbi(); +if(n < 0) this.rShiftTo(-n,r); else this.lShiftTo(n,r); +return r; +} + +//(public) this >> n +function bnShiftRight(n) { +var r = nbi(); +if(n < 0) this.lShiftTo(-n,r); else this.rShiftTo(n,r); +return r; +} + +//return index of lowest 1-bit in x, x < 2^31 +function lbit(x) { +if(x == 0) return -1; +var r = 0; +if((x&0xffff) == 0) { x >>= 16; r += 16; } +if((x&0xff) == 0) { x >>= 8; r += 8; } +if((x&0xf) == 0) { x >>= 4; r += 4; } +if((x&3) == 0) { x >>= 2; r += 2; } +if((x&1) == 0) ++r; +return r; +} + +//(public) returns index of lowest 1-bit (or -1 if none) +function bnGetLowestSetBit() { +for(var i = 0; i < this.t; ++i) + if(this.data[i] != 0) return i*this.DB+lbit(this.data[i]); +if(this.s < 0) return this.t*this.DB; +return -1; +} + +//return number of 1 bits in x +function cbit(x) { +var r = 0; +while(x != 0) { x &= x-1; ++r; } +return r; +} + +//(public) return number of set bits +function bnBitCount() { +var r = 0, x = this.s&this.DM; +for(var i = 0; i < this.t; ++i) r += cbit(this.data[i]^x); +return r; +} + +//(public) true iff nth bit is set +function bnTestBit(n) { +var j = Math.floor(n/this.DB); +if(j >= this.t) return(this.s!=0); +return((this.data[j]&(1<<(n%this.DB)))!=0); +} + +//(protected) this op (1<>= this.DB; +} +if(a.t < this.t) { + c += a.s; + while(i < this.t) { + c += this.data[i]; + r.data[i++] = c&this.DM; + c >>= this.DB; + } + c += this.s; +} else { + c += this.s; + while(i < a.t) { + c += a.data[i]; + r.data[i++] = c&this.DM; + c >>= this.DB; + } + c += a.s; +} +r.s = (c<0)?-1:0; +if(c > 0) r.data[i++] = c; +else if(c < -1) r.data[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; } + +//(public) this % a +function bnRemainder(a) { var r = nbi(); this.divRemTo(a,null,r); return r; } + +//(public) [this/a,this%a] +function bnDivideAndRemainder(a) { +var q = nbi(), r = nbi(); +this.divRemTo(a,q,r); +return new Array(q,r); +} + +//(protected) this *= n, this >= 0, 1 < n < DV +function bnpDMultiply(n) { +this.data[this.t] = this.am(0,n-1,this,0,0,this.t); +++this.t; +this.clamp(); +} + +//(protected) this += n << w words, this >= 0 +function bnpDAddOffset(n,w) { +if(n == 0) return; +while(this.t <= w) this.data[this.t++] = 0; +this.data[w] += n; +while(this.data[w] >= this.DV) { + this.data[w] -= this.DV; + if(++w >= this.t) this.data[this.t++] = 0; + ++this.data[w]; +} +} + +//A "null" reducer +function NullExp() {} +function nNop(x) { return x; } +function nMulTo(x,y,r) { x.multiplyTo(y,r); } +function nSqrTo(x,r) { x.squareTo(r); } + +NullExp.prototype.convert = nNop; +NullExp.prototype.revert = nNop; +NullExp.prototype.mulTo = nMulTo; +NullExp.prototype.sqrTo = nSqrTo; + +//(public) this^e +function bnPow(e) { return this.exp(e,new NullExp()); } + +//(protected) r = lower n words of "this * a", a.t <= n +//"this" should be the larger one if appropriate. +function bnpMultiplyLowerTo(a,n,r) { +var i = Math.min(this.t+a.t,n); +r.s = 0; // assumes a,this >= 0 +r.t = i; +while(i > 0) r.data[--i] = 0; +var j; +for(j = r.t-this.t; i < j; ++i) r.data[i+this.t] = this.am(0,a.data[i],r,i,0,this.t); +for(j = Math.min(a.t,n); i < j; ++i) this.am(0,a.data[i],r,i,0,n-i); +r.clamp(); +} + +//(protected) r = "this * a" without lower n words, n > 0 +//"this" should be the larger one if appropriate. +function bnpMultiplyUpperTo(a,n,r) { +--n; +var i = r.t = this.t+a.t-n; +r.s = 0; // assumes a,this >= 0 +while(--i >= 0) r.data[i] = 0; +for(i = Math.max(n-this.t,0); i < a.t; ++i) + r.data[this.t+i-n] = this.am(n-i,a.data[i],r,0,0,this.t+i-n); +r.clamp(); +r.drShiftTo(1,r); +} + +//Barrett modular reduction +function Barrett(m) { +// setup Barrett +this.r2 = nbi(); +this.q3 = nbi(); +BigInteger.ONE.dlShiftTo(2*m.t,this.r2); +this.mu = this.r2.divide(m); +this.m = m; +} + +function barrettConvert(x) { +if(x.s < 0 || x.t > 2*this.m.t) return x.mod(this.m); +else if(x.compareTo(this.m) < 0) return x; +else { var r = nbi(); x.copyTo(r); this.reduce(r); return r; } +} + +function barrettRevert(x) { return x; } + +//x = x mod m (HAC 14.42) +function barrettReduce(x) { +x.drShiftTo(this.m.t-1,this.r2); +if(x.t > this.m.t+1) { x.t = this.m.t+1; x.clamp(); } +this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3); +this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2); +while(x.compareTo(this.r2) < 0) x.dAddOffset(1,this.m.t+1); +x.subTo(this.r2,x); +while(x.compareTo(this.m) >= 0) x.subTo(this.m,x); +} + +//r = x^2 mod m; x != r +function barrettSqrTo(x,r) { x.squareTo(r); this.reduce(r); } + +//r = x*y mod m; x,y != r +function barrettMulTo(x,y,r) { x.multiplyTo(y,r); this.reduce(r); } + +Barrett.prototype.convert = barrettConvert; +Barrett.prototype.revert = barrettRevert; +Barrett.prototype.reduce = barrettReduce; +Barrett.prototype.mulTo = barrettMulTo; +Barrett.prototype.sqrTo = barrettSqrTo; + +//(public) this^e % m (HAC 14.85) +function bnModPow(e,m) { +var i = e.bitLength(), k, r = nbv(1), z; +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; +if(i < 8) + z = new Classic(m); +else if(m.isEven()) + z = new Barrett(m); +else + z = new Montgomery(m); + +// precomputation +var g = new Array(), n = 3, k1 = k-1, km = (1< 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.data[j])-1; +while(j >= 0) { + if(i >= k1) w = (e.data[j]>>(i-k1))&km; + else { + w = (e.data[j]&((1<<(i+1))-1))<<(k1-i); + if(j > 0) w |= e.data[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.data[j]&(1< 0) { + x.rShiftTo(g,x); + y.rShiftTo(g,y); +} +while(x.signum() > 0) { + if((i = x.getLowestSetBit()) > 0) x.rShiftTo(i,x); + if((i = y.getLowestSetBit()) > 0) y.rShiftTo(i,y); + if(x.compareTo(y) >= 0) { + x.subTo(y,x); + x.rShiftTo(1,x); + } else { + y.subTo(x,y); + y.rShiftTo(1,y); + } +} +if(g > 0) y.lShiftTo(g,y); +return y; +} + +//(protected) this % n, n < 2^26 +function bnpModInt(n) { +if(n <= 0) return 0; +var d = this.DV%n, r = (this.s<0)?n-1:0; +if(this.t > 0) + if(d == 0) r = this.data[0]%n; + else for(var i = this.t-1; i >= 0; --i) r = (d*r+this.data[i])%n; +return r; +} + +//(public) 1/this % m (HAC 14.61) +function bnModInverse(m) { +var ac = m.isEven(); +if((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO; +var u = m.clone(), v = this.clone(); +var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1); +while(u.signum() != 0) { + while(u.isEven()) { + u.rShiftTo(1,u); + if(ac) { + if(!a.isEven() || !b.isEven()) { a.addTo(this,a); b.subTo(m,b); } + a.rShiftTo(1,a); + } else if(!b.isEven()) b.subTo(m,b); + b.rShiftTo(1,b); + } + while(v.isEven()) { + v.rShiftTo(1,v); + if(ac) { + if(!c.isEven() || !d.isEven()) { c.addTo(this,c); d.subTo(m,d); } + c.rShiftTo(1,c); + } else if(!d.isEven()) d.subTo(m,d); + d.rShiftTo(1,d); + } + if(u.compareTo(v) >= 0) { + u.subTo(v,u); + if(ac) a.subTo(c,a); + b.subTo(d,b); + } else { + v.subTo(u,v); + if(ac) c.subTo(a,c); + d.subTo(b,d); + } +} +if(v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO; +if(d.compareTo(m) >= 0) return d.subtract(m); +if(d.signum() < 0) d.addTo(m,d); else return d; +if(d.signum() < 0) return d.add(m); else return d; +} + +var lowprimes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509]; +var lplim = (1<<26)/lowprimes[lowprimes.length-1]; + +//(public) test primality with certainty >= 1-.5^t +function bnIsProbablePrime(t) { +var i, x = this.abs(); +if(x.t == 1 && x.data[0] <= lowprimes[lowprimes.length-1]) { + for(i = 0; i < lowprimes.length; ++i) + if(x.data[0] == lowprimes[i]) return true; + return false; +} +if(x.isEven()) return false; +i = 1; +while(i < lowprimes.length) { + var m = lowprimes[i], j = i+1; + while(j < lowprimes.length && m < lplim) m *= lowprimes[j++]; + m = x.modInt(m); + while(i < j) if(m%lowprimes[i++] == 0) return false; +} +return x.millerRabin(t); +} + +//(protected) true if probably prime (HAC 4.24, Miller-Rabin) +function bnpMillerRabin(t) { +var n1 = this.subtract(BigInteger.ONE); +var k = n1.getLowestSetBit(); +if(k <= 0) return false; +var r = n1.shiftRight(k); +var prng = bnGetPrng(); +var a; +for(var i = 0; i < t; ++i) { + // select witness 'a' at random from between 1 and n1 + do { + a = new BigInteger(this.bitLength(), prng); + } + while(a.compareTo(BigInteger.ONE) <= 0 || a.compareTo(n1) >= 0); + var y = a.modPow(r,this); + if(y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { + var j = 1; + while(j++ < k && y.compareTo(n1) != 0) { + y = y.modPowInt(2,this); + if(y.compareTo(BigInteger.ONE) == 0) return false; + } + if(y.compareTo(n1) != 0) return false; + } +} +return true; +} + +// get pseudo random number generator +function bnGetPrng() { + // create prng with api that matches BigInteger secure random + return { + // x is an array to fill with bytes + nextBytes: function(x) { + for(var i = 0; i < x.length; ++i) { + x[i] = Math.floor(Math.random() * 0x0100); + } + } + }; +} + +//protected +BigInteger.prototype.chunkSize = bnpChunkSize; +BigInteger.prototype.toRadix = bnpToRadix; +BigInteger.prototype.fromRadix = bnpFromRadix; +BigInteger.prototype.fromNumber = bnpFromNumber; +BigInteger.prototype.bitwiseTo = bnpBitwiseTo; +BigInteger.prototype.changeBit = bnpChangeBit; +BigInteger.prototype.addTo = bnpAddTo; +BigInteger.prototype.dMultiply = bnpDMultiply; +BigInteger.prototype.dAddOffset = bnpDAddOffset; +BigInteger.prototype.multiplyLowerTo = bnpMultiplyLowerTo; +BigInteger.prototype.multiplyUpperTo = bnpMultiplyUpperTo; +BigInteger.prototype.modInt = bnpModInt; +BigInteger.prototype.millerRabin = bnpMillerRabin; + +//public +BigInteger.prototype.clone = bnClone; +BigInteger.prototype.intValue = bnIntValue; +BigInteger.prototype.byteValue = bnByteValue; +BigInteger.prototype.shortValue = bnShortValue; +BigInteger.prototype.signum = bnSigNum; +BigInteger.prototype.toByteArray = bnToByteArray; +BigInteger.prototype.equals = bnEquals; +BigInteger.prototype.min = bnMin; +BigInteger.prototype.max = bnMax; +BigInteger.prototype.and = bnAnd; +BigInteger.prototype.or = bnOr; +BigInteger.prototype.xor = bnXor; +BigInteger.prototype.andNot = bnAndNot; +BigInteger.prototype.not = bnNot; +BigInteger.prototype.shiftLeft = bnShiftLeft; +BigInteger.prototype.shiftRight = bnShiftRight; +BigInteger.prototype.getLowestSetBit = bnGetLowestSetBit; +BigInteger.prototype.bitCount = bnBitCount; +BigInteger.prototype.testBit = bnTestBit; +BigInteger.prototype.setBit = bnSetBit; +BigInteger.prototype.clearBit = bnClearBit; +BigInteger.prototype.flipBit = bnFlipBit; +BigInteger.prototype.add = bnAdd; +BigInteger.prototype.subtract = bnSubtract; +BigInteger.prototype.multiply = bnMultiply; +BigInteger.prototype.divide = bnDivide; +BigInteger.prototype.remainder = bnRemainder; +BigInteger.prototype.divideAndRemainder = bnDivideAndRemainder; +BigInteger.prototype.modPow = bnModPow; +BigInteger.prototype.modInverse = bnModInverse; +BigInteger.prototype.pow = bnPow; +BigInteger.prototype.gcd = bnGCD; +BigInteger.prototype.isProbablePrime = bnIsProbablePrime; + +//BigInteger interfaces not implemented in jsbn: + +//BigInteger(int signum, byte[] magnitude) +//double doubleValue() +//float floatValue() +//int hashCode() +//long longValue() +//static BigInteger valueOf(long val) diff --git a/node_modules/node-forge/lib/kem.js b/node_modules/node-forge/lib/kem.js new file mode 100644 index 0000000..1967016 --- /dev/null +++ b/node_modules/node-forge/lib/kem.js @@ -0,0 +1,168 @@ +/** + * Javascript implementation of RSA-KEM. + * + * @author Lautaro Cozzani Rodriguez + * @author Dave Longley + * + * Copyright (c) 2014 Lautaro Cozzani + * Copyright (c) 2014 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./util'); +require('./random'); +require('./jsbn'); + +module.exports = forge.kem = forge.kem || {}; + +var BigInteger = forge.jsbn.BigInteger; + +/** + * The API for the RSA Key Encapsulation Mechanism (RSA-KEM) from ISO 18033-2. + */ +forge.kem.rsa = {}; + +/** + * Creates an RSA KEM API object for generating a secret asymmetric key. + * + * The symmetric key may be generated via a call to 'encrypt', which will + * produce a ciphertext to be transmitted to the recipient and a key to be + * kept secret. The ciphertext is a parameter to be passed to 'decrypt' which + * will produce the same secret key for the recipient to use to decrypt a + * message that was encrypted with the secret key. + * + * @param kdf the KDF API to use (eg: new forge.kem.kdf1()). + * @param options the options to use. + * [prng] a custom crypto-secure pseudo-random number generator to use, + * that must define "getBytesSync". + */ +forge.kem.rsa.create = function(kdf, options) { + options = options || {}; + var prng = options.prng || forge.random; + + var kem = {}; + + /** + * Generates a secret key and its encapsulation. + * + * @param publicKey the RSA public key to encrypt with. + * @param keyLength the length, in bytes, of the secret key to generate. + * + * @return an object with: + * encapsulation: the ciphertext for generating the secret key, as a + * binary-encoded string of bytes. + * key: the secret key to use for encrypting a message. + */ + kem.encrypt = function(publicKey, keyLength) { + // generate a random r where 1 < r < n + var byteLength = Math.ceil(publicKey.n.bitLength() / 8); + var r; + do { + r = new BigInteger( + forge.util.bytesToHex(prng.getBytesSync(byteLength)), + 16).mod(publicKey.n); + } while(r.compareTo(BigInteger.ONE) <= 0); + + // prepend r with zeros + r = forge.util.hexToBytes(r.toString(16)); + var zeros = byteLength - r.length; + if(zeros > 0) { + r = forge.util.fillString(String.fromCharCode(0), zeros) + r; + } + + // encrypt the random + var encapsulation = publicKey.encrypt(r, 'NONE'); + + // generate the secret key + var key = kdf.generate(r, keyLength); + + return {encapsulation: encapsulation, key: key}; + }; + + /** + * Decrypts an encapsulated secret key. + * + * @param privateKey the RSA private key to decrypt with. + * @param encapsulation the ciphertext for generating the secret key, as + * a binary-encoded string of bytes. + * @param keyLength the length, in bytes, of the secret key to generate. + * + * @return the secret key as a binary-encoded string of bytes. + */ + kem.decrypt = function(privateKey, encapsulation, keyLength) { + // decrypt the encapsulation and generate the secret key + var r = privateKey.decrypt(encapsulation, 'NONE'); + return kdf.generate(r, keyLength); + }; + + return kem; +}; + +// TODO: add forge.kem.kdf.create('KDF1', {md: ..., ...}) API? + +/** + * Creates a key derivation API object that implements KDF1 per ISO 18033-2. + * + * @param md the hash API to use. + * @param [digestLength] an optional digest length that must be positive and + * less than or equal to md.digestLength. + * + * @return a KDF1 API object. + */ +forge.kem.kdf1 = function(md, digestLength) { + _createKDF(this, md, 0, digestLength || md.digestLength); +}; + +/** + * Creates a key derivation API object that implements KDF2 per ISO 18033-2. + * + * @param md the hash API to use. + * @param [digestLength] an optional digest length that must be positive and + * less than or equal to md.digestLength. + * + * @return a KDF2 API object. + */ +forge.kem.kdf2 = function(md, digestLength) { + _createKDF(this, md, 1, digestLength || md.digestLength); +}; + +/** + * Creates a KDF1 or KDF2 API object. + * + * @param md the hash API to use. + * @param counterStart the starting index for the counter. + * @param digestLength the digest length to use. + * + * @return the KDF API object. + */ +function _createKDF(kdf, md, counterStart, digestLength) { + /** + * Generate a key of the specified length. + * + * @param x the binary-encoded byte string to generate a key from. + * @param length the number of bytes to generate (the size of the key). + * + * @return the key as a binary-encoded string. + */ + kdf.generate = function(x, length) { + var key = new forge.util.ByteBuffer(); + + // run counter from counterStart to ceil(length / Hash.len) + var k = Math.ceil(length / digestLength) + counterStart; + + var c = new forge.util.ByteBuffer(); + for(var i = counterStart; i < k; ++i) { + // I2OSP(i, 4): convert counter to an octet string of 4 octets + c.putInt32(i); + + // digest 'x' and the counter and add the result to the key + md.start(); + md.update(x + c.getBytes()); + var hash = md.digest(); + key.putBytes(hash.getBytes(digestLength)); + } + + // truncate to the correct key length + key.truncate(key.length() - length); + return key.getBytes(); + }; +} diff --git a/node_modules/node-forge/lib/log.js b/node_modules/node-forge/lib/log.js new file mode 100644 index 0000000..8d36f4a --- /dev/null +++ b/node_modules/node-forge/lib/log.js @@ -0,0 +1,317 @@ +/** + * Cross-browser support for logging in a web application. + * + * @author David I. Lehn + * + * Copyright (c) 2008-2013 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./util'); + +/* LOG API */ +module.exports = forge.log = forge.log || {}; + +/** + * Application logging system. + * + * Each logger level available as it's own function of the form: + * forge.log.level(category, args...) + * The category is an arbitrary string, and the args are the same as + * Firebug's console.log API. By default the call will be output as: + * 'LEVEL [category] , args[1], ...' + * This enables proper % formatting via the first argument. + * Each category is enabled by default but can be enabled or disabled with + * the setCategoryEnabled() function. + */ +// list of known levels +forge.log.levels = [ + 'none', 'error', 'warning', 'info', 'debug', 'verbose', 'max']; +// info on the levels indexed by name: +// index: level index +// name: uppercased display name +var sLevelInfo = {}; +// list of loggers +var sLoggers = []; +/** + * Standard console logger. If no console support is enabled this will + * remain null. Check before using. + */ +var sConsoleLogger = null; + +// logger flags +/** + * Lock the level at the current value. Used in cases where user config may + * set the level such that only critical messages are seen but more verbose + * messages are needed for debugging or other purposes. + */ +forge.log.LEVEL_LOCKED = (1 << 1); +/** + * Always call log function. By default, the logging system will check the + * message level against logger.level before calling the log function. This + * flag allows the function to do its own check. + */ +forge.log.NO_LEVEL_CHECK = (1 << 2); +/** + * Perform message interpolation with the passed arguments. "%" style + * fields in log messages will be replaced by arguments as needed. Some + * loggers, such as Firebug, may do this automatically. The original log + * message will be available as 'message' and the interpolated version will + * be available as 'fullMessage'. + */ +forge.log.INTERPOLATE = (1 << 3); + +// setup each log level +for(var i = 0; i < forge.log.levels.length; ++i) { + var level = forge.log.levels[i]; + sLevelInfo[level] = { + index: i, + name: level.toUpperCase() + }; +} + +/** + * Message logger. Will dispatch a message to registered loggers as needed. + * + * @param message message object + */ +forge.log.logMessage = function(message) { + var messageLevelIndex = sLevelInfo[message.level].index; + for(var i = 0; i < sLoggers.length; ++i) { + var logger = sLoggers[i]; + if(logger.flags & forge.log.NO_LEVEL_CHECK) { + logger.f(message); + } else { + // get logger level + var loggerLevelIndex = sLevelInfo[logger.level].index; + // check level + if(messageLevelIndex <= loggerLevelIndex) { + // message critical enough, call logger + logger.f(logger, message); + } + } + } +}; + +/** + * Sets the 'standard' key on a message object to: + * "LEVEL [category] " + message + * + * @param message a message log object + */ +forge.log.prepareStandard = function(message) { + if(!('standard' in message)) { + message.standard = + sLevelInfo[message.level].name + + //' ' + +message.timestamp + + ' [' + message.category + '] ' + + message.message; + } +}; + +/** + * Sets the 'full' key on a message object to the original message + * interpolated via % formatting with the message arguments. + * + * @param message a message log object. + */ +forge.log.prepareFull = function(message) { + if(!('full' in message)) { + // copy args and insert message at the front + var args = [message.message]; + args = args.concat([] || message['arguments']); + // format the message + message.full = forge.util.format.apply(this, args); + } +}; + +/** + * Applies both preparseStandard() and prepareFull() to a message object and + * store result in 'standardFull'. + * + * @param message a message log object. + */ +forge.log.prepareStandardFull = function(message) { + if(!('standardFull' in message)) { + // FIXME implement 'standardFull' logging + forge.log.prepareStandard(message); + message.standardFull = message.standard; + } +}; + +// create log level functions +if(true) { + // levels for which we want functions + var levels = ['error', 'warning', 'info', 'debug', 'verbose']; + for(var i = 0; i < levels.length; ++i) { + // wrap in a function to ensure proper level var is passed + (function(level) { + // create function for this level + forge.log[level] = function(category, message/*, args...*/) { + // convert arguments to real array, remove category and message + var args = Array.prototype.slice.call(arguments).slice(2); + // create message object + // Note: interpolation and standard formatting is done lazily + var msg = { + timestamp: new Date(), + level: level, + category: category, + message: message, + 'arguments': args + /*standard*/ + /*full*/ + /*fullMessage*/ + }; + // process this message + forge.log.logMessage(msg); + }; + })(levels[i]); + } +} + +/** + * Creates a new logger with specified custom logging function. + * + * The logging function has a signature of: + * function(logger, message) + * logger: current logger + * message: object: + * level: level id + * category: category + * message: string message + * arguments: Array of extra arguments + * fullMessage: interpolated message and arguments if INTERPOLATE flag set + * + * @param logFunction a logging function which takes a log message object + * as a parameter. + * + * @return a logger object. + */ +forge.log.makeLogger = function(logFunction) { + var logger = { + flags: 0, + f: logFunction + }; + forge.log.setLevel(logger, 'none'); + return logger; +}; + +/** + * Sets the current log level on a logger. + * + * @param logger the target logger. + * @param level the new maximum log level as a string. + * + * @return true if set, false if not. + */ +forge.log.setLevel = function(logger, level) { + var rval = false; + if(logger && !(logger.flags & forge.log.LEVEL_LOCKED)) { + for(var i = 0; i < forge.log.levels.length; ++i) { + var aValidLevel = forge.log.levels[i]; + if(level == aValidLevel) { + // set level + logger.level = level; + rval = true; + break; + } + } + } + + return rval; +}; + +/** + * Locks the log level at its current value. + * + * @param logger the target logger. + * @param lock boolean lock value, default to true. + */ +forge.log.lock = function(logger, lock) { + if(typeof lock === 'undefined' || lock) { + logger.flags |= forge.log.LEVEL_LOCKED; + } else { + logger.flags &= ~forge.log.LEVEL_LOCKED; + } +}; + +/** + * Adds a logger. + * + * @param logger the logger object. + */ +forge.log.addLogger = function(logger) { + sLoggers.push(logger); +}; + +// setup the console logger if possible, else create fake console.log +if(typeof(console) !== 'undefined' && 'log' in console) { + var logger; + if(console.error && console.warn && console.info && console.debug) { + // looks like Firebug-style logging is available + // level handlers map + var levelHandlers = { + error: console.error, + warning: console.warn, + info: console.info, + debug: console.debug, + verbose: console.debug + }; + var f = function(logger, message) { + forge.log.prepareStandard(message); + var handler = levelHandlers[message.level]; + // prepend standard message and concat args + var args = [message.standard]; + args = args.concat(message['arguments'].slice()); + // apply to low-level console function + handler.apply(console, args); + }; + logger = forge.log.makeLogger(f); + } else { + // only appear to have basic console.log + var f = function(logger, message) { + forge.log.prepareStandardFull(message); + console.log(message.standardFull); + }; + logger = forge.log.makeLogger(f); + } + forge.log.setLevel(logger, 'debug'); + forge.log.addLogger(logger); + sConsoleLogger = logger; +} else { + // define fake console.log to avoid potential script errors on + // browsers that do not have console logging + console = { + log: function() {} + }; +} + +/* + * Check for logging control query vars. + * + * console.level= + * Set's the console log level by name. Useful to override defaults and + * allow more verbose logging before a user config is loaded. + * + * console.lock= + * Lock the console log level at whatever level it is set at. This is run + * after console.level is processed. Useful to force a level of verbosity + * that could otherwise be limited by a user config. + */ +if(sConsoleLogger !== null) { + var query = forge.util.getQueryVariables(); + if('console.level' in query) { + // set with last value + forge.log.setLevel( + sConsoleLogger, query['console.level'].slice(-1)[0]); + } + if('console.lock' in query) { + // set with last value + var lock = query['console.lock'].slice(-1)[0]; + if(lock == 'true') { + forge.log.lock(sConsoleLogger); + } + } +} + +// provide public access to console logger +forge.log.consoleLogger = sConsoleLogger; diff --git a/node_modules/node-forge/lib/md.all.js b/node_modules/node-forge/lib/md.all.js new file mode 100644 index 0000000..4e0974b --- /dev/null +++ b/node_modules/node-forge/lib/md.all.js @@ -0,0 +1,13 @@ +/** + * Node.js module for all known Forge message digests. + * + * @author Dave Longley + * + * Copyright 2011-2017 Digital Bazaar, Inc. + */ +module.exports = require('./md'); + +require('./md5'); +require('./sha1'); +require('./sha256'); +require('./sha512'); diff --git a/node_modules/node-forge/lib/md.js b/node_modules/node-forge/lib/md.js new file mode 100644 index 0000000..e4a280c --- /dev/null +++ b/node_modules/node-forge/lib/md.js @@ -0,0 +1,11 @@ +/** + * Node.js module for Forge message digests. + * + * @author Dave Longley + * + * Copyright 2011-2017 Digital Bazaar, Inc. + */ +var forge = require('./forge'); + +module.exports = forge.md = forge.md || {}; +forge.md.algorithms = forge.md.algorithms || {}; diff --git a/node_modules/node-forge/lib/md5.js b/node_modules/node-forge/lib/md5.js new file mode 100644 index 0000000..d0ba8f6 --- /dev/null +++ b/node_modules/node-forge/lib/md5.js @@ -0,0 +1,289 @@ +/** + * Message Digest Algorithm 5 with 128-bit digest (MD5) implementation. + * + * @author Dave Longley + * + * Copyright (c) 2010-2014 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./md'); +require('./util'); + +var md5 = module.exports = forge.md5 = forge.md5 || {}; +forge.md.md5 = forge.md.algorithms.md5 = md5; + +/** + * Creates an MD5 message digest object. + * + * @return a message digest object. + */ +md5.create = function() { + // do initialization as necessary + if(!_initialized) { + _init(); + } + + // MD5 state contains four 32-bit integers + var _state = null; + + // input buffer + var _input = forge.util.createBuffer(); + + // used for word storage + var _w = new Array(16); + + // message digest object + var md = { + algorithm: 'md5', + blockLength: 64, + digestLength: 16, + // 56-bit length of message so far (does not including padding) + messageLength: 0, + // true message length + fullMessageLength: null, + // size of message length in bytes + messageLengthSize: 8 + }; + + /** + * Starts the digest. + * + * @return this digest object. + */ + md.start = function() { + // up to 56-bit message length for convenience + md.messageLength = 0; + + // full message length (set md.messageLength64 for backwards-compatibility) + md.fullMessageLength = md.messageLength64 = []; + var int32s = md.messageLengthSize / 4; + for(var i = 0; i < int32s; ++i) { + md.fullMessageLength.push(0); + } + _input = forge.util.createBuffer(); + _state = { + h0: 0x67452301, + h1: 0xEFCDAB89, + h2: 0x98BADCFE, + h3: 0x10325476 + }; + return md; + }; + // start digest automatically for first time + md.start(); + + /** + * Updates the digest with the given message input. The given input can + * treated as raw input (no encoding will be applied) or an encoding of + * 'utf8' maybe given to encode the input using UTF-8. + * + * @param msg the message input to update with. + * @param encoding the encoding to use (default: 'raw', other: 'utf8'). + * + * @return this digest object. + */ + md.update = function(msg, encoding) { + if(encoding === 'utf8') { + msg = forge.util.encodeUtf8(msg); + } + + // update message length + var len = msg.length; + md.messageLength += len; + len = [(len / 0x100000000) >>> 0, len >>> 0]; + for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { + md.fullMessageLength[i] += len[1]; + len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0); + md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; + len[0] = (len[1] / 0x100000000) >>> 0; + } + + // add bytes to input buffer + _input.putBytes(msg); + + // process bytes + _update(_state, _w, _input); + + // compact input buffer every 2K or if empty + if(_input.read > 2048 || _input.length() === 0) { + _input.compact(); + } + + return md; + }; + + /** + * Produces the digest. + * + * @return a byte buffer containing the digest value. + */ + md.digest = function() { + /* Note: Here we copy the remaining bytes in the input buffer and + add the appropriate MD5 padding. Then we do the final update + on a copy of the state so that if the user wants to get + intermediate digests they can do so. */ + + /* Determine the number of bytes that must be added to the message + to ensure its length is congruent to 448 mod 512. In other words, + the data to be digested must be a multiple of 512 bits (or 128 bytes). + This data includes the message, some padding, and the length of the + message. Since the length of the message will be encoded as 8 bytes (64 + bits), that means that the last segment of the data must have 56 bytes + (448 bits) of message and padding. Therefore, the length of the message + plus the padding must be congruent to 448 mod 512 because + 512 - 128 = 448. + + In order to fill up the message length it must be filled with + padding that begins with 1 bit followed by all 0 bits. Padding + must *always* be present, so if the message length is already + congruent to 448 mod 512, then 512 padding bits must be added. */ + + var finalBlock = forge.util.createBuffer(); + finalBlock.putBytes(_input.bytes()); + + // compute remaining size to be digested (include message length size) + var remaining = ( + md.fullMessageLength[md.fullMessageLength.length - 1] + + md.messageLengthSize); + + // add padding for overflow blockSize - overflow + // _padding starts with 1 byte with first bit is set (byte value 128), then + // there may be up to (blockSize - 1) other pad bytes + var overflow = remaining & (md.blockLength - 1); + finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); + + // serialize message length in bits in little-endian order; since length + // is stored in bytes we multiply by 8 and add carry + var bits, carry = 0; + for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { + bits = md.fullMessageLength[i] * 8 + carry; + carry = (bits / 0x100000000) >>> 0; + finalBlock.putInt32Le(bits >>> 0); + } + + var s2 = { + h0: _state.h0, + h1: _state.h1, + h2: _state.h2, + h3: _state.h3 + }; + _update(s2, _w, finalBlock); + var rval = forge.util.createBuffer(); + rval.putInt32Le(s2.h0); + rval.putInt32Le(s2.h1); + rval.putInt32Le(s2.h2); + rval.putInt32Le(s2.h3); + return rval; + }; + + return md; +}; + +// padding, constant tables for calculating md5 +var _padding = null; +var _g = null; +var _r = null; +var _k = null; +var _initialized = false; + +/** + * Initializes the constant tables. + */ +function _init() { + // create padding + _padding = String.fromCharCode(128); + _padding += forge.util.fillString(String.fromCharCode(0x00), 64); + + // g values + _g = [ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 1, 6, 11, 0, 5, 10, 15, 4, 9, 14, 3, 8, 13, 2, 7, 12, + 5, 8, 11, 14, 1, 4, 7, 10, 13, 0, 3, 6, 9, 12, 15, 2, + 0, 7, 14, 5, 12, 3, 10, 1, 8, 15, 6, 13, 4, 11, 2, 9]; + + // rounds table + _r = [ + 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, 7, 12, 17, 22, + 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, 5, 9, 14, 20, + 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, 4, 11, 16, 23, + 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21, 6, 10, 15, 21]; + + // get the result of abs(sin(i + 1)) as a 32-bit integer + _k = new Array(64); + for(var i = 0; i < 64; ++i) { + _k[i] = Math.floor(Math.abs(Math.sin(i + 1)) * 0x100000000); + } + + // now initialized + _initialized = true; +} + +/** + * Updates an MD5 state with the given byte buffer. + * + * @param s the MD5 state to update. + * @param w the array to use to store words. + * @param bytes the byte buffer to update with. + */ +function _update(s, w, bytes) { + // consume 512 bit (64 byte) chunks + var t, a, b, c, d, f, r, i; + var len = bytes.length(); + while(len >= 64) { + // initialize hash value for this chunk + a = s.h0; + b = s.h1; + c = s.h2; + d = s.h3; + + // round 1 + for(i = 0; i < 16; ++i) { + w[i] = bytes.getInt32Le(); + f = d ^ (b & (c ^ d)); + t = (a + f + _k[i] + w[i]); + r = _r[i]; + a = d; + d = c; + c = b; + b += (t << r) | (t >>> (32 - r)); + } + // round 2 + for(; i < 32; ++i) { + f = c ^ (d & (b ^ c)); + t = (a + f + _k[i] + w[_g[i]]); + r = _r[i]; + a = d; + d = c; + c = b; + b += (t << r) | (t >>> (32 - r)); + } + // round 3 + for(; i < 48; ++i) { + f = b ^ c ^ d; + t = (a + f + _k[i] + w[_g[i]]); + r = _r[i]; + a = d; + d = c; + c = b; + b += (t << r) | (t >>> (32 - r)); + } + // round 4 + for(; i < 64; ++i) { + f = c ^ (b | ~d); + t = (a + f + _k[i] + w[_g[i]]); + r = _r[i]; + a = d; + d = c; + c = b; + b += (t << r) | (t >>> (32 - r)); + } + + // update hash state + s.h0 = (s.h0 + a) | 0; + s.h1 = (s.h1 + b) | 0; + s.h2 = (s.h2 + c) | 0; + s.h3 = (s.h3 + d) | 0; + + len -= 64; + } +} diff --git a/node_modules/node-forge/lib/mgf.js b/node_modules/node-forge/lib/mgf.js new file mode 100644 index 0000000..0223bc3 --- /dev/null +++ b/node_modules/node-forge/lib/mgf.js @@ -0,0 +1,12 @@ +/** + * Node.js module for Forge mask generation functions. + * + * @author Stefan Siegl + * + * Copyright 2012 Stefan Siegl + */ +var forge = require('./forge'); +require('./mgf1'); + +module.exports = forge.mgf = forge.mgf || {}; +forge.mgf.mgf1 = forge.mgf1; diff --git a/node_modules/node-forge/lib/mgf1.js b/node_modules/node-forge/lib/mgf1.js new file mode 100644 index 0000000..25ed1f7 --- /dev/null +++ b/node_modules/node-forge/lib/mgf1.js @@ -0,0 +1,57 @@ +/** + * Javascript implementation of mask generation function MGF1. + * + * @author Stefan Siegl + * @author Dave Longley + * + * Copyright (c) 2012 Stefan Siegl + * Copyright (c) 2014 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./util'); + +forge.mgf = forge.mgf || {}; +var mgf1 = module.exports = forge.mgf.mgf1 = forge.mgf1 = forge.mgf1 || {}; + +/** + * Creates a MGF1 mask generation function object. + * + * @param md the message digest API to use (eg: forge.md.sha1.create()). + * + * @return a mask generation function object. + */ +mgf1.create = function(md) { + var mgf = { + /** + * Generate mask of specified length. + * + * @param {String} seed The seed for mask generation. + * @param maskLen Number of bytes to generate. + * @return {String} The generated mask. + */ + generate: function(seed, maskLen) { + /* 2. Let T be the empty octet string. */ + var t = new forge.util.ByteBuffer(); + + /* 3. For counter from 0 to ceil(maskLen / hLen), do the following: */ + var len = Math.ceil(maskLen / md.digestLength); + for(var i = 0; i < len; i++) { + /* a. Convert counter to an octet string C of length 4 octets */ + var c = new forge.util.ByteBuffer(); + c.putInt32(i); + + /* b. Concatenate the hash of the seed mgfSeed and C to the octet + * string T: */ + md.start(); + md.update(seed + c.getBytes()); + t.putBuffer(md.digest()); + } + + /* Output the leading maskLen octets of T as the octet string mask. */ + t.truncate(t.length() - maskLen); + return t.getBytes(); + } + }; + + return mgf; +}; diff --git a/node_modules/node-forge/lib/oids.js b/node_modules/node-forge/lib/oids.js new file mode 100644 index 0000000..6a937f5 --- /dev/null +++ b/node_modules/node-forge/lib/oids.js @@ -0,0 +1,170 @@ +/** + * Object IDs for ASN.1. + * + * @author Dave Longley + * + * Copyright (c) 2010-2013 Digital Bazaar, Inc. + */ +var forge = require('./forge'); + +forge.pki = forge.pki || {}; +var oids = module.exports = forge.pki.oids = forge.oids = forge.oids || {}; + +// set id to name mapping and name to id mapping +function _IN(id, name) { + oids[id] = name; + oids[name] = id; +} +// set id to name mapping only +function _I_(id, name) { + oids[id] = name; +} + +// algorithm OIDs +_IN('1.2.840.113549.1.1.1', 'rsaEncryption'); +// Note: md2 & md4 not implemented +//_IN('1.2.840.113549.1.1.2', 'md2WithRSAEncryption'); +//_IN('1.2.840.113549.1.1.3', 'md4WithRSAEncryption'); +_IN('1.2.840.113549.1.1.4', 'md5WithRSAEncryption'); +_IN('1.2.840.113549.1.1.5', 'sha1WithRSAEncryption'); +_IN('1.2.840.113549.1.1.7', 'RSAES-OAEP'); +_IN('1.2.840.113549.1.1.8', 'mgf1'); +_IN('1.2.840.113549.1.1.9', 'pSpecified'); +_IN('1.2.840.113549.1.1.10', 'RSASSA-PSS'); +_IN('1.2.840.113549.1.1.11', 'sha256WithRSAEncryption'); +_IN('1.2.840.113549.1.1.12', 'sha384WithRSAEncryption'); +_IN('1.2.840.113549.1.1.13', 'sha512WithRSAEncryption'); +// Edwards-curve Digital Signature Algorithm (EdDSA) Ed25519 +_IN('1.3.101.112', 'EdDSA25519'); + +_IN('1.2.840.10040.4.3', 'dsa-with-sha1'); + +_IN('1.3.14.3.2.7', 'desCBC'); + +_IN('1.3.14.3.2.26', 'sha1'); +_IN('2.16.840.1.101.3.4.2.1', 'sha256'); +_IN('2.16.840.1.101.3.4.2.2', 'sha384'); +_IN('2.16.840.1.101.3.4.2.3', 'sha512'); +_IN('1.2.840.113549.2.5', 'md5'); + +// pkcs#7 content types +_IN('1.2.840.113549.1.7.1', 'data'); +_IN('1.2.840.113549.1.7.2', 'signedData'); +_IN('1.2.840.113549.1.7.3', 'envelopedData'); +_IN('1.2.840.113549.1.7.4', 'signedAndEnvelopedData'); +_IN('1.2.840.113549.1.7.5', 'digestedData'); +_IN('1.2.840.113549.1.7.6', 'encryptedData'); + +// pkcs#9 oids +_IN('1.2.840.113549.1.9.1', 'emailAddress'); +_IN('1.2.840.113549.1.9.2', 'unstructuredName'); +_IN('1.2.840.113549.1.9.3', 'contentType'); +_IN('1.2.840.113549.1.9.4', 'messageDigest'); +_IN('1.2.840.113549.1.9.5', 'signingTime'); +_IN('1.2.840.113549.1.9.6', 'counterSignature'); +_IN('1.2.840.113549.1.9.7', 'challengePassword'); +_IN('1.2.840.113549.1.9.8', 'unstructuredAddress'); +_IN('1.2.840.113549.1.9.14', 'extensionRequest'); + +_IN('1.2.840.113549.1.9.20', 'friendlyName'); +_IN('1.2.840.113549.1.9.21', 'localKeyId'); +_IN('1.2.840.113549.1.9.22.1', 'x509Certificate'); + +// pkcs#12 safe bags +_IN('1.2.840.113549.1.12.10.1.1', 'keyBag'); +_IN('1.2.840.113549.1.12.10.1.2', 'pkcs8ShroudedKeyBag'); +_IN('1.2.840.113549.1.12.10.1.3', 'certBag'); +_IN('1.2.840.113549.1.12.10.1.4', 'crlBag'); +_IN('1.2.840.113549.1.12.10.1.5', 'secretBag'); +_IN('1.2.840.113549.1.12.10.1.6', 'safeContentsBag'); + +// password-based-encryption for pkcs#12 +_IN('1.2.840.113549.1.5.13', 'pkcs5PBES2'); +_IN('1.2.840.113549.1.5.12', 'pkcs5PBKDF2'); + +_IN('1.2.840.113549.1.12.1.1', 'pbeWithSHAAnd128BitRC4'); +_IN('1.2.840.113549.1.12.1.2', 'pbeWithSHAAnd40BitRC4'); +_IN('1.2.840.113549.1.12.1.3', 'pbeWithSHAAnd3-KeyTripleDES-CBC'); +_IN('1.2.840.113549.1.12.1.4', 'pbeWithSHAAnd2-KeyTripleDES-CBC'); +_IN('1.2.840.113549.1.12.1.5', 'pbeWithSHAAnd128BitRC2-CBC'); +_IN('1.2.840.113549.1.12.1.6', 'pbewithSHAAnd40BitRC2-CBC'); + +// hmac OIDs +_IN('1.2.840.113549.2.7', 'hmacWithSHA1'); +_IN('1.2.840.113549.2.8', 'hmacWithSHA224'); +_IN('1.2.840.113549.2.9', 'hmacWithSHA256'); +_IN('1.2.840.113549.2.10', 'hmacWithSHA384'); +_IN('1.2.840.113549.2.11', 'hmacWithSHA512'); + +// symmetric key algorithm oids +_IN('1.2.840.113549.3.7', 'des-EDE3-CBC'); +_IN('2.16.840.1.101.3.4.1.2', 'aes128-CBC'); +_IN('2.16.840.1.101.3.4.1.22', 'aes192-CBC'); +_IN('2.16.840.1.101.3.4.1.42', 'aes256-CBC'); + +// certificate issuer/subject OIDs +_IN('2.5.4.3', 'commonName'); +_IN('2.5.4.5', 'serialName'); +_IN('2.5.4.6', 'countryName'); +_IN('2.5.4.7', 'localityName'); +_IN('2.5.4.8', 'stateOrProvinceName'); +_IN('2.5.4.9', 'streetAddress'); +_IN('2.5.4.10', 'organizationName'); +_IN('2.5.4.11', 'organizationalUnitName'); +_IN('2.5.4.13', 'description'); +_IN('2.5.4.15', 'businessCategory'); +_IN('2.5.4.17', 'postalCode'); +_IN('1.3.6.1.4.1.311.60.2.1.2', 'jurisdictionOfIncorporationStateOrProvinceName'); +_IN('1.3.6.1.4.1.311.60.2.1.3', 'jurisdictionOfIncorporationCountryName'); + +// X.509 extension OIDs +_IN('2.16.840.1.113730.1.1', 'nsCertType'); +_IN('2.16.840.1.113730.1.13', 'nsComment'); // deprecated in theory; still widely used +_I_('2.5.29.1', 'authorityKeyIdentifier'); // deprecated, use .35 +_I_('2.5.29.2', 'keyAttributes'); // obsolete use .37 or .15 +_I_('2.5.29.3', 'certificatePolicies'); // deprecated, use .32 +_I_('2.5.29.4', 'keyUsageRestriction'); // obsolete use .37 or .15 +_I_('2.5.29.5', 'policyMapping'); // deprecated use .33 +_I_('2.5.29.6', 'subtreesConstraint'); // obsolete use .30 +_I_('2.5.29.7', 'subjectAltName'); // deprecated use .17 +_I_('2.5.29.8', 'issuerAltName'); // deprecated use .18 +_I_('2.5.29.9', 'subjectDirectoryAttributes'); +_I_('2.5.29.10', 'basicConstraints'); // deprecated use .19 +_I_('2.5.29.11', 'nameConstraints'); // deprecated use .30 +_I_('2.5.29.12', 'policyConstraints'); // deprecated use .36 +_I_('2.5.29.13', 'basicConstraints'); // deprecated use .19 +_IN('2.5.29.14', 'subjectKeyIdentifier'); +_IN('2.5.29.15', 'keyUsage'); +_I_('2.5.29.16', 'privateKeyUsagePeriod'); +_IN('2.5.29.17', 'subjectAltName'); +_IN('2.5.29.18', 'issuerAltName'); +_IN('2.5.29.19', 'basicConstraints'); +_I_('2.5.29.20', 'cRLNumber'); +_I_('2.5.29.21', 'cRLReason'); +_I_('2.5.29.22', 'expirationDate'); +_I_('2.5.29.23', 'instructionCode'); +_I_('2.5.29.24', 'invalidityDate'); +_I_('2.5.29.25', 'cRLDistributionPoints'); // deprecated use .31 +_I_('2.5.29.26', 'issuingDistributionPoint'); // deprecated use .28 +_I_('2.5.29.27', 'deltaCRLIndicator'); +_I_('2.5.29.28', 'issuingDistributionPoint'); +_I_('2.5.29.29', 'certificateIssuer'); +_I_('2.5.29.30', 'nameConstraints'); +_IN('2.5.29.31', 'cRLDistributionPoints'); +_IN('2.5.29.32', 'certificatePolicies'); +_I_('2.5.29.33', 'policyMappings'); +_I_('2.5.29.34', 'policyConstraints'); // deprecated use .36 +_IN('2.5.29.35', 'authorityKeyIdentifier'); +_I_('2.5.29.36', 'policyConstraints'); +_IN('2.5.29.37', 'extKeyUsage'); +_I_('2.5.29.46', 'freshestCRL'); +_I_('2.5.29.54', 'inhibitAnyPolicy'); + +// extKeyUsage purposes +_IN('1.3.6.1.4.1.11129.2.4.2', 'timestampList'); +_IN('1.3.6.1.5.5.7.1.1', 'authorityInfoAccess'); +_IN('1.3.6.1.5.5.7.3.1', 'serverAuth'); +_IN('1.3.6.1.5.5.7.3.2', 'clientAuth'); +_IN('1.3.6.1.5.5.7.3.3', 'codeSigning'); +_IN('1.3.6.1.5.5.7.3.4', 'emailProtection'); +_IN('1.3.6.1.5.5.7.3.8', 'timeStamping'); diff --git a/node_modules/node-forge/lib/pbe.js b/node_modules/node-forge/lib/pbe.js new file mode 100644 index 0000000..cf8456b --- /dev/null +++ b/node_modules/node-forge/lib/pbe.js @@ -0,0 +1,1023 @@ +/** + * Password-based encryption functions. + * + * @author Dave Longley + * @author Stefan Siegl + * + * Copyright (c) 2010-2013 Digital Bazaar, Inc. + * Copyright (c) 2012 Stefan Siegl + * + * An EncryptedPrivateKeyInfo: + * + * EncryptedPrivateKeyInfo ::= SEQUENCE { + * encryptionAlgorithm EncryptionAlgorithmIdentifier, + * encryptedData EncryptedData } + * + * EncryptionAlgorithmIdentifier ::= AlgorithmIdentifier + * + * EncryptedData ::= OCTET STRING + */ +var forge = require('./forge'); +require('./aes'); +require('./asn1'); +require('./des'); +require('./md'); +require('./oids'); +require('./pbkdf2'); +require('./pem'); +require('./random'); +require('./rc2'); +require('./rsa'); +require('./util'); + +if(typeof BigInteger === 'undefined') { + var BigInteger = forge.jsbn.BigInteger; +} + +// shortcut for asn.1 API +var asn1 = forge.asn1; + +/* Password-based encryption implementation. */ +var pki = forge.pki = forge.pki || {}; +module.exports = pki.pbe = forge.pbe = forge.pbe || {}; +var oids = pki.oids; + +// validator for an EncryptedPrivateKeyInfo structure +// Note: Currently only works w/algorithm params +var encryptedPrivateKeyValidator = { + name: 'EncryptedPrivateKeyInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'EncryptedPrivateKeyInfo.encryptionAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'AlgorithmIdentifier.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'encryptionOid' + }, { + name: 'AlgorithmIdentifier.parameters', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'encryptionParams' + }] + }, { + // encryptedData + name: 'EncryptedPrivateKeyInfo.encryptedData', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'encryptedData' + }] +}; + +// validator for a PBES2Algorithms structure +// Note: Currently only works w/PBKDF2 + AES encryption schemes +var PBES2AlgorithmsValidator = { + name: 'PBES2Algorithms', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'PBES2Algorithms.keyDerivationFunc', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'PBES2Algorithms.keyDerivationFunc.oid', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'kdfOid' + }, { + name: 'PBES2Algorithms.params', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'PBES2Algorithms.params.salt', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'kdfSalt' + }, { + name: 'PBES2Algorithms.params.iterationCount', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'kdfIterationCount' + }, { + name: 'PBES2Algorithms.params.keyLength', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + optional: true, + capture: 'keyLength' + }, { + // prf + name: 'PBES2Algorithms.params.prf', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + optional: true, + value: [{ + name: 'PBES2Algorithms.params.prf.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'prfOid' + }] + }] + }] + }, { + name: 'PBES2Algorithms.encryptionScheme', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'PBES2Algorithms.encryptionScheme.oid', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'encOid' + }, { + name: 'PBES2Algorithms.encryptionScheme.iv', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'encIv' + }] + }] +}; + +var pkcs12PbeParamsValidator = { + name: 'pkcs-12PbeParams', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'pkcs-12PbeParams.salt', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'salt' + }, { + name: 'pkcs-12PbeParams.iterations', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'iterations' + }] +}; + +/** + * Encrypts a ASN.1 PrivateKeyInfo object, producing an EncryptedPrivateKeyInfo. + * + * PBES2Algorithms ALGORITHM-IDENTIFIER ::= + * { {PBES2-params IDENTIFIED BY id-PBES2}, ...} + * + * id-PBES2 OBJECT IDENTIFIER ::= {pkcs-5 13} + * + * PBES2-params ::= SEQUENCE { + * keyDerivationFunc AlgorithmIdentifier {{PBES2-KDFs}}, + * encryptionScheme AlgorithmIdentifier {{PBES2-Encs}} + * } + * + * PBES2-KDFs ALGORITHM-IDENTIFIER ::= + * { {PBKDF2-params IDENTIFIED BY id-PBKDF2}, ... } + * + * PBES2-Encs ALGORITHM-IDENTIFIER ::= { ... } + * + * PBKDF2-params ::= SEQUENCE { + * salt CHOICE { + * specified OCTET STRING, + * otherSource AlgorithmIdentifier {{PBKDF2-SaltSources}} + * }, + * iterationCount INTEGER (1..MAX), + * keyLength INTEGER (1..MAX) OPTIONAL, + * prf AlgorithmIdentifier {{PBKDF2-PRFs}} DEFAULT algid-hmacWithSHA1 + * } + * + * @param obj the ASN.1 PrivateKeyInfo object. + * @param password the password to encrypt with. + * @param options: + * algorithm the encryption algorithm to use + * ('aes128', 'aes192', 'aes256', '3des'), defaults to 'aes128'. + * count the iteration count to use. + * saltSize the salt size to use. + * prfAlgorithm the PRF message digest algorithm to use + * ('sha1', 'sha224', 'sha256', 'sha384', 'sha512') + * + * @return the ASN.1 EncryptedPrivateKeyInfo. + */ +pki.encryptPrivateKeyInfo = function(obj, password, options) { + // set default options + options = options || {}; + options.saltSize = options.saltSize || 8; + options.count = options.count || 2048; + options.algorithm = options.algorithm || 'aes128'; + options.prfAlgorithm = options.prfAlgorithm || 'sha1'; + + // generate PBE params + var salt = forge.random.getBytesSync(options.saltSize); + var count = options.count; + var countBytes = asn1.integerToDer(count); + var dkLen; + var encryptionAlgorithm; + var encryptedData; + if(options.algorithm.indexOf('aes') === 0 || options.algorithm === 'des') { + // do PBES2 + var ivLen, encOid, cipherFn; + switch(options.algorithm) { + case 'aes128': + dkLen = 16; + ivLen = 16; + encOid = oids['aes128-CBC']; + cipherFn = forge.aes.createEncryptionCipher; + break; + case 'aes192': + dkLen = 24; + ivLen = 16; + encOid = oids['aes192-CBC']; + cipherFn = forge.aes.createEncryptionCipher; + break; + case 'aes256': + dkLen = 32; + ivLen = 16; + encOid = oids['aes256-CBC']; + cipherFn = forge.aes.createEncryptionCipher; + break; + case 'des': + dkLen = 8; + ivLen = 8; + encOid = oids['desCBC']; + cipherFn = forge.des.createEncryptionCipher; + break; + default: + var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.'); + error.algorithm = options.algorithm; + throw error; + } + + // get PRF message digest + var prfAlgorithm = 'hmacWith' + options.prfAlgorithm.toUpperCase(); + var md = prfAlgorithmToMessageDigest(prfAlgorithm); + + // encrypt private key using pbe SHA-1 and AES/DES + var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md); + var iv = forge.random.getBytesSync(ivLen); + var cipher = cipherFn(dk); + cipher.start(iv); + cipher.update(asn1.toDer(obj)); + cipher.finish(); + encryptedData = cipher.output.getBytes(); + + // get PBKDF2-params + var params = createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm); + + encryptionAlgorithm = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(oids['pkcs5PBES2']).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // keyDerivationFunc + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(oids['pkcs5PBKDF2']).getBytes()), + // PBKDF2-params + params + ]), + // encryptionScheme + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(encOid).getBytes()), + // iv + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, iv) + ]) + ]) + ]); + } else if(options.algorithm === '3des') { + // Do PKCS12 PBE + dkLen = 24; + + var saltBytes = new forge.util.ByteBuffer(salt); + var dk = pki.pbe.generatePkcs12Key(password, saltBytes, 1, count, dkLen); + var iv = pki.pbe.generatePkcs12Key(password, saltBytes, 2, count, dkLen); + var cipher = forge.des.createEncryptionCipher(dk); + cipher.start(iv); + cipher.update(asn1.toDer(obj)); + cipher.finish(); + encryptedData = cipher.output.getBytes(); + + encryptionAlgorithm = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(oids['pbeWithSHAAnd3-KeyTripleDES-CBC']).getBytes()), + // pkcs-12PbeParams + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // salt + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt), + // iteration count + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + countBytes.getBytes()) + ]) + ]); + } else { + var error = new Error('Cannot encrypt private key. Unknown encryption algorithm.'); + error.algorithm = options.algorithm; + throw error; + } + + // EncryptedPrivateKeyInfo + var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // encryptionAlgorithm + encryptionAlgorithm, + // encryptedData + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, encryptedData) + ]); + return rval; +}; + +/** + * Decrypts a ASN.1 PrivateKeyInfo object. + * + * @param obj the ASN.1 EncryptedPrivateKeyInfo object. + * @param password the password to decrypt with. + * + * @return the ASN.1 PrivateKeyInfo on success, null on failure. + */ +pki.decryptPrivateKeyInfo = function(obj, password) { + var rval = null; + + // get PBE params + var capture = {}; + var errors = []; + if(!asn1.validate(obj, encryptedPrivateKeyValidator, capture, errors)) { + var error = new Error('Cannot read encrypted private key. ' + + 'ASN.1 object is not a supported EncryptedPrivateKeyInfo.'); + error.errors = errors; + throw error; + } + + // get cipher + var oid = asn1.derToOid(capture.encryptionOid); + var cipher = pki.pbe.getCipher(oid, capture.encryptionParams, password); + + // get encrypted data + var encrypted = forge.util.createBuffer(capture.encryptedData); + + cipher.update(encrypted); + if(cipher.finish()) { + rval = asn1.fromDer(cipher.output); + } + + return rval; +}; + +/** + * Converts a EncryptedPrivateKeyInfo to PEM format. + * + * @param epki the EncryptedPrivateKeyInfo. + * @param maxline the maximum characters per line, defaults to 64. + * + * @return the PEM-formatted encrypted private key. + */ +pki.encryptedPrivateKeyToPem = function(epki, maxline) { + // convert to DER, then PEM-encode + var msg = { + type: 'ENCRYPTED PRIVATE KEY', + body: asn1.toDer(epki).getBytes() + }; + return forge.pem.encode(msg, {maxline: maxline}); +}; + +/** + * Converts a PEM-encoded EncryptedPrivateKeyInfo to ASN.1 format. Decryption + * is not performed. + * + * @param pem the EncryptedPrivateKeyInfo in PEM-format. + * + * @return the ASN.1 EncryptedPrivateKeyInfo. + */ +pki.encryptedPrivateKeyFromPem = function(pem) { + var msg = forge.pem.decode(pem)[0]; + + if(msg.type !== 'ENCRYPTED PRIVATE KEY') { + var error = new Error('Could not convert encrypted private key from PEM; ' + + 'PEM header type is "ENCRYPTED PRIVATE KEY".'); + error.headerType = msg.type; + throw error; + } + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert encrypted private key from PEM; ' + + 'PEM is encrypted.'); + } + + // convert DER to ASN.1 object + return asn1.fromDer(msg.body); +}; + +/** + * Encrypts an RSA private key. By default, the key will be wrapped in + * a PrivateKeyInfo and encrypted to produce a PKCS#8 EncryptedPrivateKeyInfo. + * This is the standard, preferred way to encrypt a private key. + * + * To produce a non-standard PEM-encrypted private key that uses encapsulated + * headers to indicate the encryption algorithm (old-style non-PKCS#8 OpenSSL + * private key encryption), set the 'legacy' option to true. Note: Using this + * option will cause the iteration count to be forced to 1. + * + * Note: The 'des' algorithm is supported, but it is not considered to be + * secure because it only uses a single 56-bit key. If possible, it is highly + * recommended that a different algorithm be used. + * + * @param rsaKey the RSA key to encrypt. + * @param password the password to use. + * @param options: + * algorithm: the encryption algorithm to use + * ('aes128', 'aes192', 'aes256', '3des', 'des'). + * count: the iteration count to use. + * saltSize: the salt size to use. + * legacy: output an old non-PKCS#8 PEM-encrypted+encapsulated + * headers (DEK-Info) private key. + * + * @return the PEM-encoded ASN.1 EncryptedPrivateKeyInfo. + */ +pki.encryptRsaPrivateKey = function(rsaKey, password, options) { + // standard PKCS#8 + options = options || {}; + if(!options.legacy) { + // encrypt PrivateKeyInfo + var rval = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(rsaKey)); + rval = pki.encryptPrivateKeyInfo(rval, password, options); + return pki.encryptedPrivateKeyToPem(rval); + } + + // legacy non-PKCS#8 + var algorithm; + var iv; + var dkLen; + var cipherFn; + switch(options.algorithm) { + case 'aes128': + algorithm = 'AES-128-CBC'; + dkLen = 16; + iv = forge.random.getBytesSync(16); + cipherFn = forge.aes.createEncryptionCipher; + break; + case 'aes192': + algorithm = 'AES-192-CBC'; + dkLen = 24; + iv = forge.random.getBytesSync(16); + cipherFn = forge.aes.createEncryptionCipher; + break; + case 'aes256': + algorithm = 'AES-256-CBC'; + dkLen = 32; + iv = forge.random.getBytesSync(16); + cipherFn = forge.aes.createEncryptionCipher; + break; + case '3des': + algorithm = 'DES-EDE3-CBC'; + dkLen = 24; + iv = forge.random.getBytesSync(8); + cipherFn = forge.des.createEncryptionCipher; + break; + case 'des': + algorithm = 'DES-CBC'; + dkLen = 8; + iv = forge.random.getBytesSync(8); + cipherFn = forge.des.createEncryptionCipher; + break; + default: + var error = new Error('Could not encrypt RSA private key; unsupported ' + + 'encryption algorithm "' + options.algorithm + '".'); + error.algorithm = options.algorithm; + throw error; + } + + // encrypt private key using OpenSSL legacy key derivation + var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen); + var cipher = cipherFn(dk); + cipher.start(iv); + cipher.update(asn1.toDer(pki.privateKeyToAsn1(rsaKey))); + cipher.finish(); + + var msg = { + type: 'RSA PRIVATE KEY', + procType: { + version: '4', + type: 'ENCRYPTED' + }, + dekInfo: { + algorithm: algorithm, + parameters: forge.util.bytesToHex(iv).toUpperCase() + }, + body: cipher.output.getBytes() + }; + return forge.pem.encode(msg); +}; + +/** + * Decrypts an RSA private key. + * + * @param pem the PEM-formatted EncryptedPrivateKeyInfo to decrypt. + * @param password the password to use. + * + * @return the RSA key on success, null on failure. + */ +pki.decryptRsaPrivateKey = function(pem, password) { + var rval = null; + + var msg = forge.pem.decode(pem)[0]; + + if(msg.type !== 'ENCRYPTED PRIVATE KEY' && + msg.type !== 'PRIVATE KEY' && + msg.type !== 'RSA PRIVATE KEY') { + var error = new Error('Could not convert private key from PEM; PEM header type ' + + 'is not "ENCRYPTED PRIVATE KEY", "PRIVATE KEY", or "RSA PRIVATE KEY".'); + error.headerType = error; + throw error; + } + + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + var dkLen; + var cipherFn; + switch(msg.dekInfo.algorithm) { + case 'DES-CBC': + dkLen = 8; + cipherFn = forge.des.createDecryptionCipher; + break; + case 'DES-EDE3-CBC': + dkLen = 24; + cipherFn = forge.des.createDecryptionCipher; + break; + case 'AES-128-CBC': + dkLen = 16; + cipherFn = forge.aes.createDecryptionCipher; + break; + case 'AES-192-CBC': + dkLen = 24; + cipherFn = forge.aes.createDecryptionCipher; + break; + case 'AES-256-CBC': + dkLen = 32; + cipherFn = forge.aes.createDecryptionCipher; + break; + case 'RC2-40-CBC': + dkLen = 5; + cipherFn = function(key) { + return forge.rc2.createDecryptionCipher(key, 40); + }; + break; + case 'RC2-64-CBC': + dkLen = 8; + cipherFn = function(key) { + return forge.rc2.createDecryptionCipher(key, 64); + }; + break; + case 'RC2-128-CBC': + dkLen = 16; + cipherFn = function(key) { + return forge.rc2.createDecryptionCipher(key, 128); + }; + break; + default: + var error = new Error('Could not decrypt private key; unsupported ' + + 'encryption algorithm "' + msg.dekInfo.algorithm + '".'); + error.algorithm = msg.dekInfo.algorithm; + throw error; + } + + // use OpenSSL legacy key derivation + var iv = forge.util.hexToBytes(msg.dekInfo.parameters); + var dk = forge.pbe.opensslDeriveBytes(password, iv.substr(0, 8), dkLen); + var cipher = cipherFn(dk); + cipher.start(iv); + cipher.update(forge.util.createBuffer(msg.body)); + if(cipher.finish()) { + rval = cipher.output.getBytes(); + } else { + return rval; + } + } else { + rval = msg.body; + } + + if(msg.type === 'ENCRYPTED PRIVATE KEY') { + rval = pki.decryptPrivateKeyInfo(asn1.fromDer(rval), password); + } else { + // decryption already performed above + rval = asn1.fromDer(rval); + } + + if(rval !== null) { + rval = pki.privateKeyFromAsn1(rval); + } + + return rval; +}; + +/** + * Derives a PKCS#12 key. + * + * @param password the password to derive the key material from, null or + * undefined for none. + * @param salt the salt, as a ByteBuffer, to use. + * @param id the PKCS#12 ID byte (1 = key material, 2 = IV, 3 = MAC). + * @param iter the iteration count. + * @param n the number of bytes to derive from the password. + * @param md the message digest to use, defaults to SHA-1. + * + * @return a ByteBuffer with the bytes derived from the password. + */ +pki.pbe.generatePkcs12Key = function(password, salt, id, iter, n, md) { + var j, l; + + if(typeof md === 'undefined' || md === null) { + if(!('sha1' in forge.md)) { + throw new Error('"sha1" hash algorithm unavailable.'); + } + md = forge.md.sha1.create(); + } + + var u = md.digestLength; + var v = md.blockLength; + var result = new forge.util.ByteBuffer(); + + /* Convert password to Unicode byte buffer + trailing 0-byte. */ + var passBuf = new forge.util.ByteBuffer(); + if(password !== null && password !== undefined) { + for(l = 0; l < password.length; l++) { + passBuf.putInt16(password.charCodeAt(l)); + } + passBuf.putInt16(0); + } + + /* Length of salt and password in BYTES. */ + var p = passBuf.length(); + var s = salt.length(); + + /* 1. Construct a string, D (the "diversifier"), by concatenating + v copies of ID. */ + var D = new forge.util.ByteBuffer(); + D.fillWithByte(id, v); + + /* 2. Concatenate copies of the salt together to create a string S of length + v * ceil(s / v) bytes (the final copy of the salt may be trunacted + to create S). + Note that if the salt is the empty string, then so is S. */ + var Slen = v * Math.ceil(s / v); + var S = new forge.util.ByteBuffer(); + for(l = 0; l < Slen; l++) { + S.putByte(salt.at(l % s)); + } + + /* 3. Concatenate copies of the password together to create a string P of + length v * ceil(p / v) bytes (the final copy of the password may be + truncated to create P). + Note that if the password is the empty string, then so is P. */ + var Plen = v * Math.ceil(p / v); + var P = new forge.util.ByteBuffer(); + for(l = 0; l < Plen; l++) { + P.putByte(passBuf.at(l % p)); + } + + /* 4. Set I=S||P to be the concatenation of S and P. */ + var I = S; + I.putBuffer(P); + + /* 5. Set c=ceil(n / u). */ + var c = Math.ceil(n / u); + + /* 6. For i=1, 2, ..., c, do the following: */ + for(var i = 1; i <= c; i++) { + /* a) Set Ai=H^r(D||I). (l.e. the rth hash of D||I, H(H(H(...H(D||I)))) */ + var buf = new forge.util.ByteBuffer(); + buf.putBytes(D.bytes()); + buf.putBytes(I.bytes()); + for(var round = 0; round < iter; round++) { + md.start(); + md.update(buf.getBytes()); + buf = md.digest(); + } + + /* b) Concatenate copies of Ai to create a string B of length v bytes (the + final copy of Ai may be truncated to create B). */ + var B = new forge.util.ByteBuffer(); + for(l = 0; l < v; l++) { + B.putByte(buf.at(l % u)); + } + + /* c) Treating I as a concatenation I0, I1, ..., Ik-1 of v-byte blocks, + where k=ceil(s / v) + ceil(p / v), modify I by setting + Ij=(Ij+B+1) mod 2v for each j. */ + var k = Math.ceil(s / v) + Math.ceil(p / v); + var Inew = new forge.util.ByteBuffer(); + for(j = 0; j < k; j++) { + var chunk = new forge.util.ByteBuffer(I.getBytes(v)); + var x = 0x1ff; + for(l = B.length() - 1; l >= 0; l--) { + x = x >> 8; + x += B.at(l) + chunk.at(l); + chunk.setAt(l, x & 0xff); + } + Inew.putBuffer(chunk); + } + I = Inew; + + /* Add Ai to A. */ + result.putBuffer(buf); + } + + result.truncate(result.length() - n); + return result; +}; + +/** + * Get new Forge cipher object instance. + * + * @param oid the OID (in string notation). + * @param params the ASN.1 params object. + * @param password the password to decrypt with. + * + * @return new cipher object instance. + */ +pki.pbe.getCipher = function(oid, params, password) { + switch(oid) { + case pki.oids['pkcs5PBES2']: + return pki.pbe.getCipherForPBES2(oid, params, password); + + case pki.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']: + case pki.oids['pbewithSHAAnd40BitRC2-CBC']: + return pki.pbe.getCipherForPKCS12PBE(oid, params, password); + + default: + var error = new Error('Cannot read encrypted PBE data block. Unsupported OID.'); + error.oid = oid; + error.supportedOids = [ + 'pkcs5PBES2', + 'pbeWithSHAAnd3-KeyTripleDES-CBC', + 'pbewithSHAAnd40BitRC2-CBC' + ]; + throw error; + } +}; + +/** + * Get new Forge cipher object instance according to PBES2 params block. + * + * The returned cipher instance is already started using the IV + * from PBES2 parameter block. + * + * @param oid the PKCS#5 PBKDF2 OID (in string notation). + * @param params the ASN.1 PBES2-params object. + * @param password the password to decrypt with. + * + * @return new cipher object instance. + */ +pki.pbe.getCipherForPBES2 = function(oid, params, password) { + // get PBE params + var capture = {}; + var errors = []; + if(!asn1.validate(params, PBES2AlgorithmsValidator, capture, errors)) { + var error = new Error('Cannot read password-based-encryption algorithm ' + + 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.'); + error.errors = errors; + throw error; + } + + // check oids + oid = asn1.derToOid(capture.kdfOid); + if(oid !== pki.oids['pkcs5PBKDF2']) { + var error = new Error('Cannot read encrypted private key. ' + + 'Unsupported key derivation function OID.'); + error.oid = oid; + error.supportedOids = ['pkcs5PBKDF2']; + throw error; + } + oid = asn1.derToOid(capture.encOid); + if(oid !== pki.oids['aes128-CBC'] && + oid !== pki.oids['aes192-CBC'] && + oid !== pki.oids['aes256-CBC'] && + oid !== pki.oids['des-EDE3-CBC'] && + oid !== pki.oids['desCBC']) { + var error = new Error('Cannot read encrypted private key. ' + + 'Unsupported encryption scheme OID.'); + error.oid = oid; + error.supportedOids = [ + 'aes128-CBC', 'aes192-CBC', 'aes256-CBC', 'des-EDE3-CBC', 'desCBC']; + throw error; + } + + // set PBE params + var salt = capture.kdfSalt; + var count = forge.util.createBuffer(capture.kdfIterationCount); + count = count.getInt(count.length() << 3); + var dkLen; + var cipherFn; + switch(pki.oids[oid]) { + case 'aes128-CBC': + dkLen = 16; + cipherFn = forge.aes.createDecryptionCipher; + break; + case 'aes192-CBC': + dkLen = 24; + cipherFn = forge.aes.createDecryptionCipher; + break; + case 'aes256-CBC': + dkLen = 32; + cipherFn = forge.aes.createDecryptionCipher; + break; + case 'des-EDE3-CBC': + dkLen = 24; + cipherFn = forge.des.createDecryptionCipher; + break; + case 'desCBC': + dkLen = 8; + cipherFn = forge.des.createDecryptionCipher; + break; + } + + // get PRF message digest + var md = prfOidToMessageDigest(capture.prfOid); + + // decrypt private key using pbe with chosen PRF and AES/DES + var dk = forge.pkcs5.pbkdf2(password, salt, count, dkLen, md); + var iv = capture.encIv; + var cipher = cipherFn(dk); + cipher.start(iv); + + return cipher; +}; + +/** + * Get new Forge cipher object instance for PKCS#12 PBE. + * + * The returned cipher instance is already started using the key & IV + * derived from the provided password and PKCS#12 PBE salt. + * + * @param oid The PKCS#12 PBE OID (in string notation). + * @param params The ASN.1 PKCS#12 PBE-params object. + * @param password The password to decrypt with. + * + * @return the new cipher object instance. + */ +pki.pbe.getCipherForPKCS12PBE = function(oid, params, password) { + // get PBE params + var capture = {}; + var errors = []; + if(!asn1.validate(params, pkcs12PbeParamsValidator, capture, errors)) { + var error = new Error('Cannot read password-based-encryption algorithm ' + + 'parameters. ASN.1 object is not a supported EncryptedPrivateKeyInfo.'); + error.errors = errors; + throw error; + } + + var salt = forge.util.createBuffer(capture.salt); + var count = forge.util.createBuffer(capture.iterations); + count = count.getInt(count.length() << 3); + + var dkLen, dIvLen, cipherFn; + switch(oid) { + case pki.oids['pbeWithSHAAnd3-KeyTripleDES-CBC']: + dkLen = 24; + dIvLen = 8; + cipherFn = forge.des.startDecrypting; + break; + + case pki.oids['pbewithSHAAnd40BitRC2-CBC']: + dkLen = 5; + dIvLen = 8; + cipherFn = function(key, iv) { + var cipher = forge.rc2.createDecryptionCipher(key, 40); + cipher.start(iv, null); + return cipher; + }; + break; + + default: + var error = new Error('Cannot read PKCS #12 PBE data block. Unsupported OID.'); + error.oid = oid; + throw error; + } + + // get PRF message digest + var md = prfOidToMessageDigest(capture.prfOid); + var key = pki.pbe.generatePkcs12Key(password, salt, 1, count, dkLen, md); + md.start(); + var iv = pki.pbe.generatePkcs12Key(password, salt, 2, count, dIvLen, md); + + return cipherFn(key, iv); +}; + +/** + * OpenSSL's legacy key derivation function. + * + * See: http://www.openssl.org/docs/crypto/EVP_BytesToKey.html + * + * @param password the password to derive the key from. + * @param salt the salt to use, null for none. + * @param dkLen the number of bytes needed for the derived key. + * @param [options] the options to use: + * [md] an optional message digest object to use. + */ +pki.pbe.opensslDeriveBytes = function(password, salt, dkLen, md) { + if(typeof md === 'undefined' || md === null) { + if(!('md5' in forge.md)) { + throw new Error('"md5" hash algorithm unavailable.'); + } + md = forge.md.md5.create(); + } + if(salt === null) { + salt = ''; + } + var digests = [hash(md, password + salt)]; + for(var length = 16, i = 1; length < dkLen; ++i, length += 16) { + digests.push(hash(md, digests[i - 1] + password + salt)); + } + return digests.join('').substr(0, dkLen); +}; + +function hash(md, bytes) { + return md.start().update(bytes).digest().getBytes(); +} + +function prfOidToMessageDigest(prfOid) { + // get PRF algorithm, default to SHA-1 + var prfAlgorithm; + if(!prfOid) { + prfAlgorithm = 'hmacWithSHA1'; + } else { + prfAlgorithm = pki.oids[asn1.derToOid(prfOid)]; + if(!prfAlgorithm) { + var error = new Error('Unsupported PRF OID.'); + error.oid = prfOid; + error.supported = [ + 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384', + 'hmacWithSHA512']; + throw error; + } + } + return prfAlgorithmToMessageDigest(prfAlgorithm); +} + +function prfAlgorithmToMessageDigest(prfAlgorithm) { + var factory = forge.md; + switch(prfAlgorithm) { + case 'hmacWithSHA224': + factory = forge.md.sha512; + case 'hmacWithSHA1': + case 'hmacWithSHA256': + case 'hmacWithSHA384': + case 'hmacWithSHA512': + prfAlgorithm = prfAlgorithm.substr(8).toLowerCase(); + break; + default: + var error = new Error('Unsupported PRF algorithm.'); + error.algorithm = prfAlgorithm; + error.supported = [ + 'hmacWithSHA1', 'hmacWithSHA224', 'hmacWithSHA256', 'hmacWithSHA384', + 'hmacWithSHA512']; + throw error; + } + if(!factory || !(prfAlgorithm in factory)) { + throw new Error('Unknown hash algorithm: ' + prfAlgorithm); + } + return factory[prfAlgorithm].create(); +} + +function createPbkdf2Params(salt, countBytes, dkLen, prfAlgorithm) { + var params = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // salt + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, salt), + // iteration count + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + countBytes.getBytes()) + ]); + // when PRF algorithm is not SHA-1 default, add key length and PRF algorithm + if(prfAlgorithm !== 'hmacWithSHA1') { + params.value.push( + // key length + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + forge.util.hexToBytes(dkLen.toString(16))), + // AlgorithmIdentifier + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(pki.oids[prfAlgorithm]).getBytes()), + // parameters (null) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ])); + } + return params; +} diff --git a/node_modules/node-forge/lib/pbkdf2.js b/node_modules/node-forge/lib/pbkdf2.js new file mode 100644 index 0000000..714560e --- /dev/null +++ b/node_modules/node-forge/lib/pbkdf2.js @@ -0,0 +1,211 @@ +/** + * Password-Based Key-Derivation Function #2 implementation. + * + * See RFC 2898 for details. + * + * @author Dave Longley + * + * Copyright (c) 2010-2013 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./hmac'); +require('./md'); +require('./util'); + +var pkcs5 = forge.pkcs5 = forge.pkcs5 || {}; + +var crypto; +if(forge.util.isNodejs && !forge.options.usePureJavaScript) { + crypto = require('crypto'); +} + +/** + * Derives a key from a password. + * + * @param p the password as a binary-encoded string of bytes. + * @param s the salt as a binary-encoded string of bytes. + * @param c the iteration count, a positive integer. + * @param dkLen the intended length, in bytes, of the derived key, + * (max: 2^32 - 1) * hash length of the PRF. + * @param [md] the message digest (or algorithm identifier as a string) to use + * in the PRF, defaults to SHA-1. + * @param [callback(err, key)] presence triggers asynchronous version, called + * once the operation completes. + * + * @return the derived key, as a binary-encoded string of bytes, for the + * synchronous version (if no callback is specified). + */ +module.exports = forge.pbkdf2 = pkcs5.pbkdf2 = function( + p, s, c, dkLen, md, callback) { + if(typeof md === 'function') { + callback = md; + md = null; + } + + // use native implementation if possible and not disabled, note that + // some node versions only support SHA-1, others allow digest to be changed + if(forge.util.isNodejs && !forge.options.usePureJavaScript && + crypto.pbkdf2 && (md === null || typeof md !== 'object') && + (crypto.pbkdf2Sync.length > 4 || (!md || md === 'sha1'))) { + if(typeof md !== 'string') { + // default prf to SHA-1 + md = 'sha1'; + } + p = Buffer.from(p, 'binary'); + s = Buffer.from(s, 'binary'); + if(!callback) { + if(crypto.pbkdf2Sync.length === 4) { + return crypto.pbkdf2Sync(p, s, c, dkLen).toString('binary'); + } + return crypto.pbkdf2Sync(p, s, c, dkLen, md).toString('binary'); + } + if(crypto.pbkdf2Sync.length === 4) { + return crypto.pbkdf2(p, s, c, dkLen, function(err, key) { + if(err) { + return callback(err); + } + callback(null, key.toString('binary')); + }); + } + return crypto.pbkdf2(p, s, c, dkLen, md, function(err, key) { + if(err) { + return callback(err); + } + callback(null, key.toString('binary')); + }); + } + + if(typeof md === 'undefined' || md === null) { + // default prf to SHA-1 + md = 'sha1'; + } + if(typeof md === 'string') { + if(!(md in forge.md.algorithms)) { + throw new Error('Unknown hash algorithm: ' + md); + } + md = forge.md[md].create(); + } + + var hLen = md.digestLength; + + /* 1. If dkLen > (2^32 - 1) * hLen, output "derived key too long" and + stop. */ + if(dkLen > (0xFFFFFFFF * hLen)) { + var err = new Error('Derived key is too long.'); + if(callback) { + return callback(err); + } + throw err; + } + + /* 2. Let len be the number of hLen-octet blocks in the derived key, + rounding up, and let r be the number of octets in the last + block: + + len = CEIL(dkLen / hLen), + r = dkLen - (len - 1) * hLen. */ + var len = Math.ceil(dkLen / hLen); + var r = dkLen - (len - 1) * hLen; + + /* 3. For each block of the derived key apply the function F defined + below to the password P, the salt S, the iteration count c, and + the block index to compute the block: + + T_1 = F(P, S, c, 1), + T_2 = F(P, S, c, 2), + ... + T_len = F(P, S, c, len), + + where the function F is defined as the exclusive-or sum of the + first c iterates of the underlying pseudorandom function PRF + applied to the password P and the concatenation of the salt S + and the block index i: + + F(P, S, c, i) = u_1 XOR u_2 XOR ... XOR u_c + + where + + u_1 = PRF(P, S || INT(i)), + u_2 = PRF(P, u_1), + ... + u_c = PRF(P, u_{c-1}). + + Here, INT(i) is a four-octet encoding of the integer i, most + significant octet first. */ + var prf = forge.hmac.create(); + prf.start(md, p); + var dk = ''; + var xor, u_c, u_c1; + + // sync version + if(!callback) { + for(var i = 1; i <= len; ++i) { + // PRF(P, S || INT(i)) (first iteration) + prf.start(null, null); + prf.update(s); + prf.update(forge.util.int32ToBytes(i)); + xor = u_c1 = prf.digest().getBytes(); + + // PRF(P, u_{c-1}) (other iterations) + for(var j = 2; j <= c; ++j) { + prf.start(null, null); + prf.update(u_c1); + u_c = prf.digest().getBytes(); + // F(p, s, c, i) + xor = forge.util.xorBytes(xor, u_c, hLen); + u_c1 = u_c; + } + + /* 4. Concatenate the blocks and extract the first dkLen octets to + produce a derived key DK: + + DK = T_1 || T_2 || ... || T_len<0..r-1> */ + dk += (i < len) ? xor : xor.substr(0, r); + } + /* 5. Output the derived key DK. */ + return dk; + } + + // async version + var i = 1, j; + function outer() { + if(i > len) { + // done + return callback(null, dk); + } + + // PRF(P, S || INT(i)) (first iteration) + prf.start(null, null); + prf.update(s); + prf.update(forge.util.int32ToBytes(i)); + xor = u_c1 = prf.digest().getBytes(); + + // PRF(P, u_{c-1}) (other iterations) + j = 2; + inner(); + } + + function inner() { + if(j <= c) { + prf.start(null, null); + prf.update(u_c1); + u_c = prf.digest().getBytes(); + // F(p, s, c, i) + xor = forge.util.xorBytes(xor, u_c, hLen); + u_c1 = u_c; + ++j; + return forge.util.setImmediate(inner); + } + + /* 4. Concatenate the blocks and extract the first dkLen octets to + produce a derived key DK: + + DK = T_1 || T_2 || ... || T_len<0..r-1> */ + dk += (i < len) ? xor : xor.substr(0, r); + + ++i; + outer(); + } + + outer(); +}; diff --git a/node_modules/node-forge/lib/pem.js b/node_modules/node-forge/lib/pem.js new file mode 100644 index 0000000..aed8bdf --- /dev/null +++ b/node_modules/node-forge/lib/pem.js @@ -0,0 +1,230 @@ +/** + * Javascript implementation of basic PEM (Privacy Enhanced Mail) algorithms. + * + * See: RFC 1421. + * + * @author Dave Longley + * + * Copyright (c) 2013-2014 Digital Bazaar, Inc. + * + * A Forge PEM object has the following fields: + * + * type: identifies the type of message (eg: "RSA PRIVATE KEY"). + * + * procType: identifies the type of processing performed on the message, + * it has two subfields: version and type, eg: 4,ENCRYPTED. + * + * contentDomain: identifies the type of content in the message, typically + * only uses the value: "RFC822". + * + * dekInfo: identifies the message encryption algorithm and mode and includes + * any parameters for the algorithm, it has two subfields: algorithm and + * parameters, eg: DES-CBC,F8143EDE5960C597. + * + * headers: contains all other PEM encapsulated headers -- where order is + * significant (for pairing data like recipient ID + key info). + * + * body: the binary-encoded body. + */ +var forge = require('./forge'); +require('./util'); + +// shortcut for pem API +var pem = module.exports = forge.pem = forge.pem || {}; + +/** + * Encodes (serializes) the given PEM object. + * + * @param msg the PEM message object to encode. + * @param options the options to use: + * maxline the maximum characters per line for the body, (default: 64). + * + * @return the PEM-formatted string. + */ +pem.encode = function(msg, options) { + options = options || {}; + var rval = '-----BEGIN ' + msg.type + '-----\r\n'; + + // encode special headers + var header; + if(msg.procType) { + header = { + name: 'Proc-Type', + values: [String(msg.procType.version), msg.procType.type] + }; + rval += foldHeader(header); + } + if(msg.contentDomain) { + header = {name: 'Content-Domain', values: [msg.contentDomain]}; + rval += foldHeader(header); + } + if(msg.dekInfo) { + header = {name: 'DEK-Info', values: [msg.dekInfo.algorithm]}; + if(msg.dekInfo.parameters) { + header.values.push(msg.dekInfo.parameters); + } + rval += foldHeader(header); + } + + if(msg.headers) { + // encode all other headers + for(var i = 0; i < msg.headers.length; ++i) { + rval += foldHeader(msg.headers[i]); + } + } + + // terminate header + if(msg.procType) { + rval += '\r\n'; + } + + // add body + rval += forge.util.encode64(msg.body, options.maxline || 64) + '\r\n'; + + rval += '-----END ' + msg.type + '-----\r\n'; + return rval; +}; + +/** + * Decodes (deserializes) all PEM messages found in the given string. + * + * @param str the PEM-formatted string to decode. + * + * @return the PEM message objects in an array. + */ +pem.decode = function(str) { + var rval = []; + + // split string into PEM messages (be lenient w/EOF on BEGIN line) + var rMessage = /\s*-----BEGIN ([A-Z0-9- ]+)-----\r?\n?([\x21-\x7e\s]+?(?:\r?\n\r?\n))?([:A-Za-z0-9+\/=\s]+?)-----END \1-----/g; + var rHeader = /([\x21-\x7e]+):\s*([\x21-\x7e\s^:]+)/; + var rCRLF = /\r?\n/; + var match; + while(true) { + match = rMessage.exec(str); + if(!match) { + break; + } + + var msg = { + type: match[1], + procType: null, + contentDomain: null, + dekInfo: null, + headers: [], + body: forge.util.decode64(match[3]) + }; + rval.push(msg); + + // no headers + if(!match[2]) { + continue; + } + + // parse headers + var lines = match[2].split(rCRLF); + var li = 0; + while(match && li < lines.length) { + // get line, trim any rhs whitespace + var line = lines[li].replace(/\s+$/, ''); + + // RFC2822 unfold any following folded lines + for(var nl = li + 1; nl < lines.length; ++nl) { + var next = lines[nl]; + if(!/\s/.test(next[0])) { + break; + } + line += next; + li = nl; + } + + // parse header + match = line.match(rHeader); + if(match) { + var header = {name: match[1], values: []}; + var values = match[2].split(','); + for(var vi = 0; vi < values.length; ++vi) { + header.values.push(ltrim(values[vi])); + } + + // Proc-Type must be the first header + if(!msg.procType) { + if(header.name !== 'Proc-Type') { + throw new Error('Invalid PEM formatted message. The first ' + + 'encapsulated header must be "Proc-Type".'); + } else if(header.values.length !== 2) { + throw new Error('Invalid PEM formatted message. The "Proc-Type" ' + + 'header must have two subfields.'); + } + msg.procType = {version: values[0], type: values[1]}; + } else if(!msg.contentDomain && header.name === 'Content-Domain') { + // special-case Content-Domain + msg.contentDomain = values[0] || ''; + } else if(!msg.dekInfo && header.name === 'DEK-Info') { + // special-case DEK-Info + if(header.values.length === 0) { + throw new Error('Invalid PEM formatted message. The "DEK-Info" ' + + 'header must have at least one subfield.'); + } + msg.dekInfo = {algorithm: values[0], parameters: values[1] || null}; + } else { + msg.headers.push(header); + } + } + + ++li; + } + + if(msg.procType === 'ENCRYPTED' && !msg.dekInfo) { + throw new Error('Invalid PEM formatted message. The "DEK-Info" ' + + 'header must be present if "Proc-Type" is "ENCRYPTED".'); + } + } + + if(rval.length === 0) { + throw new Error('Invalid PEM formatted message.'); + } + + return rval; +}; + +function foldHeader(header) { + var rval = header.name + ': '; + + // ensure values with CRLF are folded + var values = []; + var insertSpace = function(match, $1) { + return ' ' + $1; + }; + for(var i = 0; i < header.values.length; ++i) { + values.push(header.values[i].replace(/^(\S+\r\n)/, insertSpace)); + } + rval += values.join(',') + '\r\n'; + + // do folding + var length = 0; + var candidate = -1; + for(var i = 0; i < rval.length; ++i, ++length) { + if(length > 65 && candidate !== -1) { + var insert = rval[candidate]; + if(insert === ',') { + ++candidate; + rval = rval.substr(0, candidate) + '\r\n ' + rval.substr(candidate); + } else { + rval = rval.substr(0, candidate) + + '\r\n' + insert + rval.substr(candidate + 1); + } + length = (i - candidate - 1); + candidate = -1; + ++i; + } else if(rval[i] === ' ' || rval[i] === '\t' || rval[i] === ',') { + candidate = i; + } + } + + return rval; +} + +function ltrim(str) { + return str.replace(/^\s+/, ''); +} diff --git a/node_modules/node-forge/lib/pkcs1.js b/node_modules/node-forge/lib/pkcs1.js new file mode 100644 index 0000000..a3af924 --- /dev/null +++ b/node_modules/node-forge/lib/pkcs1.js @@ -0,0 +1,276 @@ +/** + * Partial implementation of PKCS#1 v2.2: RSA-OEAP + * + * Modified but based on the following MIT and BSD licensed code: + * + * https://github.com/kjur/jsjws/blob/master/rsa.js: + * + * The 'jsjws'(JSON Web Signature JavaScript Library) License + * + * Copyright (c) 2012 Kenji Urushima + * + * 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. + * + * http://webrsa.cvs.sourceforge.net/viewvc/webrsa/Client/RSAES-OAEP.js?content-type=text%2Fplain: + * + * RSAES-OAEP.js + * $Id: RSAES-OAEP.js,v 1.1.1.1 2003/03/19 15:37:20 ellispritchard Exp $ + * JavaScript Implementation of PKCS #1 v2.1 RSA CRYPTOGRAPHY STANDARD (RSA Laboratories, June 14, 2002) + * Copyright (C) Ellis Pritchard, Guardian Unlimited 2003. + * Contact: ellis@nukinetics.com + * Distributed under the BSD License. + * + * Official documentation: http://www.rsa.com/rsalabs/node.asp?id=2125 + * + * @author Evan Jones (http://evanjones.ca/) + * @author Dave Longley + * + * Copyright (c) 2013-2014 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./util'); +require('./random'); +require('./sha1'); + +// shortcut for PKCS#1 API +var pkcs1 = module.exports = forge.pkcs1 = forge.pkcs1 || {}; + +/** + * Encode the given RSAES-OAEP message (M) using key, with optional label (L) + * and seed. + * + * This method does not perform RSA encryption, it only encodes the message + * using RSAES-OAEP. + * + * @param key the RSA key to use. + * @param message the message to encode. + * @param options the options to use: + * label an optional label to use. + * seed the seed to use. + * md the message digest object to use, undefined for SHA-1. + * mgf1 optional mgf1 parameters: + * md the message digest object to use for MGF1. + * + * @return the encoded message bytes. + */ +pkcs1.encode_rsa_oaep = function(key, message, options) { + // parse arguments + var label; + var seed; + var md; + var mgf1Md; + // legacy args (label, seed, md) + if(typeof options === 'string') { + label = options; + seed = arguments[3] || undefined; + md = arguments[4] || undefined; + } else if(options) { + label = options.label || undefined; + seed = options.seed || undefined; + md = options.md || undefined; + if(options.mgf1 && options.mgf1.md) { + mgf1Md = options.mgf1.md; + } + } + + // default OAEP to SHA-1 message digest + if(!md) { + md = forge.md.sha1.create(); + } else { + md.start(); + } + + // default MGF-1 to same as OAEP + if(!mgf1Md) { + mgf1Md = md; + } + + // compute length in bytes and check output + var keyLength = Math.ceil(key.n.bitLength() / 8); + var maxLength = keyLength - 2 * md.digestLength - 2; + if(message.length > maxLength) { + var error = new Error('RSAES-OAEP input message length is too long.'); + error.length = message.length; + error.maxLength = maxLength; + throw error; + } + + if(!label) { + label = ''; + } + md.update(label, 'raw'); + var lHash = md.digest(); + + var PS = ''; + var PS_length = maxLength - message.length; + for(var i = 0; i < PS_length; i++) { + PS += '\x00'; + } + + var DB = lHash.getBytes() + PS + '\x01' + message; + + if(!seed) { + seed = forge.random.getBytes(md.digestLength); + } else if(seed.length !== md.digestLength) { + var error = new Error('Invalid RSAES-OAEP seed. The seed length must ' + + 'match the digest length.'); + error.seedLength = seed.length; + error.digestLength = md.digestLength; + throw error; + } + + var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md); + var maskedDB = forge.util.xorBytes(DB, dbMask, DB.length); + + var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md); + var maskedSeed = forge.util.xorBytes(seed, seedMask, seed.length); + + // return encoded message + return '\x00' + maskedSeed + maskedDB; +}; + +/** + * Decode the given RSAES-OAEP encoded message (EM) using key, with optional + * label (L). + * + * This method does not perform RSA decryption, it only decodes the message + * using RSAES-OAEP. + * + * @param key the RSA key to use. + * @param em the encoded message to decode. + * @param options the options to use: + * label an optional label to use. + * md the message digest object to use for OAEP, undefined for SHA-1. + * mgf1 optional mgf1 parameters: + * md the message digest object to use for MGF1. + * + * @return the decoded message bytes. + */ +pkcs1.decode_rsa_oaep = function(key, em, options) { + // parse args + var label; + var md; + var mgf1Md; + // legacy args + if(typeof options === 'string') { + label = options; + md = arguments[3] || undefined; + } else if(options) { + label = options.label || undefined; + md = options.md || undefined; + if(options.mgf1 && options.mgf1.md) { + mgf1Md = options.mgf1.md; + } + } + + // compute length in bytes + var keyLength = Math.ceil(key.n.bitLength() / 8); + + if(em.length !== keyLength) { + var error = new Error('RSAES-OAEP encoded message length is invalid.'); + error.length = em.length; + error.expectedLength = keyLength; + throw error; + } + + // default OAEP to SHA-1 message digest + if(md === undefined) { + md = forge.md.sha1.create(); + } else { + md.start(); + } + + // default MGF-1 to same as OAEP + if(!mgf1Md) { + mgf1Md = md; + } + + if(keyLength < 2 * md.digestLength + 2) { + throw new Error('RSAES-OAEP key is too short for the hash function.'); + } + + if(!label) { + label = ''; + } + md.update(label, 'raw'); + var lHash = md.digest().getBytes(); + + // split the message into its parts + var y = em.charAt(0); + var maskedSeed = em.substring(1, md.digestLength + 1); + var maskedDB = em.substring(1 + md.digestLength); + + var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md); + var seed = forge.util.xorBytes(maskedSeed, seedMask, maskedSeed.length); + + var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md); + var db = forge.util.xorBytes(maskedDB, dbMask, maskedDB.length); + + var lHashPrime = db.substring(0, md.digestLength); + + // constant time check that all values match what is expected + var error = (y !== '\x00'); + + // constant time check lHash vs lHashPrime + for(var i = 0; i < md.digestLength; ++i) { + error |= (lHash.charAt(i) !== lHashPrime.charAt(i)); + } + + // "constant time" find the 0x1 byte separating the padding (zeros) from the + // message + // TODO: It must be possible to do this in a better/smarter way? + var in_ps = 1; + var index = md.digestLength; + for(var j = md.digestLength; j < db.length; j++) { + var code = db.charCodeAt(j); + + var is_0 = (code & 0x1) ^ 0x1; + + // non-zero if not 0 or 1 in the ps section + var error_mask = in_ps ? 0xfffe : 0x0000; + error |= (code & error_mask); + + // latch in_ps to zero after we find 0x1 + in_ps = in_ps & is_0; + index += in_ps; + } + + if(error || db.charCodeAt(index) !== 0x1) { + throw new Error('Invalid RSAES-OAEP padding.'); + } + + return db.substring(index + 1); +}; + +function rsa_mgf1(seed, maskLength, hash) { + // default to SHA-1 message digest + if(!hash) { + hash = forge.md.sha1.create(); + } + var t = ''; + var count = Math.ceil(maskLength / hash.digestLength); + for(var i = 0; i < count; ++i) { + var c = String.fromCharCode( + (i >> 24) & 0xFF, (i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF); + hash.start(); + hash.update(seed + c); + t += hash.digest().getBytes(); + } + return t.substring(0, maskLength); +} diff --git a/node_modules/node-forge/lib/pkcs12.js b/node_modules/node-forge/lib/pkcs12.js new file mode 100644 index 0000000..cd06c49 --- /dev/null +++ b/node_modules/node-forge/lib/pkcs12.js @@ -0,0 +1,1074 @@ +/** + * Javascript implementation of PKCS#12. + * + * @author Dave Longley + * @author Stefan Siegl + * + * Copyright (c) 2010-2014 Digital Bazaar, Inc. + * Copyright (c) 2012 Stefan Siegl + * + * The ASN.1 representation of PKCS#12 is as follows + * (see ftp://ftp.rsasecurity.com/pub/pkcs/pkcs-12/pkcs-12-tc1.pdf for details) + * + * PFX ::= SEQUENCE { + * version INTEGER {v3(3)}(v3,...), + * authSafe ContentInfo, + * macData MacData OPTIONAL + * } + * + * MacData ::= SEQUENCE { + * mac DigestInfo, + * macSalt OCTET STRING, + * iterations INTEGER DEFAULT 1 + * } + * Note: The iterations default is for historical reasons and its use is + * deprecated. A higher value, like 1024, is recommended. + * + * DigestInfo is defined in PKCS#7 as follows: + * + * DigestInfo ::= SEQUENCE { + * digestAlgorithm DigestAlgorithmIdentifier, + * digest Digest + * } + * + * DigestAlgorithmIdentifier ::= AlgorithmIdentifier + * + * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters + * for the algorithm, if any. In the case of SHA1 there is none. + * + * AlgorithmIdentifer ::= SEQUENCE { + * algorithm OBJECT IDENTIFIER, + * parameters ANY DEFINED BY algorithm OPTIONAL + * } + * + * Digest ::= OCTET STRING + * + * + * ContentInfo ::= SEQUENCE { + * contentType ContentType, + * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL + * } + * + * ContentType ::= OBJECT IDENTIFIER + * + * AuthenticatedSafe ::= SEQUENCE OF ContentInfo + * -- Data if unencrypted + * -- EncryptedData if password-encrypted + * -- EnvelopedData if public key-encrypted + * + * + * SafeContents ::= SEQUENCE OF SafeBag + * + * SafeBag ::= SEQUENCE { + * bagId BAG-TYPE.&id ({PKCS12BagSet}) + * bagValue [0] EXPLICIT BAG-TYPE.&Type({PKCS12BagSet}{@bagId}), + * bagAttributes SET OF PKCS12Attribute OPTIONAL + * } + * + * PKCS12Attribute ::= SEQUENCE { + * attrId ATTRIBUTE.&id ({PKCS12AttrSet}), + * attrValues SET OF ATTRIBUTE.&Type ({PKCS12AttrSet}{@attrId}) + * } -- This type is compatible with the X.500 type 'Attribute' + * + * PKCS12AttrSet ATTRIBUTE ::= { + * friendlyName | -- from PKCS #9 + * localKeyId, -- from PKCS #9 + * ... -- Other attributes are allowed + * } + * + * CertBag ::= SEQUENCE { + * certId BAG-TYPE.&id ({CertTypes}), + * certValue [0] EXPLICIT BAG-TYPE.&Type ({CertTypes}{@certId}) + * } + * + * x509Certificate BAG-TYPE ::= {OCTET STRING IDENTIFIED BY {certTypes 1}} + * -- DER-encoded X.509 certificate stored in OCTET STRING + * + * sdsiCertificate BAG-TYPE ::= {IA5String IDENTIFIED BY {certTypes 2}} + * -- Base64-encoded SDSI certificate stored in IA5String + * + * CertTypes BAG-TYPE ::= { + * x509Certificate | + * sdsiCertificate, + * ... -- For future extensions + * } + */ +var forge = require('./forge'); +require('./asn1'); +require('./hmac'); +require('./oids'); +require('./pkcs7asn1'); +require('./pbe'); +require('./random'); +require('./rsa'); +require('./sha1'); +require('./util'); +require('./x509'); + +// shortcut for asn.1 & PKI API +var asn1 = forge.asn1; +var pki = forge.pki; + +// shortcut for PKCS#12 API +var p12 = module.exports = forge.pkcs12 = forge.pkcs12 || {}; + +var contentInfoValidator = { + name: 'ContentInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, // a ContentInfo + constructed: true, + value: [{ + name: 'ContentInfo.contentType', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'contentType' + }, { + name: 'ContentInfo.content', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + constructed: true, + captureAsn1: 'content' + }] +}; + +var pfxValidator = { + name: 'PFX', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'PFX.version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'version' + }, + contentInfoValidator, { + name: 'PFX.macData', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + optional: true, + captureAsn1: 'mac', + value: [{ + name: 'PFX.macData.mac', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, // DigestInfo + constructed: true, + value: [{ + name: 'PFX.macData.mac.digestAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, // DigestAlgorithmIdentifier + constructed: true, + value: [{ + name: 'PFX.macData.mac.digestAlgorithm.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'macAlgorithm' + }, { + name: 'PFX.macData.mac.digestAlgorithm.parameters', + tagClass: asn1.Class.UNIVERSAL, + captureAsn1: 'macAlgorithmParameters' + }] + }, { + name: 'PFX.macData.mac.digest', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'macDigest' + }] + }, { + name: 'PFX.macData.macSalt', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'macSalt' + }, { + name: 'PFX.macData.iterations', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + optional: true, + capture: 'macIterations' + }] + }] +}; + +var safeBagValidator = { + name: 'SafeBag', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'SafeBag.bagId', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'bagId' + }, { + name: 'SafeBag.bagValue', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + constructed: true, + captureAsn1: 'bagValue' + }, { + name: 'SafeBag.bagAttributes', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + constructed: true, + optional: true, + capture: 'bagAttributes' + }] +}; + +var attributeValidator = { + name: 'Attribute', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'Attribute.attrId', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'oid' + }, { + name: 'Attribute.attrValues', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + constructed: true, + capture: 'values' + }] +}; + +var certBagValidator = { + name: 'CertBag', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'CertBag.certId', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'certId' + }, { + name: 'CertBag.certValue', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + constructed: true, + /* So far we only support X.509 certificates (which are wrapped in + an OCTET STRING, hence hard code that here). */ + value: [{ + name: 'CertBag.certValue[0]', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Class.OCTETSTRING, + constructed: false, + capture: 'cert' + }] + }] +}; + +/** + * Search SafeContents structure for bags with matching attributes. + * + * The search can optionally be narrowed by a certain bag type. + * + * @param safeContents the SafeContents structure to search in. + * @param attrName the name of the attribute to compare against. + * @param attrValue the attribute value to search for. + * @param [bagType] bag type to narrow search by. + * + * @return an array of matching bags. + */ +function _getBagsByAttribute(safeContents, attrName, attrValue, bagType) { + var result = []; + + for(var i = 0; i < safeContents.length; i++) { + for(var j = 0; j < safeContents[i].safeBags.length; j++) { + var bag = safeContents[i].safeBags[j]; + if(bagType !== undefined && bag.type !== bagType) { + continue; + } + // only filter by bag type, no attribute specified + if(attrName === null) { + result.push(bag); + continue; + } + if(bag.attributes[attrName] !== undefined && + bag.attributes[attrName].indexOf(attrValue) >= 0) { + result.push(bag); + } + } + } + + return result; +} + +/** + * Converts a PKCS#12 PFX in ASN.1 notation into a PFX object. + * + * @param obj The PKCS#12 PFX in ASN.1 notation. + * @param strict true to use strict DER decoding, false not to (default: true). + * @param {String} password Password to decrypt with (optional). + * + * @return PKCS#12 PFX object. + */ +p12.pkcs12FromAsn1 = function(obj, strict, password) { + // handle args + if(typeof strict === 'string') { + password = strict; + strict = true; + } else if(strict === undefined) { + strict = true; + } + + // validate PFX and capture data + var capture = {}; + var errors = []; + if(!asn1.validate(obj, pfxValidator, capture, errors)) { + var error = new Error('Cannot read PKCS#12 PFX. ' + + 'ASN.1 object is not an PKCS#12 PFX.'); + error.errors = error; + throw error; + } + + var pfx = { + version: capture.version.charCodeAt(0), + safeContents: [], + + /** + * Gets bags with matching attributes. + * + * @param filter the attributes to filter by: + * [localKeyId] the localKeyId to search for. + * [localKeyIdHex] the localKeyId in hex to search for. + * [friendlyName] the friendly name to search for. + * [bagType] bag type to narrow each attribute search by. + * + * @return a map of attribute type to an array of matching bags or, if no + * attribute was given but a bag type, the map key will be the + * bag type. + */ + getBags: function(filter) { + var rval = {}; + + var localKeyId; + if('localKeyId' in filter) { + localKeyId = filter.localKeyId; + } else if('localKeyIdHex' in filter) { + localKeyId = forge.util.hexToBytes(filter.localKeyIdHex); + } + + // filter on bagType only + if(localKeyId === undefined && !('friendlyName' in filter) && + 'bagType' in filter) { + rval[filter.bagType] = _getBagsByAttribute( + pfx.safeContents, null, null, filter.bagType); + } + + if(localKeyId !== undefined) { + rval.localKeyId = _getBagsByAttribute( + pfx.safeContents, 'localKeyId', + localKeyId, filter.bagType); + } + if('friendlyName' in filter) { + rval.friendlyName = _getBagsByAttribute( + pfx.safeContents, 'friendlyName', + filter.friendlyName, filter.bagType); + } + + return rval; + }, + + /** + * DEPRECATED: use getBags() instead. + * + * Get bags with matching friendlyName attribute. + * + * @param friendlyName the friendly name to search for. + * @param [bagType] bag type to narrow search by. + * + * @return an array of bags with matching friendlyName attribute. + */ + getBagsByFriendlyName: function(friendlyName, bagType) { + return _getBagsByAttribute( + pfx.safeContents, 'friendlyName', friendlyName, bagType); + }, + + /** + * DEPRECATED: use getBags() instead. + * + * Get bags with matching localKeyId attribute. + * + * @param localKeyId the localKeyId to search for. + * @param [bagType] bag type to narrow search by. + * + * @return an array of bags with matching localKeyId attribute. + */ + getBagsByLocalKeyId: function(localKeyId, bagType) { + return _getBagsByAttribute( + pfx.safeContents, 'localKeyId', localKeyId, bagType); + } + }; + + if(capture.version.charCodeAt(0) !== 3) { + var error = new Error('PKCS#12 PFX of version other than 3 not supported.'); + error.version = capture.version.charCodeAt(0); + throw error; + } + + if(asn1.derToOid(capture.contentType) !== pki.oids.data) { + var error = new Error('Only PKCS#12 PFX in password integrity mode supported.'); + error.oid = asn1.derToOid(capture.contentType); + throw error; + } + + var data = capture.content.value[0]; + if(data.tagClass !== asn1.Class.UNIVERSAL || + data.type !== asn1.Type.OCTETSTRING) { + throw new Error('PKCS#12 authSafe content data is not an OCTET STRING.'); + } + data = _decodePkcs7Data(data); + + // check for MAC + if(capture.mac) { + var md = null; + var macKeyBytes = 0; + var macAlgorithm = asn1.derToOid(capture.macAlgorithm); + switch(macAlgorithm) { + case pki.oids.sha1: + md = forge.md.sha1.create(); + macKeyBytes = 20; + break; + case pki.oids.sha256: + md = forge.md.sha256.create(); + macKeyBytes = 32; + break; + case pki.oids.sha384: + md = forge.md.sha384.create(); + macKeyBytes = 48; + break; + case pki.oids.sha512: + md = forge.md.sha512.create(); + macKeyBytes = 64; + break; + case pki.oids.md5: + md = forge.md.md5.create(); + macKeyBytes = 16; + break; + } + if(md === null) { + throw new Error('PKCS#12 uses unsupported MAC algorithm: ' + macAlgorithm); + } + + // verify MAC (iterations default to 1) + var macSalt = new forge.util.ByteBuffer(capture.macSalt); + var macIterations = (('macIterations' in capture) ? + parseInt(forge.util.bytesToHex(capture.macIterations), 16) : 1); + var macKey = p12.generateKey( + password, macSalt, 3, macIterations, macKeyBytes, md); + var mac = forge.hmac.create(); + mac.start(md, macKey); + mac.update(data.value); + var macValue = mac.getMac(); + if(macValue.getBytes() !== capture.macDigest) { + throw new Error('PKCS#12 MAC could not be verified. Invalid password?'); + } + } + + _decodeAuthenticatedSafe(pfx, data.value, strict, password); + return pfx; +}; + +/** + * Decodes PKCS#7 Data. PKCS#7 (RFC 2315) defines "Data" as an OCTET STRING, + * but it is sometimes an OCTET STRING that is composed/constructed of chunks, + * each its own OCTET STRING. This is BER-encoding vs. DER-encoding. This + * function transforms this corner-case into the usual simple, + * non-composed/constructed OCTET STRING. + * + * This function may be moved to ASN.1 at some point to better deal with + * more BER-encoding issues, should they arise. + * + * @param data the ASN.1 Data object to transform. + */ +function _decodePkcs7Data(data) { + // handle special case of "chunked" data content: an octet string composed + // of other octet strings + if(data.composed || data.constructed) { + var value = forge.util.createBuffer(); + for(var i = 0; i < data.value.length; ++i) { + value.putBytes(data.value[i].value); + } + data.composed = data.constructed = false; + data.value = value.getBytes(); + } + return data; +} + +/** + * Decode PKCS#12 AuthenticatedSafe (BER encoded) into PFX object. + * + * The AuthenticatedSafe is a BER-encoded SEQUENCE OF ContentInfo. + * + * @param pfx The PKCS#12 PFX object to fill. + * @param {String} authSafe BER-encoded AuthenticatedSafe. + * @param strict true to use strict DER decoding, false not to. + * @param {String} password Password to decrypt with (optional). + */ +function _decodeAuthenticatedSafe(pfx, authSafe, strict, password) { + authSafe = asn1.fromDer(authSafe, strict); /* actually it's BER encoded */ + + if(authSafe.tagClass !== asn1.Class.UNIVERSAL || + authSafe.type !== asn1.Type.SEQUENCE || + authSafe.constructed !== true) { + throw new Error('PKCS#12 AuthenticatedSafe expected to be a ' + + 'SEQUENCE OF ContentInfo'); + } + + for(var i = 0; i < authSafe.value.length; i++) { + var contentInfo = authSafe.value[i]; + + // validate contentInfo and capture data + var capture = {}; + var errors = []; + if(!asn1.validate(contentInfo, contentInfoValidator, capture, errors)) { + var error = new Error('Cannot read ContentInfo.'); + error.errors = errors; + throw error; + } + + var obj = { + encrypted: false + }; + var safeContents = null; + var data = capture.content.value[0]; + switch(asn1.derToOid(capture.contentType)) { + case pki.oids.data: + if(data.tagClass !== asn1.Class.UNIVERSAL || + data.type !== asn1.Type.OCTETSTRING) { + throw new Error('PKCS#12 SafeContents Data is not an OCTET STRING.'); + } + safeContents = _decodePkcs7Data(data).value; + break; + case pki.oids.encryptedData: + safeContents = _decryptSafeContents(data, password); + obj.encrypted = true; + break; + default: + var error = new Error('Unsupported PKCS#12 contentType.'); + error.contentType = asn1.derToOid(capture.contentType); + throw error; + } + + obj.safeBags = _decodeSafeContents(safeContents, strict, password); + pfx.safeContents.push(obj); + } +} + +/** + * Decrypt PKCS#7 EncryptedData structure. + * + * @param data ASN.1 encoded EncryptedContentInfo object. + * @param password The user-provided password. + * + * @return The decrypted SafeContents (ASN.1 object). + */ +function _decryptSafeContents(data, password) { + var capture = {}; + var errors = []; + if(!asn1.validate( + data, forge.pkcs7.asn1.encryptedDataValidator, capture, errors)) { + var error = new Error('Cannot read EncryptedContentInfo.'); + error.errors = errors; + throw error; + } + + var oid = asn1.derToOid(capture.contentType); + if(oid !== pki.oids.data) { + var error = new Error( + 'PKCS#12 EncryptedContentInfo ContentType is not Data.'); + error.oid = oid; + throw error; + } + + // get cipher + oid = asn1.derToOid(capture.encAlgorithm); + var cipher = pki.pbe.getCipher(oid, capture.encParameter, password); + + // get encrypted data + var encryptedContentAsn1 = _decodePkcs7Data(capture.encryptedContentAsn1); + var encrypted = forge.util.createBuffer(encryptedContentAsn1.value); + + cipher.update(encrypted); + if(!cipher.finish()) { + throw new Error('Failed to decrypt PKCS#12 SafeContents.'); + } + + return cipher.output.getBytes(); +} + +/** + * Decode PKCS#12 SafeContents (BER-encoded) into array of Bag objects. + * + * The safeContents is a BER-encoded SEQUENCE OF SafeBag. + * + * @param {String} safeContents BER-encoded safeContents. + * @param strict true to use strict DER decoding, false not to. + * @param {String} password Password to decrypt with (optional). + * + * @return {Array} Array of Bag objects. + */ +function _decodeSafeContents(safeContents, strict, password) { + // if strict and no safe contents, return empty safes + if(!strict && safeContents.length === 0) { + return []; + } + + // actually it's BER-encoded + safeContents = asn1.fromDer(safeContents, strict); + + if(safeContents.tagClass !== asn1.Class.UNIVERSAL || + safeContents.type !== asn1.Type.SEQUENCE || + safeContents.constructed !== true) { + throw new Error( + 'PKCS#12 SafeContents expected to be a SEQUENCE OF SafeBag.'); + } + + var res = []; + for(var i = 0; i < safeContents.value.length; i++) { + var safeBag = safeContents.value[i]; + + // validate SafeBag and capture data + var capture = {}; + var errors = []; + if(!asn1.validate(safeBag, safeBagValidator, capture, errors)) { + var error = new Error('Cannot read SafeBag.'); + error.errors = errors; + throw error; + } + + /* Create bag object and push to result array. */ + var bag = { + type: asn1.derToOid(capture.bagId), + attributes: _decodeBagAttributes(capture.bagAttributes) + }; + res.push(bag); + + var validator, decoder; + var bagAsn1 = capture.bagValue.value[0]; + switch(bag.type) { + case pki.oids.pkcs8ShroudedKeyBag: + /* bagAsn1 has a EncryptedPrivateKeyInfo, which we need to decrypt. + Afterwards we can handle it like a keyBag, + which is a PrivateKeyInfo. */ + bagAsn1 = pki.decryptPrivateKeyInfo(bagAsn1, password); + if(bagAsn1 === null) { + throw new Error( + 'Unable to decrypt PKCS#8 ShroudedKeyBag, wrong password?'); + } + + /* fall through */ + case pki.oids.keyBag: + /* A PKCS#12 keyBag is a simple PrivateKeyInfo as understood by our + PKI module, hence we don't have to do validation/capturing here, + just pass what we already got. */ + try { + bag.key = pki.privateKeyFromAsn1(bagAsn1); + } catch(e) { + // ignore unknown key type, pass asn1 value + bag.key = null; + bag.asn1 = bagAsn1; + } + continue; /* Nothing more to do. */ + + case pki.oids.certBag: + /* A PKCS#12 certBag can wrap both X.509 and sdsi certificates. + Therefore put the SafeBag content through another validator to + capture the fields. Afterwards check & store the results. */ + validator = certBagValidator; + decoder = function() { + if(asn1.derToOid(capture.certId) !== pki.oids.x509Certificate) { + var error = new Error( + 'Unsupported certificate type, only X.509 supported.'); + error.oid = asn1.derToOid(capture.certId); + throw error; + } + + // true=produce cert hash + var certAsn1 = asn1.fromDer(capture.cert, strict); + try { + bag.cert = pki.certificateFromAsn1(certAsn1, true); + } catch(e) { + // ignore unknown cert type, pass asn1 value + bag.cert = null; + bag.asn1 = certAsn1; + } + }; + break; + + default: + var error = new Error('Unsupported PKCS#12 SafeBag type.'); + error.oid = bag.type; + throw error; + } + + /* Validate SafeBag value (i.e. CertBag, etc.) and capture data if needed. */ + if(validator !== undefined && + !asn1.validate(bagAsn1, validator, capture, errors)) { + var error = new Error('Cannot read PKCS#12 ' + validator.name); + error.errors = errors; + throw error; + } + + /* Call decoder function from above to store the results. */ + decoder(); + } + + return res; +} + +/** + * Decode PKCS#12 SET OF PKCS12Attribute into JavaScript object. + * + * @param attributes SET OF PKCS12Attribute (ASN.1 object). + * + * @return the decoded attributes. + */ +function _decodeBagAttributes(attributes) { + var decodedAttrs = {}; + + if(attributes !== undefined) { + for(var i = 0; i < attributes.length; ++i) { + var capture = {}; + var errors = []; + if(!asn1.validate(attributes[i], attributeValidator, capture, errors)) { + var error = new Error('Cannot read PKCS#12 BagAttribute.'); + error.errors = errors; + throw error; + } + + var oid = asn1.derToOid(capture.oid); + if(pki.oids[oid] === undefined) { + // unsupported attribute type, ignore. + continue; + } + + decodedAttrs[pki.oids[oid]] = []; + for(var j = 0; j < capture.values.length; ++j) { + decodedAttrs[pki.oids[oid]].push(capture.values[j].value); + } + } + } + + return decodedAttrs; +} + +/** + * Wraps a private key and certificate in a PKCS#12 PFX wrapper. If a + * password is provided then the private key will be encrypted. + * + * An entire certificate chain may also be included. To do this, pass + * an array for the "cert" parameter where the first certificate is + * the one that is paired with the private key and each subsequent one + * verifies the previous one. The certificates may be in PEM format or + * have been already parsed by Forge. + * + * @todo implement password-based-encryption for the whole package + * + * @param key the private key. + * @param cert the certificate (may be an array of certificates in order + * to specify a certificate chain). + * @param password the password to use, null for none. + * @param options: + * algorithm the encryption algorithm to use + * ('aes128', 'aes192', 'aes256', '3des'), defaults to 'aes128'. + * count the iteration count to use. + * saltSize the salt size to use. + * useMac true to include a MAC, false not to, defaults to true. + * localKeyId the local key ID to use, in hex. + * friendlyName the friendly name to use. + * generateLocalKeyId true to generate a random local key ID, + * false not to, defaults to true. + * + * @return the PKCS#12 PFX ASN.1 object. + */ +p12.toPkcs12Asn1 = function(key, cert, password, options) { + // set default options + options = options || {}; + options.saltSize = options.saltSize || 8; + options.count = options.count || 2048; + options.algorithm = options.algorithm || options.encAlgorithm || 'aes128'; + if(!('useMac' in options)) { + options.useMac = true; + } + if(!('localKeyId' in options)) { + options.localKeyId = null; + } + if(!('generateLocalKeyId' in options)) { + options.generateLocalKeyId = true; + } + + var localKeyId = options.localKeyId; + var bagAttrs; + if(localKeyId !== null) { + localKeyId = forge.util.hexToBytes(localKeyId); + } else if(options.generateLocalKeyId) { + // use SHA-1 of paired cert, if available + if(cert) { + var pairedCert = forge.util.isArray(cert) ? cert[0] : cert; + if(typeof pairedCert === 'string') { + pairedCert = pki.certificateFromPem(pairedCert); + } + var sha1 = forge.md.sha1.create(); + sha1.update(asn1.toDer(pki.certificateToAsn1(pairedCert)).getBytes()); + localKeyId = sha1.digest().getBytes(); + } else { + // FIXME: consider using SHA-1 of public key (which can be generated + // from private key components), see: cert.generateSubjectKeyIdentifier + // generate random bytes + localKeyId = forge.random.getBytes(20); + } + } + + var attrs = []; + if(localKeyId !== null) { + attrs.push( + // localKeyID + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // attrId + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(pki.oids.localKeyId).getBytes()), + // attrValues + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + localKeyId) + ]) + ])); + } + if('friendlyName' in options) { + attrs.push( + // friendlyName + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // attrId + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(pki.oids.friendlyName).getBytes()), + // attrValues + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BMPSTRING, false, + options.friendlyName) + ]) + ])); + } + + if(attrs.length > 0) { + bagAttrs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, attrs); + } + + // collect contents for AuthenticatedSafe + var contents = []; + + // create safe bag(s) for certificate chain + var chain = []; + if(cert !== null) { + if(forge.util.isArray(cert)) { + chain = cert; + } else { + chain = [cert]; + } + } + + var certSafeBags = []; + for(var i = 0; i < chain.length; ++i) { + // convert cert from PEM as necessary + cert = chain[i]; + if(typeof cert === 'string') { + cert = pki.certificateFromPem(cert); + } + + // SafeBag + var certBagAttrs = (i === 0) ? bagAttrs : undefined; + var certAsn1 = pki.certificateToAsn1(cert); + var certSafeBag = + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // bagId + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(pki.oids.certBag).getBytes()), + // bagValue + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + // CertBag + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // certId + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(pki.oids.x509Certificate).getBytes()), + // certValue (x509Certificate) + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + asn1.toDer(certAsn1).getBytes()) + ])])]), + // bagAttributes (OPTIONAL) + certBagAttrs + ]); + certSafeBags.push(certSafeBag); + } + + if(certSafeBags.length > 0) { + // SafeContents + var certSafeContents = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, certSafeBags); + + // ContentInfo + var certCI = + // PKCS#7 ContentInfo + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // contentType + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + // OID for the content type is 'data' + asn1.oidToDer(pki.oids.data).getBytes()), + // content + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + asn1.toDer(certSafeContents).getBytes()) + ]) + ]); + contents.push(certCI); + } + + // create safe contents for private key + var keyBag = null; + if(key !== null) { + // SafeBag + var pkAsn1 = pki.wrapRsaPrivateKey(pki.privateKeyToAsn1(key)); + if(password === null) { + // no encryption + keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // bagId + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(pki.oids.keyBag).getBytes()), + // bagValue + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + // PrivateKeyInfo + pkAsn1 + ]), + // bagAttributes (OPTIONAL) + bagAttrs + ]); + } else { + // encrypted PrivateKeyInfo + keyBag = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // bagId + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(pki.oids.pkcs8ShroudedKeyBag).getBytes()), + // bagValue + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + // EncryptedPrivateKeyInfo + pki.encryptPrivateKeyInfo(pkAsn1, password, options) + ]), + // bagAttributes (OPTIONAL) + bagAttrs + ]); + } + + // SafeContents + var keySafeContents = + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [keyBag]); + + // ContentInfo + var keyCI = + // PKCS#7 ContentInfo + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // contentType + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + // OID for the content type is 'data' + asn1.oidToDer(pki.oids.data).getBytes()), + // content + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + asn1.toDer(keySafeContents).getBytes()) + ]) + ]); + contents.push(keyCI); + } + + // create AuthenticatedSafe by stringing together the contents + var safe = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, contents); + + var macData; + if(options.useMac) { + // MacData + var sha1 = forge.md.sha1.create(); + var macSalt = new forge.util.ByteBuffer( + forge.random.getBytes(options.saltSize)); + var count = options.count; + // 160-bit key + var key = p12.generateKey(password, macSalt, 3, count, 20); + var mac = forge.hmac.create(); + mac.start(sha1, key); + mac.update(asn1.toDer(safe).getBytes()); + var macValue = mac.getMac(); + macData = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // mac DigestInfo + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // digestAlgorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm = SHA-1 + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(pki.oids.sha1).getBytes()), + // parameters = Null + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ]), + // digest + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, + false, macValue.getBytes()) + ]), + // macSalt OCTET STRING + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, macSalt.getBytes()), + // iterations INTEGER (XXX: Only support count < 65536) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(count).getBytes() + ) + ]); + } + + // PFX + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // version (3) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(3).getBytes()), + // PKCS#7 ContentInfo + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // contentType + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + // OID for the content type is 'data' + asn1.oidToDer(pki.oids.data).getBytes()), + // content + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + asn1.toDer(safe).getBytes()) + ]) + ]), + macData + ]); +}; + +/** + * Derives a PKCS#12 key. + * + * @param password the password to derive the key material from, null or + * undefined for none. + * @param salt the salt, as a ByteBuffer, to use. + * @param id the PKCS#12 ID byte (1 = key material, 2 = IV, 3 = MAC). + * @param iter the iteration count. + * @param n the number of bytes to derive from the password. + * @param md the message digest to use, defaults to SHA-1. + * + * @return a ByteBuffer with the bytes derived from the password. + */ +p12.generateKey = forge.pbe.generatePkcs12Key; diff --git a/node_modules/node-forge/lib/pkcs7.js b/node_modules/node-forge/lib/pkcs7.js new file mode 100644 index 0000000..bb87de3 --- /dev/null +++ b/node_modules/node-forge/lib/pkcs7.js @@ -0,0 +1,1257 @@ +/** + * Javascript implementation of PKCS#7 v1.5. + * + * @author Stefan Siegl + * @author Dave Longley + * + * Copyright (c) 2012 Stefan Siegl + * Copyright (c) 2012-2015 Digital Bazaar, Inc. + * + * Currently this implementation only supports ContentType of EnvelopedData, + * EncryptedData, or SignedData at the root level. The top level elements may + * contain only a ContentInfo of ContentType Data, i.e. plain data. Further + * nesting is not (yet) supported. + * + * The Forge validators for PKCS #7's ASN.1 structures are available from + * a separate file pkcs7asn1.js, since those are referenced from other + * PKCS standards like PKCS #12. + */ +var forge = require('./forge'); +require('./aes'); +require('./asn1'); +require('./des'); +require('./oids'); +require('./pem'); +require('./pkcs7asn1'); +require('./random'); +require('./util'); +require('./x509'); + +// shortcut for ASN.1 API +var asn1 = forge.asn1; + +// shortcut for PKCS#7 API +var p7 = module.exports = forge.pkcs7 = forge.pkcs7 || {}; + +/** + * Converts a PKCS#7 message from PEM format. + * + * @param pem the PEM-formatted PKCS#7 message. + * + * @return the PKCS#7 message. + */ +p7.messageFromPem = function(pem) { + var msg = forge.pem.decode(pem)[0]; + + if(msg.type !== 'PKCS7') { + var error = new Error('Could not convert PKCS#7 message from PEM; PEM ' + + 'header type is not "PKCS#7".'); + error.headerType = msg.type; + throw error; + } + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert PKCS#7 message from PEM; PEM is encrypted.'); + } + + // convert DER to ASN.1 object + var obj = asn1.fromDer(msg.body); + + return p7.messageFromAsn1(obj); +}; + +/** + * Converts a PKCS#7 message to PEM format. + * + * @param msg The PKCS#7 message object + * @param maxline The maximum characters per line, defaults to 64. + * + * @return The PEM-formatted PKCS#7 message. + */ +p7.messageToPem = function(msg, maxline) { + // convert to ASN.1, then DER, then PEM-encode + var pemObj = { + type: 'PKCS7', + body: asn1.toDer(msg.toAsn1()).getBytes() + }; + return forge.pem.encode(pemObj, {maxline: maxline}); +}; + +/** + * Converts a PKCS#7 message from an ASN.1 object. + * + * @param obj the ASN.1 representation of a ContentInfo. + * + * @return the PKCS#7 message. + */ +p7.messageFromAsn1 = function(obj) { + // validate root level ContentInfo and capture data + var capture = {}; + var errors = []; + if(!asn1.validate(obj, p7.asn1.contentInfoValidator, capture, errors)) { + var error = new Error('Cannot read PKCS#7 message. ' + + 'ASN.1 object is not an PKCS#7 ContentInfo.'); + error.errors = errors; + throw error; + } + + var contentType = asn1.derToOid(capture.contentType); + var msg; + + switch(contentType) { + case forge.pki.oids.envelopedData: + msg = p7.createEnvelopedData(); + break; + + case forge.pki.oids.encryptedData: + msg = p7.createEncryptedData(); + break; + + case forge.pki.oids.signedData: + msg = p7.createSignedData(); + break; + + default: + throw new Error('Cannot read PKCS#7 message. ContentType with OID ' + + contentType + ' is not (yet) supported.'); + } + + msg.fromAsn1(capture.content.value[0]); + return msg; +}; + +p7.createSignedData = function() { + var msg = null; + msg = { + type: forge.pki.oids.signedData, + version: 1, + certificates: [], + crls: [], + // TODO: add json-formatted signer stuff here? + signers: [], + // populated during sign() + digestAlgorithmIdentifiers: [], + contentInfo: null, + signerInfos: [], + + fromAsn1: function(obj) { + // validate SignedData content block and capture data. + _fromAsn1(msg, obj, p7.asn1.signedDataValidator); + msg.certificates = []; + msg.crls = []; + msg.digestAlgorithmIdentifiers = []; + msg.contentInfo = null; + msg.signerInfos = []; + + if(msg.rawCapture.certificates) { + var certs = msg.rawCapture.certificates.value; + for(var i = 0; i < certs.length; ++i) { + msg.certificates.push(forge.pki.certificateFromAsn1(certs[i])); + } + } + + // TODO: parse crls + }, + + toAsn1: function() { + // degenerate case with no content + if(!msg.contentInfo) { + msg.sign(); + } + + var certs = []; + for(var i = 0; i < msg.certificates.length; ++i) { + certs.push(forge.pki.certificateToAsn1(msg.certificates[i])); + } + + var crls = []; + // TODO: implement CRLs + + // [0] SignedData + var signedData = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Version + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(msg.version).getBytes()), + // DigestAlgorithmIdentifiers + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SET, true, + msg.digestAlgorithmIdentifiers), + // ContentInfo + msg.contentInfo + ]) + ]); + if(certs.length > 0) { + // [0] IMPLICIT ExtendedCertificatesAndCertificates OPTIONAL + signedData.value[0].value.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, certs)); + } + if(crls.length > 0) { + // [1] IMPLICIT CertificateRevocationLists OPTIONAL + signedData.value[0].value.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, crls)); + } + // SignerInfos + signedData.value[0].value.push( + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, + msg.signerInfos)); + + // ContentInfo + return asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // ContentType + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(msg.type).getBytes()), + // [0] SignedData + signedData + ]); + }, + + /** + * Add (another) entity to list of signers. + * + * Note: If authenticatedAttributes are provided, then, per RFC 2315, + * they must include at least two attributes: content type and + * message digest. The message digest attribute value will be + * auto-calculated during signing and will be ignored if provided. + * + * Here's an example of providing these two attributes: + * + * forge.pkcs7.createSignedData(); + * p7.addSigner({ + * issuer: cert.issuer.attributes, + * serialNumber: cert.serialNumber, + * key: privateKey, + * digestAlgorithm: forge.pki.oids.sha1, + * authenticatedAttributes: [{ + * type: forge.pki.oids.contentType, + * value: forge.pki.oids.data + * }, { + * type: forge.pki.oids.messageDigest + * }] + * }); + * + * TODO: Support [subjectKeyIdentifier] as signer's ID. + * + * @param signer the signer information: + * key the signer's private key. + * [certificate] a certificate containing the public key + * associated with the signer's private key; use this option as + * an alternative to specifying signer.issuer and + * signer.serialNumber. + * [issuer] the issuer attributes (eg: cert.issuer.attributes). + * [serialNumber] the signer's certificate's serial number in + * hexadecimal (eg: cert.serialNumber). + * [digestAlgorithm] the message digest OID, as a string, to use + * (eg: forge.pki.oids.sha1). + * [authenticatedAttributes] an optional array of attributes + * to also sign along with the content. + */ + addSigner: function(signer) { + var issuer = signer.issuer; + var serialNumber = signer.serialNumber; + if(signer.certificate) { + var cert = signer.certificate; + if(typeof cert === 'string') { + cert = forge.pki.certificateFromPem(cert); + } + issuer = cert.issuer.attributes; + serialNumber = cert.serialNumber; + } + var key = signer.key; + if(!key) { + throw new Error( + 'Could not add PKCS#7 signer; no private key specified.'); + } + if(typeof key === 'string') { + key = forge.pki.privateKeyFromPem(key); + } + + // ensure OID known for digest algorithm + var digestAlgorithm = signer.digestAlgorithm || forge.pki.oids.sha1; + switch(digestAlgorithm) { + case forge.pki.oids.sha1: + case forge.pki.oids.sha256: + case forge.pki.oids.sha384: + case forge.pki.oids.sha512: + case forge.pki.oids.md5: + break; + default: + throw new Error( + 'Could not add PKCS#7 signer; unknown message digest algorithm: ' + + digestAlgorithm); + } + + // if authenticatedAttributes is present, then the attributes + // must contain at least PKCS #9 content-type and message-digest + var authenticatedAttributes = signer.authenticatedAttributes || []; + if(authenticatedAttributes.length > 0) { + var contentType = false; + var messageDigest = false; + for(var i = 0; i < authenticatedAttributes.length; ++i) { + var attr = authenticatedAttributes[i]; + if(!contentType && attr.type === forge.pki.oids.contentType) { + contentType = true; + if(messageDigest) { + break; + } + continue; + } + if(!messageDigest && attr.type === forge.pki.oids.messageDigest) { + messageDigest = true; + if(contentType) { + break; + } + continue; + } + } + + if(!contentType || !messageDigest) { + throw new Error('Invalid signer.authenticatedAttributes. If ' + + 'signer.authenticatedAttributes is specified, then it must ' + + 'contain at least two attributes, PKCS #9 content-type and ' + + 'PKCS #9 message-digest.'); + } + } + + msg.signers.push({ + key: key, + version: 1, + issuer: issuer, + serialNumber: serialNumber, + digestAlgorithm: digestAlgorithm, + signatureAlgorithm: forge.pki.oids.rsaEncryption, + signature: null, + authenticatedAttributes: authenticatedAttributes, + unauthenticatedAttributes: [] + }); + }, + + /** + * Signs the content. + * @param options Options to apply when signing: + * [detached] boolean. If signing should be done in detached mode. Defaults to false. + */ + sign: function(options) { + options = options || {}; + // auto-generate content info + if(typeof msg.content !== 'object' || msg.contentInfo === null) { + // use Data ContentInfo + msg.contentInfo = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // ContentType + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(forge.pki.oids.data).getBytes()) + ]); + + // add actual content, if present + if('content' in msg) { + var content; + if(msg.content instanceof forge.util.ByteBuffer) { + content = msg.content.bytes(); + } else if(typeof msg.content === 'string') { + content = forge.util.encodeUtf8(msg.content); + } + + if (options.detached) { + msg.detachedContent = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, content); + } else { + msg.contentInfo.value.push( + // [0] EXPLICIT content + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + content) + ])); + } + } + } + + // no signers, return early (degenerate case for certificate container) + if(msg.signers.length === 0) { + return; + } + + // generate digest algorithm identifiers + var mds = addDigestAlgorithmIds(); + + // generate signerInfos + addSignerInfos(mds); + }, + + verify: function() { + throw new Error('PKCS#7 signature verification not yet implemented.'); + }, + + /** + * Add a certificate. + * + * @param cert the certificate to add. + */ + addCertificate: function(cert) { + // convert from PEM + if(typeof cert === 'string') { + cert = forge.pki.certificateFromPem(cert); + } + msg.certificates.push(cert); + }, + + /** + * Add a certificate revokation list. + * + * @param crl the certificate revokation list to add. + */ + addCertificateRevokationList: function(crl) { + throw new Error('PKCS#7 CRL support not yet implemented.'); + } + }; + return msg; + + function addDigestAlgorithmIds() { + var mds = {}; + + for(var i = 0; i < msg.signers.length; ++i) { + var signer = msg.signers[i]; + var oid = signer.digestAlgorithm; + if(!(oid in mds)) { + // content digest + mds[oid] = forge.md[forge.pki.oids[oid]].create(); + } + if(signer.authenticatedAttributes.length === 0) { + // no custom attributes to digest; use content message digest + signer.md = mds[oid]; + } else { + // custom attributes to be digested; use own message digest + // TODO: optimize to just copy message digest state if that + // feature is ever supported with message digests + signer.md = forge.md[forge.pki.oids[oid]].create(); + } + } + + // add unique digest algorithm identifiers + msg.digestAlgorithmIdentifiers = []; + for(var oid in mds) { + msg.digestAlgorithmIdentifiers.push( + // AlgorithmIdentifier + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(oid).getBytes()), + // parameters (null) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ])); + } + + return mds; + } + + function addSignerInfos(mds) { + var content; + + if (msg.detachedContent) { + // Signature has been made in detached mode. + content = msg.detachedContent; + } else { + // Note: ContentInfo is a SEQUENCE with 2 values, second value is + // the content field and is optional for a ContentInfo but required here + // since signers are present + // get ContentInfo content + content = msg.contentInfo.value[1]; + // skip [0] EXPLICIT content wrapper + content = content.value[0]; + } + + if(!content) { + throw new Error( + 'Could not sign PKCS#7 message; there is no content to sign.'); + } + + // get ContentInfo content type + var contentType = asn1.derToOid(msg.contentInfo.value[0].value); + + // serialize content + var bytes = asn1.toDer(content); + + // skip identifier and length per RFC 2315 9.3 + // skip identifier (1 byte) + bytes.getByte(); + // read and discard length bytes + asn1.getBerValueLength(bytes); + bytes = bytes.getBytes(); + + // digest content DER value bytes + for(var oid in mds) { + mds[oid].start().update(bytes); + } + + // sign content + var signingTime = new Date(); + for(var i = 0; i < msg.signers.length; ++i) { + var signer = msg.signers[i]; + + if(signer.authenticatedAttributes.length === 0) { + // if ContentInfo content type is not "Data", then + // authenticatedAttributes must be present per RFC 2315 + if(contentType !== forge.pki.oids.data) { + throw new Error( + 'Invalid signer; authenticatedAttributes must be present ' + + 'when the ContentInfo content type is not PKCS#7 Data.'); + } + } else { + // process authenticated attributes + // [0] IMPLICIT + signer.authenticatedAttributesAsn1 = asn1.create( + asn1.Class.CONTEXT_SPECIFIC, 0, true, []); + + // per RFC 2315, attributes are to be digested using a SET container + // not the above [0] IMPLICIT container + var attrsAsn1 = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SET, true, []); + + for(var ai = 0; ai < signer.authenticatedAttributes.length; ++ai) { + var attr = signer.authenticatedAttributes[ai]; + if(attr.type === forge.pki.oids.messageDigest) { + // use content message digest as value + attr.value = mds[signer.digestAlgorithm].digest(); + } else if(attr.type === forge.pki.oids.signingTime) { + // auto-populate signing time if not already set + if(!attr.value) { + attr.value = signingTime; + } + } + + // convert to ASN.1 and push onto Attributes SET (for signing) and + // onto authenticatedAttributesAsn1 to complete SignedData ASN.1 + // TODO: optimize away duplication + attrsAsn1.value.push(_attributeToAsn1(attr)); + signer.authenticatedAttributesAsn1.value.push(_attributeToAsn1(attr)); + } + + // DER-serialize and digest SET OF attributes only + bytes = asn1.toDer(attrsAsn1).getBytes(); + signer.md.start().update(bytes); + } + + // sign digest + signer.signature = signer.key.sign(signer.md, 'RSASSA-PKCS1-V1_5'); + } + + // add signer info + msg.signerInfos = _signersToAsn1(msg.signers); + } +}; + +/** + * Creates an empty PKCS#7 message of type EncryptedData. + * + * @return the message. + */ +p7.createEncryptedData = function() { + var msg = null; + msg = { + type: forge.pki.oids.encryptedData, + version: 0, + encryptedContent: { + algorithm: forge.pki.oids['aes256-CBC'] + }, + + /** + * Reads an EncryptedData content block (in ASN.1 format) + * + * @param obj The ASN.1 representation of the EncryptedData content block + */ + fromAsn1: function(obj) { + // Validate EncryptedData content block and capture data. + _fromAsn1(msg, obj, p7.asn1.encryptedDataValidator); + }, + + /** + * Decrypt encrypted content + * + * @param key The (symmetric) key as a byte buffer + */ + decrypt: function(key) { + if(key !== undefined) { + msg.encryptedContent.key = key; + } + _decryptContent(msg); + } + }; + return msg; +}; + +/** + * Creates an empty PKCS#7 message of type EnvelopedData. + * + * @return the message. + */ +p7.createEnvelopedData = function() { + var msg = null; + msg = { + type: forge.pki.oids.envelopedData, + version: 0, + recipients: [], + encryptedContent: { + algorithm: forge.pki.oids['aes256-CBC'] + }, + + /** + * Reads an EnvelopedData content block (in ASN.1 format) + * + * @param obj the ASN.1 representation of the EnvelopedData content block. + */ + fromAsn1: function(obj) { + // validate EnvelopedData content block and capture data + var capture = _fromAsn1(msg, obj, p7.asn1.envelopedDataValidator); + msg.recipients = _recipientsFromAsn1(capture.recipientInfos.value); + }, + + toAsn1: function() { + // ContentInfo + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // ContentType + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(msg.type).getBytes()), + // [0] EnvelopedData + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Version + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(msg.version).getBytes()), + // RecipientInfos + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, + _recipientsToAsn1(msg.recipients)), + // EncryptedContentInfo + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, + _encryptedContentToAsn1(msg.encryptedContent)) + ]) + ]) + ]); + }, + + /** + * Find recipient by X.509 certificate's issuer. + * + * @param cert the certificate with the issuer to look for. + * + * @return the recipient object. + */ + findRecipient: function(cert) { + var sAttr = cert.issuer.attributes; + + for(var i = 0; i < msg.recipients.length; ++i) { + var r = msg.recipients[i]; + var rAttr = r.issuer; + + if(r.serialNumber !== cert.serialNumber) { + continue; + } + + if(rAttr.length !== sAttr.length) { + continue; + } + + var match = true; + for(var j = 0; j < sAttr.length; ++j) { + if(rAttr[j].type !== sAttr[j].type || + rAttr[j].value !== sAttr[j].value) { + match = false; + break; + } + } + + if(match) { + return r; + } + } + + return null; + }, + + /** + * Decrypt enveloped content + * + * @param recipient The recipient object related to the private key + * @param privKey The (RSA) private key object + */ + decrypt: function(recipient, privKey) { + if(msg.encryptedContent.key === undefined && recipient !== undefined && + privKey !== undefined) { + switch(recipient.encryptedContent.algorithm) { + case forge.pki.oids.rsaEncryption: + case forge.pki.oids.desCBC: + var key = privKey.decrypt(recipient.encryptedContent.content); + msg.encryptedContent.key = forge.util.createBuffer(key); + break; + + default: + throw new Error('Unsupported asymmetric cipher, ' + + 'OID ' + recipient.encryptedContent.algorithm); + } + } + + _decryptContent(msg); + }, + + /** + * Add (another) entity to list of recipients. + * + * @param cert The certificate of the entity to add. + */ + addRecipient: function(cert) { + msg.recipients.push({ + version: 0, + issuer: cert.issuer.attributes, + serialNumber: cert.serialNumber, + encryptedContent: { + // We simply assume rsaEncryption here, since forge.pki only + // supports RSA so far. If the PKI module supports other + // ciphers one day, we need to modify this one as well. + algorithm: forge.pki.oids.rsaEncryption, + key: cert.publicKey + } + }); + }, + + /** + * Encrypt enveloped content. + * + * This function supports two optional arguments, cipher and key, which + * can be used to influence symmetric encryption. Unless cipher is + * provided, the cipher specified in encryptedContent.algorithm is used + * (defaults to AES-256-CBC). If no key is provided, encryptedContent.key + * is (re-)used. If that one's not set, a random key will be generated + * automatically. + * + * @param [key] The key to be used for symmetric encryption. + * @param [cipher] The OID of the symmetric cipher to use. + */ + encrypt: function(key, cipher) { + // Part 1: Symmetric encryption + if(msg.encryptedContent.content === undefined) { + cipher = cipher || msg.encryptedContent.algorithm; + key = key || msg.encryptedContent.key; + + var keyLen, ivLen, ciphFn; + switch(cipher) { + case forge.pki.oids['aes128-CBC']: + keyLen = 16; + ivLen = 16; + ciphFn = forge.aes.createEncryptionCipher; + break; + + case forge.pki.oids['aes192-CBC']: + keyLen = 24; + ivLen = 16; + ciphFn = forge.aes.createEncryptionCipher; + break; + + case forge.pki.oids['aes256-CBC']: + keyLen = 32; + ivLen = 16; + ciphFn = forge.aes.createEncryptionCipher; + break; + + case forge.pki.oids['des-EDE3-CBC']: + keyLen = 24; + ivLen = 8; + ciphFn = forge.des.createEncryptionCipher; + break; + + default: + throw new Error('Unsupported symmetric cipher, OID ' + cipher); + } + + if(key === undefined) { + key = forge.util.createBuffer(forge.random.getBytes(keyLen)); + } else if(key.length() != keyLen) { + throw new Error('Symmetric key has wrong length; ' + + 'got ' + key.length() + ' bytes, expected ' + keyLen + '.'); + } + + // Keep a copy of the key & IV in the object, so the caller can + // use it for whatever reason. + msg.encryptedContent.algorithm = cipher; + msg.encryptedContent.key = key; + msg.encryptedContent.parameter = forge.util.createBuffer( + forge.random.getBytes(ivLen)); + + var ciph = ciphFn(key); + ciph.start(msg.encryptedContent.parameter.copy()); + ciph.update(msg.content); + + // The finish function does PKCS#7 padding by default, therefore + // no action required by us. + if(!ciph.finish()) { + throw new Error('Symmetric encryption failed.'); + } + + msg.encryptedContent.content = ciph.output; + } + + // Part 2: asymmetric encryption for each recipient + for(var i = 0; i < msg.recipients.length; ++i) { + var recipient = msg.recipients[i]; + + // Nothing to do, encryption already done. + if(recipient.encryptedContent.content !== undefined) { + continue; + } + + switch(recipient.encryptedContent.algorithm) { + case forge.pki.oids.rsaEncryption: + recipient.encryptedContent.content = + recipient.encryptedContent.key.encrypt( + msg.encryptedContent.key.data); + break; + + default: + throw new Error('Unsupported asymmetric cipher, OID ' + + recipient.encryptedContent.algorithm); + } + } + } + }; + return msg; +}; + +/** + * Converts a single recipient from an ASN.1 object. + * + * @param obj the ASN.1 RecipientInfo. + * + * @return the recipient object. + */ +function _recipientFromAsn1(obj) { + // validate EnvelopedData content block and capture data + var capture = {}; + var errors = []; + if(!asn1.validate(obj, p7.asn1.recipientInfoValidator, capture, errors)) { + var error = new Error('Cannot read PKCS#7 RecipientInfo. ' + + 'ASN.1 object is not an PKCS#7 RecipientInfo.'); + error.errors = errors; + throw error; + } + + return { + version: capture.version.charCodeAt(0), + issuer: forge.pki.RDNAttributesAsArray(capture.issuer), + serialNumber: forge.util.createBuffer(capture.serial).toHex(), + encryptedContent: { + algorithm: asn1.derToOid(capture.encAlgorithm), + parameter: capture.encParameter.value, + content: capture.encKey + } + }; +} + +/** + * Converts a single recipient object to an ASN.1 object. + * + * @param obj the recipient object. + * + * @return the ASN.1 RecipientInfo. + */ +function _recipientToAsn1(obj) { + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Version + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(obj.version).getBytes()), + // IssuerAndSerialNumber + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Name + forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}), + // Serial + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + forge.util.hexToBytes(obj.serialNumber)) + ]), + // KeyEncryptionAlgorithmIdentifier + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(obj.encryptedContent.algorithm).getBytes()), + // Parameter, force NULL, only RSA supported for now. + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ]), + // EncryptedKey + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + obj.encryptedContent.content) + ]); +} + +/** + * Map a set of RecipientInfo ASN.1 objects to recipient objects. + * + * @param infos an array of ASN.1 representations RecipientInfo (i.e. SET OF). + * + * @return an array of recipient objects. + */ +function _recipientsFromAsn1(infos) { + var ret = []; + for(var i = 0; i < infos.length; ++i) { + ret.push(_recipientFromAsn1(infos[i])); + } + return ret; +} + +/** + * Map an array of recipient objects to ASN.1 RecipientInfo objects. + * + * @param recipients an array of recipientInfo objects. + * + * @return an array of ASN.1 RecipientInfos. + */ +function _recipientsToAsn1(recipients) { + var ret = []; + for(var i = 0; i < recipients.length; ++i) { + ret.push(_recipientToAsn1(recipients[i])); + } + return ret; +} + +/** + * Converts a single signer from an ASN.1 object. + * + * @param obj the ASN.1 representation of a SignerInfo. + * + * @return the signer object. + */ +function _signerFromAsn1(obj) { + // validate EnvelopedData content block and capture data + var capture = {}; + var errors = []; + if(!asn1.validate(obj, p7.asn1.signerInfoValidator, capture, errors)) { + var error = new Error('Cannot read PKCS#7 SignerInfo. ' + + 'ASN.1 object is not an PKCS#7 SignerInfo.'); + error.errors = errors; + throw error; + } + + var rval = { + version: capture.version.charCodeAt(0), + issuer: forge.pki.RDNAttributesAsArray(capture.issuer), + serialNumber: forge.util.createBuffer(capture.serial).toHex(), + digestAlgorithm: asn1.derToOid(capture.digestAlgorithm), + signatureAlgorithm: asn1.derToOid(capture.signatureAlgorithm), + signature: capture.signature, + authenticatedAttributes: [], + unauthenticatedAttributes: [] + }; + + // TODO: convert attributes + var authenticatedAttributes = capture.authenticatedAttributes || []; + var unauthenticatedAttributes = capture.unauthenticatedAttributes || []; + + return rval; +} + +/** + * Converts a single signerInfo object to an ASN.1 object. + * + * @param obj the signerInfo object. + * + * @return the ASN.1 representation of a SignerInfo. + */ +function _signerToAsn1(obj) { + // SignerInfo + var rval = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // version + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(obj.version).getBytes()), + // issuerAndSerialNumber + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // name + forge.pki.distinguishedNameToAsn1({attributes: obj.issuer}), + // serial + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + forge.util.hexToBytes(obj.serialNumber)) + ]), + // digestAlgorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(obj.digestAlgorithm).getBytes()), + // parameters (null) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ]) + ]); + + // authenticatedAttributes (OPTIONAL) + if(obj.authenticatedAttributesAsn1) { + // add ASN.1 previously generated during signing + rval.value.push(obj.authenticatedAttributesAsn1); + } + + // digestEncryptionAlgorithm + rval.value.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(obj.signatureAlgorithm).getBytes()), + // parameters (null) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ])); + + // encryptedDigest + rval.value.push(asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, obj.signature)); + + // unauthenticatedAttributes (OPTIONAL) + if(obj.unauthenticatedAttributes.length > 0) { + // [1] IMPLICIT + var attrsAsn1 = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, []); + for(var i = 0; i < obj.unauthenticatedAttributes.length; ++i) { + var attr = obj.unauthenticatedAttributes[i]; + attrsAsn1.values.push(_attributeToAsn1(attr)); + } + rval.value.push(attrsAsn1); + } + + return rval; +} + +/** + * Map a set of SignerInfo ASN.1 objects to an array of signer objects. + * + * @param signerInfoAsn1s an array of ASN.1 SignerInfos (i.e. SET OF). + * + * @return an array of signers objects. + */ +function _signersFromAsn1(signerInfoAsn1s) { + var ret = []; + for(var i = 0; i < signerInfoAsn1s.length; ++i) { + ret.push(_signerFromAsn1(signerInfoAsn1s[i])); + } + return ret; +} + +/** + * Map an array of signer objects to ASN.1 objects. + * + * @param signers an array of signer objects. + * + * @return an array of ASN.1 SignerInfos. + */ +function _signersToAsn1(signers) { + var ret = []; + for(var i = 0; i < signers.length; ++i) { + ret.push(_signerToAsn1(signers[i])); + } + return ret; +} + +/** + * Convert an attribute object to an ASN.1 Attribute. + * + * @param attr the attribute object. + * + * @return the ASN.1 Attribute. + */ +function _attributeToAsn1(attr) { + var value; + + // TODO: generalize to support more attributes + if(attr.type === forge.pki.oids.contentType) { + value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(attr.value).getBytes()); + } else if(attr.type === forge.pki.oids.messageDigest) { + value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + attr.value.bytes()); + } else if(attr.type === forge.pki.oids.signingTime) { + /* Note per RFC 2985: Dates between 1 January 1950 and 31 December 2049 + (inclusive) MUST be encoded as UTCTime. Any dates with year values + before 1950 or after 2049 MUST be encoded as GeneralizedTime. [Further,] + UTCTime values MUST be expressed in Greenwich Mean Time (Zulu) and MUST + include seconds (i.e., times are YYMMDDHHMMSSZ), even where the + number of seconds is zero. Midnight (GMT) must be represented as + "YYMMDD000000Z". */ + // TODO: make these module-level constants + var jan_1_1950 = new Date('1950-01-01T00:00:00Z'); + var jan_1_2050 = new Date('2050-01-01T00:00:00Z'); + var date = attr.value; + if(typeof date === 'string') { + // try to parse date + var timestamp = Date.parse(date); + if(!isNaN(timestamp)) { + date = new Date(timestamp); + } else if(date.length === 13) { + // YYMMDDHHMMSSZ (13 chars for UTCTime) + date = asn1.utcTimeToDate(date); + } else { + // assume generalized time + date = asn1.generalizedTimeToDate(date); + } + } + + if(date >= jan_1_1950 && date < jan_1_2050) { + value = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false, + asn1.dateToUtcTime(date)); + } else { + value = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false, + asn1.dateToGeneralizedTime(date)); + } + } + + // TODO: expose as common API call + // create a RelativeDistinguishedName set + // each value in the set is an AttributeTypeAndValue first + // containing the type (an OID) and second the value + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // AttributeType + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(attr.type).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ + // AttributeValue + value + ]) + ]); +} + +/** + * Map messages encrypted content to ASN.1 objects. + * + * @param ec The encryptedContent object of the message. + * + * @return ASN.1 representation of the encryptedContent object (SEQUENCE). + */ +function _encryptedContentToAsn1(ec) { + return [ + // ContentType, always Data for the moment + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(forge.pki.oids.data).getBytes()), + // ContentEncryptionAlgorithmIdentifier + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // Algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(ec.algorithm).getBytes()), + // Parameters (IV) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + ec.parameter.getBytes()) + ]), + // [0] EncryptedContent + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + ec.content.getBytes()) + ]) + ]; +} + +/** + * Reads the "common part" of an PKCS#7 content block (in ASN.1 format) + * + * This function reads the "common part" of the PKCS#7 content blocks + * EncryptedData and EnvelopedData, i.e. version number and symmetrically + * encrypted content block. + * + * The result of the ASN.1 validate and capture process is returned + * to allow the caller to extract further data, e.g. the list of recipients + * in case of a EnvelopedData object. + * + * @param msg the PKCS#7 object to read the data to. + * @param obj the ASN.1 representation of the content block. + * @param validator the ASN.1 structure validator object to use. + * + * @return the value map captured by validator object. + */ +function _fromAsn1(msg, obj, validator) { + var capture = {}; + var errors = []; + if(!asn1.validate(obj, validator, capture, errors)) { + var error = new Error('Cannot read PKCS#7 message. ' + + 'ASN.1 object is not a supported PKCS#7 message.'); + error.errors = error; + throw error; + } + + // Check contentType, so far we only support (raw) Data. + var contentType = asn1.derToOid(capture.contentType); + if(contentType !== forge.pki.oids.data) { + throw new Error('Unsupported PKCS#7 message. ' + + 'Only wrapped ContentType Data supported.'); + } + + if(capture.encryptedContent) { + var content = ''; + if(forge.util.isArray(capture.encryptedContent)) { + for(var i = 0; i < capture.encryptedContent.length; ++i) { + if(capture.encryptedContent[i].type !== asn1.Type.OCTETSTRING) { + throw new Error('Malformed PKCS#7 message, expecting encrypted ' + + 'content constructed of only OCTET STRING objects.'); + } + content += capture.encryptedContent[i].value; + } + } else { + content = capture.encryptedContent; + } + msg.encryptedContent = { + algorithm: asn1.derToOid(capture.encAlgorithm), + parameter: forge.util.createBuffer(capture.encParameter.value), + content: forge.util.createBuffer(content) + }; + } + + if(capture.content) { + var content = ''; + if(forge.util.isArray(capture.content)) { + for(var i = 0; i < capture.content.length; ++i) { + if(capture.content[i].type !== asn1.Type.OCTETSTRING) { + throw new Error('Malformed PKCS#7 message, expecting ' + + 'content constructed of only OCTET STRING objects.'); + } + content += capture.content[i].value; + } + } else { + content = capture.content; + } + msg.content = forge.util.createBuffer(content); + } + + msg.version = capture.version.charCodeAt(0); + msg.rawCapture = capture; + + return capture; +} + +/** + * Decrypt the symmetrically encrypted content block of the PKCS#7 message. + * + * Decryption is skipped in case the PKCS#7 message object already has a + * (decrypted) content attribute. The algorithm, key and cipher parameters + * (probably the iv) are taken from the encryptedContent attribute of the + * message object. + * + * @param The PKCS#7 message object. + */ +function _decryptContent(msg) { + if(msg.encryptedContent.key === undefined) { + throw new Error('Symmetric key not available.'); + } + + if(msg.content === undefined) { + var ciph; + + switch(msg.encryptedContent.algorithm) { + case forge.pki.oids['aes128-CBC']: + case forge.pki.oids['aes192-CBC']: + case forge.pki.oids['aes256-CBC']: + ciph = forge.aes.createDecryptionCipher(msg.encryptedContent.key); + break; + + case forge.pki.oids['desCBC']: + case forge.pki.oids['des-EDE3-CBC']: + ciph = forge.des.createDecryptionCipher(msg.encryptedContent.key); + break; + + default: + throw new Error('Unsupported symmetric cipher, OID ' + + msg.encryptedContent.algorithm); + } + ciph.start(msg.encryptedContent.parameter); + ciph.update(msg.encryptedContent.content); + + if(!ciph.finish()) { + throw new Error('Symmetric decryption failed.'); + } + + msg.content = ciph.output; + } +} diff --git a/node_modules/node-forge/lib/pkcs7asn1.js b/node_modules/node-forge/lib/pkcs7asn1.js new file mode 100644 index 0000000..a2ac01f --- /dev/null +++ b/node_modules/node-forge/lib/pkcs7asn1.js @@ -0,0 +1,409 @@ +/** + * Javascript implementation of ASN.1 validators for PKCS#7 v1.5. + * + * @author Dave Longley + * @author Stefan Siegl + * + * Copyright (c) 2012-2015 Digital Bazaar, Inc. + * Copyright (c) 2012 Stefan Siegl + * + * The ASN.1 representation of PKCS#7 is as follows + * (see RFC #2315 for details, http://www.ietf.org/rfc/rfc2315.txt): + * + * A PKCS#7 message consists of a ContentInfo on root level, which may + * contain any number of further ContentInfo nested into it. + * + * ContentInfo ::= SEQUENCE { + * contentType ContentType, + * content [0] EXPLICIT ANY DEFINED BY contentType OPTIONAL + * } + * + * ContentType ::= OBJECT IDENTIFIER + * + * EnvelopedData ::= SEQUENCE { + * version Version, + * recipientInfos RecipientInfos, + * encryptedContentInfo EncryptedContentInfo + * } + * + * EncryptedData ::= SEQUENCE { + * version Version, + * encryptedContentInfo EncryptedContentInfo + * } + * + * id-signedData OBJECT IDENTIFIER ::= { iso(1) member-body(2) + * us(840) rsadsi(113549) pkcs(1) pkcs7(7) 2 } + * + * SignedData ::= SEQUENCE { + * version INTEGER, + * digestAlgorithms DigestAlgorithmIdentifiers, + * contentInfo ContentInfo, + * certificates [0] IMPLICIT Certificates OPTIONAL, + * crls [1] IMPLICIT CertificateRevocationLists OPTIONAL, + * signerInfos SignerInfos + * } + * + * SignerInfos ::= SET OF SignerInfo + * + * SignerInfo ::= SEQUENCE { + * version Version, + * issuerAndSerialNumber IssuerAndSerialNumber, + * digestAlgorithm DigestAlgorithmIdentifier, + * authenticatedAttributes [0] IMPLICIT Attributes OPTIONAL, + * digestEncryptionAlgorithm DigestEncryptionAlgorithmIdentifier, + * encryptedDigest EncryptedDigest, + * unauthenticatedAttributes [1] IMPLICIT Attributes OPTIONAL + * } + * + * EncryptedDigest ::= OCTET STRING + * + * Attributes ::= SET OF Attribute + * + * Attribute ::= SEQUENCE { + * attrType OBJECT IDENTIFIER, + * attrValues SET OF AttributeValue + * } + * + * AttributeValue ::= ANY + * + * Version ::= INTEGER + * + * RecipientInfos ::= SET OF RecipientInfo + * + * EncryptedContentInfo ::= SEQUENCE { + * contentType ContentType, + * contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier, + * encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL + * } + * + * ContentEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier + * + * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters + * for the algorithm, if any. In the case of AES and DES3, there is only one, + * the IV. + * + * AlgorithmIdentifer ::= SEQUENCE { + * algorithm OBJECT IDENTIFIER, + * parameters ANY DEFINED BY algorithm OPTIONAL + * } + * + * EncryptedContent ::= OCTET STRING + * + * RecipientInfo ::= SEQUENCE { + * version Version, + * issuerAndSerialNumber IssuerAndSerialNumber, + * keyEncryptionAlgorithm KeyEncryptionAlgorithmIdentifier, + * encryptedKey EncryptedKey + * } + * + * IssuerAndSerialNumber ::= SEQUENCE { + * issuer Name, + * serialNumber CertificateSerialNumber + * } + * + * CertificateSerialNumber ::= INTEGER + * + * KeyEncryptionAlgorithmIdentifier ::= AlgorithmIdentifier + * + * EncryptedKey ::= OCTET STRING + */ +var forge = require('./forge'); +require('./asn1'); +require('./util'); + +// shortcut for ASN.1 API +var asn1 = forge.asn1; + +// shortcut for PKCS#7 API +var p7v = module.exports = forge.pkcs7asn1 = forge.pkcs7asn1 || {}; +forge.pkcs7 = forge.pkcs7 || {}; +forge.pkcs7.asn1 = p7v; + +var contentInfoValidator = { + name: 'ContentInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'ContentInfo.ContentType', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'contentType' + }, { + name: 'ContentInfo.content', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + optional: true, + captureAsn1: 'content' + }] +}; +p7v.contentInfoValidator = contentInfoValidator; + +var encryptedContentInfoValidator = { + name: 'EncryptedContentInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'EncryptedContentInfo.contentType', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'contentType' + }, { + name: 'EncryptedContentInfo.contentEncryptionAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'EncryptedContentInfo.contentEncryptionAlgorithm.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'encAlgorithm' + }, { + name: 'EncryptedContentInfo.contentEncryptionAlgorithm.parameter', + tagClass: asn1.Class.UNIVERSAL, + captureAsn1: 'encParameter' + }] + }, { + name: 'EncryptedContentInfo.encryptedContent', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + /* The PKCS#7 structure output by OpenSSL somewhat differs from what + * other implementations do generate. + * + * OpenSSL generates a structure like this: + * SEQUENCE { + * ... + * [0] + * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38 + * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45 + * ... + * } + * + * Whereas other implementations (and this PKCS#7 module) generate: + * SEQUENCE { + * ... + * [0] { + * OCTET STRING + * 26 DA 67 D2 17 9C 45 3C B1 2A A8 59 2F 29 33 38 + * C3 C3 DF 86 71 74 7A 19 9F 40 D0 29 BE 85 90 45 + * ... + * } + * } + * + * In order to support both, we just capture the context specific + * field here. The OCTET STRING bit is removed below. + */ + capture: 'encryptedContent', + captureAsn1: 'encryptedContentAsn1' + }] +}; + +p7v.envelopedDataValidator = { + name: 'EnvelopedData', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'EnvelopedData.Version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'version' + }, { + name: 'EnvelopedData.RecipientInfos', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + constructed: true, + captureAsn1: 'recipientInfos' + }].concat(encryptedContentInfoValidator) +}; + +p7v.encryptedDataValidator = { + name: 'EncryptedData', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'EncryptedData.Version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'version' + }].concat(encryptedContentInfoValidator) +}; + +var signerValidator = { + name: 'SignerInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'SignerInfo.version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false + }, { + name: 'SignerInfo.issuerAndSerialNumber', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'SignerInfo.issuerAndSerialNumber.issuer', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'issuer' + }, { + name: 'SignerInfo.issuerAndSerialNumber.serialNumber', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'serial' + }] + }, { + name: 'SignerInfo.digestAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'SignerInfo.digestAlgorithm.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'digestAlgorithm' + }, { + name: 'SignerInfo.digestAlgorithm.parameter', + tagClass: asn1.Class.UNIVERSAL, + constructed: false, + captureAsn1: 'digestParameter', + optional: true + }] + }, { + name: 'SignerInfo.authenticatedAttributes', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + optional: true, + capture: 'authenticatedAttributes' + }, { + name: 'SignerInfo.digestEncryptionAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + capture: 'signatureAlgorithm' + }, { + name: 'SignerInfo.encryptedDigest', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'signature' + }, { + name: 'SignerInfo.unauthenticatedAttributes', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 1, + constructed: true, + optional: true, + capture: 'unauthenticatedAttributes' + }] +}; + +p7v.signedDataValidator = { + name: 'SignedData', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'SignedData.Version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'version' + }, { + name: 'SignedData.DigestAlgorithms', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + constructed: true, + captureAsn1: 'digestAlgorithms' + }, + contentInfoValidator, + { + name: 'SignedData.Certificates', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + optional: true, + captureAsn1: 'certificates' + }, { + name: 'SignedData.CertificateRevocationLists', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 1, + optional: true, + captureAsn1: 'crls' + }, { + name: 'SignedData.SignerInfos', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + capture: 'signerInfos', + optional: true, + value: [signerValidator] + }] +}; + +p7v.recipientInfoValidator = { + name: 'RecipientInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'RecipientInfo.version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'version' + }, { + name: 'RecipientInfo.issuerAndSerial', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'RecipientInfo.issuerAndSerial.issuer', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'issuer' + }, { + name: 'RecipientInfo.issuerAndSerial.serialNumber', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'serial' + }] + }, { + name: 'RecipientInfo.keyEncryptionAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'RecipientInfo.keyEncryptionAlgorithm.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'encAlgorithm' + }, { + name: 'RecipientInfo.keyEncryptionAlgorithm.parameter', + tagClass: asn1.Class.UNIVERSAL, + constructed: false, + captureAsn1: 'encParameter' + }] + }, { + name: 'RecipientInfo.encryptedKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'encKey' + }] +}; diff --git a/node_modules/node-forge/lib/pki.js b/node_modules/node-forge/lib/pki.js new file mode 100644 index 0000000..ee82ff1 --- /dev/null +++ b/node_modules/node-forge/lib/pki.js @@ -0,0 +1,102 @@ +/** + * Javascript implementation of a basic Public Key Infrastructure, including + * support for RSA public and private keys. + * + * @author Dave Longley + * + * Copyright (c) 2010-2013 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./asn1'); +require('./oids'); +require('./pbe'); +require('./pem'); +require('./pbkdf2'); +require('./pkcs12'); +require('./pss'); +require('./rsa'); +require('./util'); +require('./x509'); + +// shortcut for asn.1 API +var asn1 = forge.asn1; + +/* Public Key Infrastructure (PKI) implementation. */ +var pki = module.exports = forge.pki = forge.pki || {}; + +/** + * NOTE: THIS METHOD IS DEPRECATED. Use pem.decode() instead. + * + * Converts PEM-formatted data to DER. + * + * @param pem the PEM-formatted data. + * + * @return the DER-formatted data. + */ +pki.pemToDer = function(pem) { + var msg = forge.pem.decode(pem)[0]; + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert PEM to DER; PEM is encrypted.'); + } + return forge.util.createBuffer(msg.body); +}; + +/** + * Converts an RSA private key from PEM format. + * + * @param pem the PEM-formatted private key. + * + * @return the private key. + */ +pki.privateKeyFromPem = function(pem) { + var msg = forge.pem.decode(pem)[0]; + + if(msg.type !== 'PRIVATE KEY' && msg.type !== 'RSA PRIVATE KEY') { + var error = new Error('Could not convert private key from PEM; PEM ' + + 'header type is not "PRIVATE KEY" or "RSA PRIVATE KEY".'); + error.headerType = msg.type; + throw error; + } + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert private key from PEM; PEM is encrypted.'); + } + + // convert DER to ASN.1 object + var obj = asn1.fromDer(msg.body); + + return pki.privateKeyFromAsn1(obj); +}; + +/** + * Converts an RSA private key to PEM format. + * + * @param key the private key. + * @param maxline the maximum characters per line, defaults to 64. + * + * @return the PEM-formatted private key. + */ +pki.privateKeyToPem = function(key, maxline) { + // convert to ASN.1, then DER, then PEM-encode + var msg = { + type: 'RSA PRIVATE KEY', + body: asn1.toDer(pki.privateKeyToAsn1(key)).getBytes() + }; + return forge.pem.encode(msg, {maxline: maxline}); +}; + +/** + * Converts a PrivateKeyInfo to PEM format. + * + * @param pki the PrivateKeyInfo. + * @param maxline the maximum characters per line, defaults to 64. + * + * @return the PEM-formatted private key. + */ +pki.privateKeyInfoToPem = function(pki, maxline) { + // convert to DER, then PEM-encode + var msg = { + type: 'PRIVATE KEY', + body: asn1.toDer(pki).getBytes() + }; + return forge.pem.encode(msg, {maxline: maxline}); +}; diff --git a/node_modules/node-forge/lib/prime.js b/node_modules/node-forge/lib/prime.js new file mode 100644 index 0000000..3d51473 --- /dev/null +++ b/node_modules/node-forge/lib/prime.js @@ -0,0 +1,297 @@ +/** + * Prime number generation API. + * + * @author Dave Longley + * + * Copyright (c) 2014 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./util'); +require('./jsbn'); +require('./random'); + +(function() { + +// forge.prime already defined +if(forge.prime) { + module.exports = forge.prime; + return; +} + +/* PRIME API */ +var prime = module.exports = forge.prime = forge.prime || {}; + +var BigInteger = forge.jsbn.BigInteger; + +// primes are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29 +var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2]; +var THIRTY = new BigInteger(null); +THIRTY.fromInt(30); +var op_or = function(x, y) {return x|y;}; + +/** + * Generates a random probable prime with the given number of bits. + * + * Alternative algorithms can be specified by name as a string or as an + * object with custom options like so: + * + * { + * name: 'PRIMEINC', + * options: { + * maxBlockTime: , + * millerRabinTests: , + * workerScript: , + * workers: . + * workLoad: the size of the work load, ie: number of possible prime + * numbers for each web worker to check per work assignment, + * (default: 100). + * } + * } + * + * @param bits the number of bits for the prime number. + * @param options the options to use. + * [algorithm] the algorithm to use (default: 'PRIMEINC'). + * [prng] a custom crypto-secure pseudo-random number generator to use, + * that must define "getBytesSync". + * + * @return callback(err, num) called once the operation completes. + */ +prime.generateProbablePrime = function(bits, options, callback) { + if(typeof options === 'function') { + callback = options; + options = {}; + } + options = options || {}; + + // default to PRIMEINC algorithm + var algorithm = options.algorithm || 'PRIMEINC'; + if(typeof algorithm === 'string') { + algorithm = {name: algorithm}; + } + algorithm.options = algorithm.options || {}; + + // create prng with api that matches BigInteger secure random + var prng = options.prng || forge.random; + var rng = { + // x is an array to fill with bytes + nextBytes: function(x) { + var b = prng.getBytesSync(x.length); + for(var i = 0; i < x.length; ++i) { + x[i] = b.charCodeAt(i); + } + } + }; + + if(algorithm.name === 'PRIMEINC') { + return primeincFindPrime(bits, rng, algorithm.options, callback); + } + + throw new Error('Invalid prime generation algorithm: ' + algorithm.name); +}; + +function primeincFindPrime(bits, rng, options, callback) { + if('workers' in options) { + return primeincFindPrimeWithWorkers(bits, rng, options, callback); + } + return primeincFindPrimeWithoutWorkers(bits, rng, options, callback); +} + +function primeincFindPrimeWithoutWorkers(bits, rng, options, callback) { + // initialize random number + var num = generateRandom(bits, rng); + + /* Note: All primes are of the form 30k+i for i < 30 and gcd(30, i)=1. The + number we are given is always aligned at 30k + 1. Each time the number is + determined not to be prime we add to get to the next 'i', eg: if the number + was at 30k + 1 we add 6. */ + var deltaIdx = 0; + + // get required number of MR tests + var mrTests = getMillerRabinTests(num.bitLength()); + if('millerRabinTests' in options) { + mrTests = options.millerRabinTests; + } + + // find prime nearest to 'num' for maxBlockTime ms + // 10 ms gives 5ms of leeway for other calculations before dropping + // below 60fps (1000/60 == 16.67), but in reality, the number will + // likely be higher due to an 'atomic' big int modPow + var maxBlockTime = 10; + if('maxBlockTime' in options) { + maxBlockTime = options.maxBlockTime; + } + + _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback); +} + +function _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback) { + var start = +new Date(); + do { + // overflow, regenerate random number + if(num.bitLength() > bits) { + num = generateRandom(bits, rng); + } + // do primality test + if(num.isProbablePrime(mrTests)) { + return callback(null, num); + } + // get next potential prime + num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0); + } while(maxBlockTime < 0 || (+new Date() - start < maxBlockTime)); + + // keep trying later + forge.util.setImmediate(function() { + _primeinc(num, bits, rng, deltaIdx, mrTests, maxBlockTime, callback); + }); +} + +// NOTE: This algorithm is indeterminate in nature because workers +// run in parallel looking at different segments of numbers. Even if this +// algorithm is run twice with the same input from a predictable RNG, it +// may produce different outputs. +function primeincFindPrimeWithWorkers(bits, rng, options, callback) { + // web workers unavailable + if(typeof Worker === 'undefined') { + return primeincFindPrimeWithoutWorkers(bits, rng, options, callback); + } + + // initialize random number + var num = generateRandom(bits, rng); + + // use web workers to generate keys + var numWorkers = options.workers; + var workLoad = options.workLoad || 100; + var range = workLoad * 30 / 8; + var workerScript = options.workerScript || 'forge/prime.worker.js'; + if(numWorkers === -1) { + return forge.util.estimateCores(function(err, cores) { + if(err) { + // default to 2 + cores = 2; + } + numWorkers = cores - 1; + generate(); + }); + } + generate(); + + function generate() { + // require at least 1 worker + numWorkers = Math.max(1, numWorkers); + + // TODO: consider optimizing by starting workers outside getPrime() ... + // note that in order to clean up they will have to be made internally + // asynchronous which may actually be slower + + // start workers immediately + var workers = []; + for(var i = 0; i < numWorkers; ++i) { + // FIXME: fix path or use blob URLs + workers[i] = new Worker(workerScript); + } + var running = numWorkers; + + // listen for requests from workers and assign ranges to find prime + for(var i = 0; i < numWorkers; ++i) { + workers[i].addEventListener('message', workerMessage); + } + + /* Note: The distribution of random numbers is unknown. Therefore, each + web worker is continuously allocated a range of numbers to check for a + random number until one is found. + + Every 30 numbers will be checked just 8 times, because prime numbers + have the form: + + 30k+i, for i < 30 and gcd(30, i)=1 (there are 8 values of i for this) + + Therefore, if we want a web worker to run N checks before asking for + a new range of numbers, each range must contain N*30/8 numbers. + + For 100 checks (workLoad), this is a range of 375. */ + + var found = false; + function workerMessage(e) { + // ignore message, prime already found + if(found) { + return; + } + + --running; + var data = e.data; + if(data.found) { + // terminate all workers + for(var i = 0; i < workers.length; ++i) { + workers[i].terminate(); + } + found = true; + return callback(null, new BigInteger(data.prime, 16)); + } + + // overflow, regenerate random number + if(num.bitLength() > bits) { + num = generateRandom(bits, rng); + } + + // assign new range to check + var hex = num.toString(16); + + // start prime search + e.target.postMessage({ + hex: hex, + workLoad: workLoad + }); + + num.dAddOffset(range, 0); + } + } +} + +/** + * Generates a random number using the given number of bits and RNG. + * + * @param bits the number of bits for the number. + * @param rng the random number generator to use. + * + * @return the random number. + */ +function generateRandom(bits, rng) { + var num = new BigInteger(bits, rng); + // force MSB set + var bits1 = bits - 1; + if(!num.testBit(bits1)) { + num.bitwiseTo(BigInteger.ONE.shiftLeft(bits1), op_or, num); + } + // align number on 30k+1 boundary + num.dAddOffset(31 - num.mod(THIRTY).byteValue(), 0); + return num; +} + +/** + * Returns the required number of Miller-Rabin tests to generate a + * prime with an error probability of (1/2)^80. + * + * See Handbook of Applied Cryptography Chapter 4, Table 4.4. + * + * @param bits the bit size. + * + * @return the required number of iterations. + */ +function getMillerRabinTests(bits) { + if(bits <= 100) return 27; + if(bits <= 150) return 18; + if(bits <= 200) return 15; + if(bits <= 250) return 12; + if(bits <= 300) return 9; + if(bits <= 350) return 8; + if(bits <= 400) return 7; + if(bits <= 500) return 6; + if(bits <= 600) return 5; + if(bits <= 800) return 4; + if(bits <= 1250) return 3; + return 2; +} + +})(); diff --git a/node_modules/node-forge/lib/prime.worker.js b/node_modules/node-forge/lib/prime.worker.js new file mode 100644 index 0000000..ce1355d --- /dev/null +++ b/node_modules/node-forge/lib/prime.worker.js @@ -0,0 +1,168 @@ +/** + * RSA Key Generation Worker. + * + * @author Dave Longley + * + * Copyright (c) 2013 Digital Bazaar, Inc. + */ +// worker is built using CommonJS syntax to include all code in one worker file +//importScripts('jsbn.js'); +var forge = require('./forge'); +require('./jsbn'); + +// prime constants +var LOW_PRIMES = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997]; +var LP_LIMIT = (1 << 26) / LOW_PRIMES[LOW_PRIMES.length - 1]; + +var BigInteger = forge.jsbn.BigInteger; +var BIG_TWO = new BigInteger(null); +BIG_TWO.fromInt(2); + +self.addEventListener('message', function(e) { + var result = findPrime(e.data); + self.postMessage(result); +}); + +// start receiving ranges to check +self.postMessage({found: false}); + +// primes are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29 +var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2]; + +function findPrime(data) { + // TODO: abstract based on data.algorithm (PRIMEINC vs. others) + + // create BigInteger from given random bytes + var num = new BigInteger(data.hex, 16); + + /* Note: All primes are of the form 30k+i for i < 30 and gcd(30, i)=1. The + number we are given is always aligned at 30k + 1. Each time the number is + determined not to be prime we add to get to the next 'i', eg: if the number + was at 30k + 1 we add 6. */ + var deltaIdx = 0; + + // find nearest prime + var workLoad = data.workLoad; + for(var i = 0; i < workLoad; ++i) { + // do primality test + if(isProbablePrime(num)) { + return {found: true, prime: num.toString(16)}; + } + // get next potential prime + num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0); + } + + return {found: false}; +} + +function isProbablePrime(n) { + // divide by low primes, ignore even checks, etc (n alread aligned properly) + var i = 1; + while(i < LOW_PRIMES.length) { + var m = LOW_PRIMES[i]; + var j = i + 1; + while(j < LOW_PRIMES.length && m < LP_LIMIT) { + m *= LOW_PRIMES[j++]; + } + m = n.modInt(m); + while(i < j) { + if(m % LOW_PRIMES[i++] === 0) { + return false; + } + } + } + return runMillerRabin(n); +} + +// HAC 4.24, Miller-Rabin +function runMillerRabin(n) { + // n1 = n - 1 + var n1 = n.subtract(BigInteger.ONE); + + // get s and d such that n1 = 2^s * d + var s = n1.getLowestSetBit(); + if(s <= 0) { + return false; + } + var d = n1.shiftRight(s); + + var k = _getMillerRabinTests(n.bitLength()); + var prng = getPrng(); + var a; + for(var i = 0; i < k; ++i) { + // select witness 'a' at random from between 1 and n - 1 + do { + a = new BigInteger(n.bitLength(), prng); + } while(a.compareTo(BigInteger.ONE) <= 0 || a.compareTo(n1) >= 0); + + /* See if 'a' is a composite witness. */ + + // x = a^d mod n + var x = a.modPow(d, n); + + // probably prime + if(x.compareTo(BigInteger.ONE) === 0 || x.compareTo(n1) === 0) { + continue; + } + + var j = s; + while(--j) { + // x = x^2 mod a + x = x.modPowInt(2, n); + + // 'n' is composite because no previous x == -1 mod n + if(x.compareTo(BigInteger.ONE) === 0) { + return false; + } + // x == -1 mod n, so probably prime + if(x.compareTo(n1) === 0) { + break; + } + } + + // 'x' is first_x^(n1/2) and is not +/- 1, so 'n' is not prime + if(j === 0) { + return false; + } + } + + return true; +} + +// get pseudo random number generator +function getPrng() { + // create prng with api that matches BigInteger secure random + return { + // x is an array to fill with bytes + nextBytes: function(x) { + for(var i = 0; i < x.length; ++i) { + x[i] = Math.floor(Math.random() * 0xFF); + } + } + }; +} + +/** + * Returns the required number of Miller-Rabin tests to generate a + * prime with an error probability of (1/2)^80. + * + * See Handbook of Applied Cryptography Chapter 4, Table 4.4. + * + * @param bits the bit size. + * + * @return the required number of iterations. + */ +function _getMillerRabinTests(bits) { + if(bits <= 100) return 27; + if(bits <= 150) return 18; + if(bits <= 200) return 15; + if(bits <= 250) return 12; + if(bits <= 300) return 9; + if(bits <= 350) return 8; + if(bits <= 400) return 7; + if(bits <= 500) return 6; + if(bits <= 600) return 5; + if(bits <= 800) return 4; + if(bits <= 1250) return 3; + return 2; +} diff --git a/node_modules/node-forge/lib/prng.js b/node_modules/node-forge/lib/prng.js new file mode 100644 index 0000000..c2f5f05 --- /dev/null +++ b/node_modules/node-forge/lib/prng.js @@ -0,0 +1,419 @@ +/** + * A javascript implementation of a cryptographically-secure + * Pseudo Random Number Generator (PRNG). The Fortuna algorithm is followed + * here though the use of SHA-256 is not enforced; when generating an + * a PRNG context, the hashing algorithm and block cipher used for + * the generator are specified via a plugin. + * + * @author Dave Longley + * + * Copyright (c) 2010-2014 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./util'); + +var _crypto = null; +if(forge.util.isNodejs && !forge.options.usePureJavaScript && + !process.versions['node-webkit']) { + _crypto = require('crypto'); +} + +/* PRNG API */ +var prng = module.exports = forge.prng = forge.prng || {}; + +/** + * Creates a new PRNG context. + * + * A PRNG plugin must be passed in that will provide: + * + * 1. A function that initializes the key and seed of a PRNG context. It + * will be given a 16 byte key and a 16 byte seed. Any key expansion + * or transformation of the seed from a byte string into an array of + * integers (or similar) should be performed. + * 2. The cryptographic function used by the generator. It takes a key and + * a seed. + * 3. A seed increment function. It takes the seed and returns seed + 1. + * 4. An api to create a message digest. + * + * For an example, see random.js. + * + * @param plugin the PRNG plugin to use. + */ +prng.create = function(plugin) { + var ctx = { + plugin: plugin, + key: null, + seed: null, + time: null, + // number of reseeds so far + reseeds: 0, + // amount of data generated so far + generated: 0, + // no initial key bytes + keyBytes: '' + }; + + // create 32 entropy pools (each is a message digest) + var md = plugin.md; + var pools = new Array(32); + for(var i = 0; i < 32; ++i) { + pools[i] = md.create(); + } + ctx.pools = pools; + + // entropy pools are written to cyclically, starting at index 0 + ctx.pool = 0; + + /** + * Generates random bytes. The bytes may be generated synchronously or + * asynchronously. Web workers must use the asynchronous interface or + * else the behavior is undefined. + * + * @param count the number of random bytes to generate. + * @param [callback(err, bytes)] called once the operation completes. + * + * @return count random bytes as a string. + */ + ctx.generate = function(count, callback) { + // do synchronously + if(!callback) { + return ctx.generateSync(count); + } + + // simple generator using counter-based CBC + var cipher = ctx.plugin.cipher; + var increment = ctx.plugin.increment; + var formatKey = ctx.plugin.formatKey; + var formatSeed = ctx.plugin.formatSeed; + var b = forge.util.createBuffer(); + + // paranoid deviation from Fortuna: + // reset key for every request to protect previously + // generated random bytes should the key be discovered; + // there is no 100ms based reseeding because of this + // forced reseed for every `generate` call + ctx.key = null; + + generate(); + + function generate(err) { + if(err) { + return callback(err); + } + + // sufficient bytes generated + if(b.length() >= count) { + return callback(null, b.getBytes(count)); + } + + // if amount of data generated is greater than 1 MiB, trigger reseed + if(ctx.generated > 0xfffff) { + ctx.key = null; + } + + if(ctx.key === null) { + // prevent stack overflow + return forge.util.nextTick(function() { + _reseed(generate); + }); + } + + // generate the random bytes + var bytes = cipher(ctx.key, ctx.seed); + ctx.generated += bytes.length; + b.putBytes(bytes); + + // generate bytes for a new key and seed + ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed))); + ctx.seed = formatSeed(cipher(ctx.key, ctx.seed)); + + forge.util.setImmediate(generate); + } + }; + + /** + * Generates random bytes synchronously. + * + * @param count the number of random bytes to generate. + * + * @return count random bytes as a string. + */ + ctx.generateSync = function(count) { + // simple generator using counter-based CBC + var cipher = ctx.plugin.cipher; + var increment = ctx.plugin.increment; + var formatKey = ctx.plugin.formatKey; + var formatSeed = ctx.plugin.formatSeed; + + // paranoid deviation from Fortuna: + // reset key for every request to protect previously + // generated random bytes should the key be discovered; + // there is no 100ms based reseeding because of this + // forced reseed for every `generateSync` call + ctx.key = null; + + var b = forge.util.createBuffer(); + while(b.length() < count) { + // if amount of data generated is greater than 1 MiB, trigger reseed + if(ctx.generated > 0xfffff) { + ctx.key = null; + } + + if(ctx.key === null) { + _reseedSync(); + } + + // generate the random bytes + var bytes = cipher(ctx.key, ctx.seed); + ctx.generated += bytes.length; + b.putBytes(bytes); + + // generate bytes for a new key and seed + ctx.key = formatKey(cipher(ctx.key, increment(ctx.seed))); + ctx.seed = formatSeed(cipher(ctx.key, ctx.seed)); + } + + return b.getBytes(count); + }; + + /** + * Private function that asynchronously reseeds a generator. + * + * @param callback(err) called once the operation completes. + */ + function _reseed(callback) { + if(ctx.pools[0].messageLength >= 32) { + _seed(); + return callback(); + } + // not enough seed data... + var needed = (32 - ctx.pools[0].messageLength) << 5; + ctx.seedFile(needed, function(err, bytes) { + if(err) { + return callback(err); + } + ctx.collect(bytes); + _seed(); + callback(); + }); + } + + /** + * Private function that synchronously reseeds a generator. + */ + function _reseedSync() { + if(ctx.pools[0].messageLength >= 32) { + return _seed(); + } + // not enough seed data... + var needed = (32 - ctx.pools[0].messageLength) << 5; + ctx.collect(ctx.seedFileSync(needed)); + _seed(); + } + + /** + * Private function that seeds a generator once enough bytes are available. + */ + function _seed() { + // update reseed count + ctx.reseeds = (ctx.reseeds === 0xffffffff) ? 0 : ctx.reseeds + 1; + + // goal is to update `key` via: + // key = hash(key + s) + // where 's' is all collected entropy from selected pools, then... + + // create a plugin-based message digest + var md = ctx.plugin.md.create(); + + // consume current key bytes + md.update(ctx.keyBytes); + + // digest the entropy of pools whose index k meet the + // condition 'n mod 2^k == 0' where n is the number of reseeds + var _2powK = 1; + for(var k = 0; k < 32; ++k) { + if(ctx.reseeds % _2powK === 0) { + md.update(ctx.pools[k].digest().getBytes()); + ctx.pools[k].start(); + } + _2powK = _2powK << 1; + } + + // get digest for key bytes + ctx.keyBytes = md.digest().getBytes(); + + // paranoid deviation from Fortuna: + // update `seed` via `seed = hash(key)` + // instead of initializing to zero once and only + // ever incrementing it + md.start(); + md.update(ctx.keyBytes); + var seedBytes = md.digest().getBytes(); + + // update state + ctx.key = ctx.plugin.formatKey(ctx.keyBytes); + ctx.seed = ctx.plugin.formatSeed(seedBytes); + ctx.generated = 0; + } + + /** + * The built-in default seedFile. This seedFile is used when entropy + * is needed immediately. + * + * @param needed the number of bytes that are needed. + * + * @return the random bytes. + */ + function defaultSeedFile(needed) { + // use window.crypto.getRandomValues strong source of entropy if available + var getRandomValues = null; + var globalScope = forge.util.globalScope; + var _crypto = globalScope.crypto || globalScope.msCrypto; + if(_crypto && _crypto.getRandomValues) { + getRandomValues = function(arr) { + return _crypto.getRandomValues(arr); + }; + } + + var b = forge.util.createBuffer(); + if(getRandomValues) { + while(b.length() < needed) { + // max byte length is 65536 before QuotaExceededError is thrown + // http://www.w3.org/TR/WebCryptoAPI/#RandomSource-method-getRandomValues + var count = Math.max(1, Math.min(needed - b.length(), 65536) / 4); + var entropy = new Uint32Array(Math.floor(count)); + try { + getRandomValues(entropy); + for(var i = 0; i < entropy.length; ++i) { + b.putInt32(entropy[i]); + } + } catch(e) { + /* only ignore QuotaExceededError */ + if(!(typeof QuotaExceededError !== 'undefined' && + e instanceof QuotaExceededError)) { + throw e; + } + } + } + } + + // be sad and add some weak random data + if(b.length() < needed) { + /* Draws from Park-Miller "minimal standard" 31 bit PRNG, + implemented with David G. Carta's optimization: with 32 bit math + and without division (Public Domain). */ + var hi, lo, next; + var seed = Math.floor(Math.random() * 0x010000); + while(b.length() < needed) { + lo = 16807 * (seed & 0xFFFF); + hi = 16807 * (seed >> 16); + lo += (hi & 0x7FFF) << 16; + lo += hi >> 15; + lo = (lo & 0x7FFFFFFF) + (lo >> 31); + seed = lo & 0xFFFFFFFF; + + // consume lower 3 bytes of seed + for(var i = 0; i < 3; ++i) { + // throw in more pseudo random + next = seed >>> (i << 3); + next ^= Math.floor(Math.random() * 0x0100); + b.putByte(String.fromCharCode(next & 0xFF)); + } + } + } + + return b.getBytes(needed); + } + // initialize seed file APIs + if(_crypto) { + // use nodejs async API + ctx.seedFile = function(needed, callback) { + _crypto.randomBytes(needed, function(err, bytes) { + if(err) { + return callback(err); + } + callback(null, bytes.toString()); + }); + }; + // use nodejs sync API + ctx.seedFileSync = function(needed) { + return _crypto.randomBytes(needed).toString(); + }; + } else { + ctx.seedFile = function(needed, callback) { + try { + callback(null, defaultSeedFile(needed)); + } catch(e) { + callback(e); + } + }; + ctx.seedFileSync = defaultSeedFile; + } + + /** + * Adds entropy to a prng ctx's accumulator. + * + * @param bytes the bytes of entropy as a string. + */ + ctx.collect = function(bytes) { + // iterate over pools distributing entropy cyclically + var count = bytes.length; + for(var i = 0; i < count; ++i) { + ctx.pools[ctx.pool].update(bytes.substr(i, 1)); + ctx.pool = (ctx.pool === 31) ? 0 : ctx.pool + 1; + } + }; + + /** + * Collects an integer of n bits. + * + * @param i the integer entropy. + * @param n the number of bits in the integer. + */ + ctx.collectInt = function(i, n) { + var bytes = ''; + for(var x = 0; x < n; x += 8) { + bytes += String.fromCharCode((i >> x) & 0xFF); + } + ctx.collect(bytes); + }; + + /** + * Registers a Web Worker to receive immediate entropy from the main thread. + * This method is required until Web Workers can access the native crypto + * API. This method should be called twice for each created worker, once in + * the main thread, and once in the worker itself. + * + * @param worker the worker to register. + */ + ctx.registerWorker = function(worker) { + // worker receives random bytes + if(worker === self) { + ctx.seedFile = function(needed, callback) { + function listener(e) { + var data = e.data; + if(data.forge && data.forge.prng) { + self.removeEventListener('message', listener); + callback(data.forge.prng.err, data.forge.prng.bytes); + } + } + self.addEventListener('message', listener); + self.postMessage({forge: {prng: {needed: needed}}}); + }; + } else { + // main thread sends random bytes upon request + var listener = function(e) { + var data = e.data; + if(data.forge && data.forge.prng) { + ctx.seedFile(data.forge.prng.needed, function(err, bytes) { + worker.postMessage({forge: {prng: {err: err, bytes: bytes}}}); + }); + } + }; + // TODO: do we need to remove the event listener when the worker dies? + worker.addEventListener('message', listener); + } + }; + + return ctx; +}; diff --git a/node_modules/node-forge/lib/pss.js b/node_modules/node-forge/lib/pss.js new file mode 100644 index 0000000..2596693 --- /dev/null +++ b/node_modules/node-forge/lib/pss.js @@ -0,0 +1,241 @@ +/** + * Javascript implementation of PKCS#1 PSS signature padding. + * + * @author Stefan Siegl + * + * Copyright (c) 2012 Stefan Siegl + */ +var forge = require('./forge'); +require('./random'); +require('./util'); + +// shortcut for PSS API +var pss = module.exports = forge.pss = forge.pss || {}; + +/** + * Creates a PSS signature scheme object. + * + * There are several ways to provide a salt for encoding: + * + * 1. Specify the saltLength only and the built-in PRNG will generate it. + * 2. Specify the saltLength and a custom PRNG with 'getBytesSync' defined that + * will be used. + * 3. Specify the salt itself as a forge.util.ByteBuffer. + * + * @param options the options to use: + * md the message digest object to use, a forge md instance. + * mgf the mask generation function to use, a forge mgf instance. + * [saltLength] the length of the salt in octets. + * [prng] the pseudo-random number generator to use to produce a salt. + * [salt] the salt to use when encoding. + * + * @return a signature scheme object. + */ +pss.create = function(options) { + // backwards compatibility w/legacy args: hash, mgf, sLen + if(arguments.length === 3) { + options = { + md: arguments[0], + mgf: arguments[1], + saltLength: arguments[2] + }; + } + + var hash = options.md; + var mgf = options.mgf; + var hLen = hash.digestLength; + + var salt_ = options.salt || null; + if(typeof salt_ === 'string') { + // assume binary-encoded string + salt_ = forge.util.createBuffer(salt_); + } + + var sLen; + if('saltLength' in options) { + sLen = options.saltLength; + } else if(salt_ !== null) { + sLen = salt_.length(); + } else { + throw new Error('Salt length not specified or specific salt not given.'); + } + + if(salt_ !== null && salt_.length() !== sLen) { + throw new Error('Given salt length does not match length of given salt.'); + } + + var prng = options.prng || forge.random; + + var pssobj = {}; + + /** + * Encodes a PSS signature. + * + * This function implements EMSA-PSS-ENCODE as per RFC 3447, section 9.1.1. + * + * @param md the message digest object with the hash to sign. + * @param modsBits the length of the RSA modulus in bits. + * + * @return the encoded message as a binary-encoded string of length + * ceil((modBits - 1) / 8). + */ + pssobj.encode = function(md, modBits) { + var i; + var emBits = modBits - 1; + var emLen = Math.ceil(emBits / 8); + + /* 2. Let mHash = Hash(M), an octet string of length hLen. */ + var mHash = md.digest().getBytes(); + + /* 3. If emLen < hLen + sLen + 2, output "encoding error" and stop. */ + if(emLen < hLen + sLen + 2) { + throw new Error('Message is too long to encrypt.'); + } + + /* 4. Generate a random octet string salt of length sLen; if sLen = 0, + * then salt is the empty string. */ + var salt; + if(salt_ === null) { + salt = prng.getBytesSync(sLen); + } else { + salt = salt_.bytes(); + } + + /* 5. Let M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt; */ + var m_ = new forge.util.ByteBuffer(); + m_.fillWithByte(0, 8); + m_.putBytes(mHash); + m_.putBytes(salt); + + /* 6. Let H = Hash(M'), an octet string of length hLen. */ + hash.start(); + hash.update(m_.getBytes()); + var h = hash.digest().getBytes(); + + /* 7. Generate an octet string PS consisting of emLen - sLen - hLen - 2 + * zero octets. The length of PS may be 0. */ + var ps = new forge.util.ByteBuffer(); + ps.fillWithByte(0, emLen - sLen - hLen - 2); + + /* 8. Let DB = PS || 0x01 || salt; DB is an octet string of length + * emLen - hLen - 1. */ + ps.putByte(0x01); + ps.putBytes(salt); + var db = ps.getBytes(); + + /* 9. Let dbMask = MGF(H, emLen - hLen - 1). */ + var maskLen = emLen - hLen - 1; + var dbMask = mgf.generate(h, maskLen); + + /* 10. Let maskedDB = DB \xor dbMask. */ + var maskedDB = ''; + for(i = 0; i < maskLen; i++) { + maskedDB += String.fromCharCode(db.charCodeAt(i) ^ dbMask.charCodeAt(i)); + } + + /* 11. Set the leftmost 8emLen - emBits bits of the leftmost octet in + * maskedDB to zero. */ + var mask = (0xFF00 >> (8 * emLen - emBits)) & 0xFF; + maskedDB = String.fromCharCode(maskedDB.charCodeAt(0) & ~mask) + + maskedDB.substr(1); + + /* 12. Let EM = maskedDB || H || 0xbc. + * 13. Output EM. */ + return maskedDB + h + String.fromCharCode(0xbc); + }; + + /** + * Verifies a PSS signature. + * + * This function implements EMSA-PSS-VERIFY as per RFC 3447, section 9.1.2. + * + * @param mHash the message digest hash, as a binary-encoded string, to + * compare against the signature. + * @param em the encoded message, as a binary-encoded string + * (RSA decryption result). + * @param modsBits the length of the RSA modulus in bits. + * + * @return true if the signature was verified, false if not. + */ + pssobj.verify = function(mHash, em, modBits) { + var i; + var emBits = modBits - 1; + var emLen = Math.ceil(emBits / 8); + + /* c. Convert the message representative m to an encoded message EM + * of length emLen = ceil((modBits - 1) / 8) octets, where modBits + * is the length in bits of the RSA modulus n */ + em = em.substr(-emLen); + + /* 3. If emLen < hLen + sLen + 2, output "inconsistent" and stop. */ + if(emLen < hLen + sLen + 2) { + throw new Error('Inconsistent parameters to PSS signature verification.'); + } + + /* 4. If the rightmost octet of EM does not have hexadecimal value + * 0xbc, output "inconsistent" and stop. */ + if(em.charCodeAt(emLen - 1) !== 0xbc) { + throw new Error('Encoded message does not end in 0xBC.'); + } + + /* 5. Let maskedDB be the leftmost emLen - hLen - 1 octets of EM, and + * let H be the next hLen octets. */ + var maskLen = emLen - hLen - 1; + var maskedDB = em.substr(0, maskLen); + var h = em.substr(maskLen, hLen); + + /* 6. If the leftmost 8emLen - emBits bits of the leftmost octet in + * maskedDB are not all equal to zero, output "inconsistent" and stop. */ + var mask = (0xFF00 >> (8 * emLen - emBits)) & 0xFF; + if((maskedDB.charCodeAt(0) & mask) !== 0) { + throw new Error('Bits beyond keysize not zero as expected.'); + } + + /* 7. Let dbMask = MGF(H, emLen - hLen - 1). */ + var dbMask = mgf.generate(h, maskLen); + + /* 8. Let DB = maskedDB \xor dbMask. */ + var db = ''; + for(i = 0; i < maskLen; i++) { + db += String.fromCharCode(maskedDB.charCodeAt(i) ^ dbMask.charCodeAt(i)); + } + + /* 9. Set the leftmost 8emLen - emBits bits of the leftmost octet + * in DB to zero. */ + db = String.fromCharCode(db.charCodeAt(0) & ~mask) + db.substr(1); + + /* 10. If the emLen - hLen - sLen - 2 leftmost octets of DB are not zero + * or if the octet at position emLen - hLen - sLen - 1 (the leftmost + * position is "position 1") does not have hexadecimal value 0x01, + * output "inconsistent" and stop. */ + var checkLen = emLen - hLen - sLen - 2; + for(i = 0; i < checkLen; i++) { + if(db.charCodeAt(i) !== 0x00) { + throw new Error('Leftmost octets not zero as expected'); + } + } + + if(db.charCodeAt(checkLen) !== 0x01) { + throw new Error('Inconsistent PSS signature, 0x01 marker not found'); + } + + /* 11. Let salt be the last sLen octets of DB. */ + var salt = db.substr(-sLen); + + /* 12. Let M' = (0x)00 00 00 00 00 00 00 00 || mHash || salt */ + var m_ = new forge.util.ByteBuffer(); + m_.fillWithByte(0, 8); + m_.putBytes(mHash); + m_.putBytes(salt); + + /* 13. Let H' = Hash(M'), an octet string of length hLen. */ + hash.start(); + hash.update(m_.getBytes()); + var h_ = hash.digest().getBytes(); + + /* 14. If H = H', output "consistent." Otherwise, output "inconsistent." */ + return h === h_; + }; + + return pssobj; +}; diff --git a/node_modules/node-forge/lib/random.js b/node_modules/node-forge/lib/random.js new file mode 100644 index 0000000..d4e4bea --- /dev/null +++ b/node_modules/node-forge/lib/random.js @@ -0,0 +1,191 @@ +/** + * An API for getting cryptographically-secure random bytes. The bytes are + * generated using the Fortuna algorithm devised by Bruce Schneier and + * Niels Ferguson. + * + * Getting strong random bytes is not yet easy to do in javascript. The only + * truish random entropy that can be collected is from the mouse, keyboard, or + * from timing with respect to page loads, etc. This generator makes a poor + * attempt at providing random bytes when those sources haven't yet provided + * enough entropy to initially seed or to reseed the PRNG. + * + * @author Dave Longley + * + * Copyright (c) 2009-2014 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./aes'); +require('./sha256'); +require('./prng'); +require('./util'); + +(function() { + +// forge.random already defined +if(forge.random && forge.random.getBytes) { + module.exports = forge.random; + return; +} + +(function(jQuery) { + +// the default prng plugin, uses AES-128 +var prng_aes = {}; +var _prng_aes_output = new Array(4); +var _prng_aes_buffer = forge.util.createBuffer(); +prng_aes.formatKey = function(key) { + // convert the key into 32-bit integers + var tmp = forge.util.createBuffer(key); + key = new Array(4); + key[0] = tmp.getInt32(); + key[1] = tmp.getInt32(); + key[2] = tmp.getInt32(); + key[3] = tmp.getInt32(); + + // return the expanded key + return forge.aes._expandKey(key, false); +}; +prng_aes.formatSeed = function(seed) { + // convert seed into 32-bit integers + var tmp = forge.util.createBuffer(seed); + seed = new Array(4); + seed[0] = tmp.getInt32(); + seed[1] = tmp.getInt32(); + seed[2] = tmp.getInt32(); + seed[3] = tmp.getInt32(); + return seed; +}; +prng_aes.cipher = function(key, seed) { + forge.aes._updateBlock(key, seed, _prng_aes_output, false); + _prng_aes_buffer.putInt32(_prng_aes_output[0]); + _prng_aes_buffer.putInt32(_prng_aes_output[1]); + _prng_aes_buffer.putInt32(_prng_aes_output[2]); + _prng_aes_buffer.putInt32(_prng_aes_output[3]); + return _prng_aes_buffer.getBytes(); +}; +prng_aes.increment = function(seed) { + // FIXME: do we care about carry or signed issues? + ++seed[3]; + return seed; +}; +prng_aes.md = forge.md.sha256; + +/** + * Creates a new PRNG. + */ +function spawnPrng() { + var ctx = forge.prng.create(prng_aes); + + /** + * Gets random bytes. If a native secure crypto API is unavailable, this + * method tries to make the bytes more unpredictable by drawing from data that + * can be collected from the user of the browser, eg: mouse movement. + * + * If a callback is given, this method will be called asynchronously. + * + * @param count the number of random bytes to get. + * @param [callback(err, bytes)] called once the operation completes. + * + * @return the random bytes in a string. + */ + ctx.getBytes = function(count, callback) { + return ctx.generate(count, callback); + }; + + /** + * Gets random bytes asynchronously. If a native secure crypto API is + * unavailable, this method tries to make the bytes more unpredictable by + * drawing from data that can be collected from the user of the browser, + * eg: mouse movement. + * + * @param count the number of random bytes to get. + * + * @return the random bytes in a string. + */ + ctx.getBytesSync = function(count) { + return ctx.generate(count); + }; + + return ctx; +} + +// create default prng context +var _ctx = spawnPrng(); + +// add other sources of entropy only if window.crypto.getRandomValues is not +// available -- otherwise this source will be automatically used by the prng +var getRandomValues = null; +var globalScope = forge.util.globalScope; +var _crypto = globalScope.crypto || globalScope.msCrypto; +if(_crypto && _crypto.getRandomValues) { + getRandomValues = function(arr) { + return _crypto.getRandomValues(arr); + }; +} + +if(forge.options.usePureJavaScript || + (!forge.util.isNodejs && !getRandomValues)) { + // if this is a web worker, do not use weak entropy, instead register to + // receive strong entropy asynchronously from the main thread + if(typeof window === 'undefined' || window.document === undefined) { + // FIXME: + } + + // get load time entropy + _ctx.collectInt(+new Date(), 32); + + // add some entropy from navigator object + if(typeof(navigator) !== 'undefined') { + var _navBytes = ''; + for(var key in navigator) { + try { + if(typeof(navigator[key]) == 'string') { + _navBytes += navigator[key]; + } + } catch(e) { + /* Some navigator keys might not be accessible, e.g. the geolocation + attribute throws an exception if touched in Mozilla chrome:// + context. + + Silently ignore this and just don't use this as a source of + entropy. */ + } + } + _ctx.collect(_navBytes); + _navBytes = null; + } + + // add mouse and keyboard collectors if jquery is available + if(jQuery) { + // set up mouse entropy capture + jQuery().mousemove(function(e) { + // add mouse coords + _ctx.collectInt(e.clientX, 16); + _ctx.collectInt(e.clientY, 16); + }); + + // set up keyboard entropy capture + jQuery().keypress(function(e) { + _ctx.collectInt(e.charCode, 8); + }); + } +} + +/* Random API */ +if(!forge.random) { + forge.random = _ctx; +} else { + // extend forge.random with _ctx + for(var key in _ctx) { + forge.random[key] = _ctx[key]; + } +} + +// expose spawn PRNG +forge.random.createInstance = spawnPrng; + +module.exports = forge.random; + +})(typeof(jQuery) !== 'undefined' ? jQuery : null); + +})(); diff --git a/node_modules/node-forge/lib/rc2.js b/node_modules/node-forge/lib/rc2.js new file mode 100644 index 0000000..e33f78a --- /dev/null +++ b/node_modules/node-forge/lib/rc2.js @@ -0,0 +1,410 @@ +/** + * RC2 implementation. + * + * @author Stefan Siegl + * + * Copyright (c) 2012 Stefan Siegl + * + * Information on the RC2 cipher is available from RFC #2268, + * http://www.ietf.org/rfc/rfc2268.txt + */ +var forge = require('./forge'); +require('./util'); + +var piTable = [ + 0xd9, 0x78, 0xf9, 0xc4, 0x19, 0xdd, 0xb5, 0xed, 0x28, 0xe9, 0xfd, 0x79, 0x4a, 0xa0, 0xd8, 0x9d, + 0xc6, 0x7e, 0x37, 0x83, 0x2b, 0x76, 0x53, 0x8e, 0x62, 0x4c, 0x64, 0x88, 0x44, 0x8b, 0xfb, 0xa2, + 0x17, 0x9a, 0x59, 0xf5, 0x87, 0xb3, 0x4f, 0x13, 0x61, 0x45, 0x6d, 0x8d, 0x09, 0x81, 0x7d, 0x32, + 0xbd, 0x8f, 0x40, 0xeb, 0x86, 0xb7, 0x7b, 0x0b, 0xf0, 0x95, 0x21, 0x22, 0x5c, 0x6b, 0x4e, 0x82, + 0x54, 0xd6, 0x65, 0x93, 0xce, 0x60, 0xb2, 0x1c, 0x73, 0x56, 0xc0, 0x14, 0xa7, 0x8c, 0xf1, 0xdc, + 0x12, 0x75, 0xca, 0x1f, 0x3b, 0xbe, 0xe4, 0xd1, 0x42, 0x3d, 0xd4, 0x30, 0xa3, 0x3c, 0xb6, 0x26, + 0x6f, 0xbf, 0x0e, 0xda, 0x46, 0x69, 0x07, 0x57, 0x27, 0xf2, 0x1d, 0x9b, 0xbc, 0x94, 0x43, 0x03, + 0xf8, 0x11, 0xc7, 0xf6, 0x90, 0xef, 0x3e, 0xe7, 0x06, 0xc3, 0xd5, 0x2f, 0xc8, 0x66, 0x1e, 0xd7, + 0x08, 0xe8, 0xea, 0xde, 0x80, 0x52, 0xee, 0xf7, 0x84, 0xaa, 0x72, 0xac, 0x35, 0x4d, 0x6a, 0x2a, + 0x96, 0x1a, 0xd2, 0x71, 0x5a, 0x15, 0x49, 0x74, 0x4b, 0x9f, 0xd0, 0x5e, 0x04, 0x18, 0xa4, 0xec, + 0xc2, 0xe0, 0x41, 0x6e, 0x0f, 0x51, 0xcb, 0xcc, 0x24, 0x91, 0xaf, 0x50, 0xa1, 0xf4, 0x70, 0x39, + 0x99, 0x7c, 0x3a, 0x85, 0x23, 0xb8, 0xb4, 0x7a, 0xfc, 0x02, 0x36, 0x5b, 0x25, 0x55, 0x97, 0x31, + 0x2d, 0x5d, 0xfa, 0x98, 0xe3, 0x8a, 0x92, 0xae, 0x05, 0xdf, 0x29, 0x10, 0x67, 0x6c, 0xba, 0xc9, + 0xd3, 0x00, 0xe6, 0xcf, 0xe1, 0x9e, 0xa8, 0x2c, 0x63, 0x16, 0x01, 0x3f, 0x58, 0xe2, 0x89, 0xa9, + 0x0d, 0x38, 0x34, 0x1b, 0xab, 0x33, 0xff, 0xb0, 0xbb, 0x48, 0x0c, 0x5f, 0xb9, 0xb1, 0xcd, 0x2e, + 0xc5, 0xf3, 0xdb, 0x47, 0xe5, 0xa5, 0x9c, 0x77, 0x0a, 0xa6, 0x20, 0x68, 0xfe, 0x7f, 0xc1, 0xad +]; + +var s = [1, 2, 3, 5]; + +/** + * Rotate a word left by given number of bits. + * + * Bits that are shifted out on the left are put back in on the right + * hand side. + * + * @param word The word to shift left. + * @param bits The number of bits to shift by. + * @return The rotated word. + */ +var rol = function(word, bits) { + return ((word << bits) & 0xffff) | ((word & 0xffff) >> (16 - bits)); +}; + +/** + * Rotate a word right by given number of bits. + * + * Bits that are shifted out on the right are put back in on the left + * hand side. + * + * @param word The word to shift right. + * @param bits The number of bits to shift by. + * @return The rotated word. + */ +var ror = function(word, bits) { + return ((word & 0xffff) >> bits) | ((word << (16 - bits)) & 0xffff); +}; + +/* RC2 API */ +module.exports = forge.rc2 = forge.rc2 || {}; + +/** + * Perform RC2 key expansion as per RFC #2268, section 2. + * + * @param key variable-length user key (between 1 and 128 bytes) + * @param effKeyBits number of effective key bits (default: 128) + * @return the expanded RC2 key (ByteBuffer of 128 bytes) + */ +forge.rc2.expandKey = function(key, effKeyBits) { + if(typeof key === 'string') { + key = forge.util.createBuffer(key); + } + effKeyBits = effKeyBits || 128; + + /* introduce variables that match the names used in RFC #2268 */ + var L = key; + var T = key.length(); + var T1 = effKeyBits; + var T8 = Math.ceil(T1 / 8); + var TM = 0xff >> (T1 & 0x07); + var i; + + for(i = T; i < 128; i++) { + L.putByte(piTable[(L.at(i - 1) + L.at(i - T)) & 0xff]); + } + + L.setAt(128 - T8, piTable[L.at(128 - T8) & TM]); + + for(i = 127 - T8; i >= 0; i--) { + L.setAt(i, piTable[L.at(i + 1) ^ L.at(i + T8)]); + } + + return L; +}; + +/** + * Creates a RC2 cipher object. + * + * @param key the symmetric key to use (as base for key generation). + * @param bits the number of effective key bits. + * @param encrypt false for decryption, true for encryption. + * + * @return the cipher. + */ +var createCipher = function(key, bits, encrypt) { + var _finish = false, _input = null, _output = null, _iv = null; + var mixRound, mashRound; + var i, j, K = []; + + /* Expand key and fill into K[] Array */ + key = forge.rc2.expandKey(key, bits); + for(i = 0; i < 64; i++) { + K.push(key.getInt16Le()); + } + + if(encrypt) { + /** + * Perform one mixing round "in place". + * + * @param R Array of four words to perform mixing on. + */ + mixRound = function(R) { + for(i = 0; i < 4; i++) { + R[i] += K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) + + ((~R[(i + 3) % 4]) & R[(i + 1) % 4]); + R[i] = rol(R[i], s[i]); + j++; + } + }; + + /** + * Perform one mashing round "in place". + * + * @param R Array of four words to perform mashing on. + */ + mashRound = function(R) { + for(i = 0; i < 4; i++) { + R[i] += K[R[(i + 3) % 4] & 63]; + } + }; + } else { + /** + * Perform one r-mixing round "in place". + * + * @param R Array of four words to perform mixing on. + */ + mixRound = function(R) { + for(i = 3; i >= 0; i--) { + R[i] = ror(R[i], s[i]); + R[i] -= K[j] + (R[(i + 3) % 4] & R[(i + 2) % 4]) + + ((~R[(i + 3) % 4]) & R[(i + 1) % 4]); + j--; + } + }; + + /** + * Perform one r-mashing round "in place". + * + * @param R Array of four words to perform mashing on. + */ + mashRound = function(R) { + for(i = 3; i >= 0; i--) { + R[i] -= K[R[(i + 3) % 4] & 63]; + } + }; + } + + /** + * Run the specified cipher execution plan. + * + * This function takes four words from the input buffer, applies the IV on + * it (if requested) and runs the provided execution plan. + * + * The plan must be put together in form of a array of arrays. Where the + * outer one is simply a list of steps to perform and the inner one needs + * to have two elements: the first one telling how many rounds to perform, + * the second one telling what to do (i.e. the function to call). + * + * @param {Array} plan The plan to execute. + */ + var runPlan = function(plan) { + var R = []; + + /* Get data from input buffer and fill the four words into R */ + for(i = 0; i < 4; i++) { + var val = _input.getInt16Le(); + + if(_iv !== null) { + if(encrypt) { + /* We're encrypting, apply the IV first. */ + val ^= _iv.getInt16Le(); + } else { + /* We're decryption, keep cipher text for next block. */ + _iv.putInt16Le(val); + } + } + + R.push(val & 0xffff); + } + + /* Reset global "j" variable as per spec. */ + j = encrypt ? 0 : 63; + + /* Run execution plan. */ + for(var ptr = 0; ptr < plan.length; ptr++) { + for(var ctr = 0; ctr < plan[ptr][0]; ctr++) { + plan[ptr][1](R); + } + } + + /* Write back result to output buffer. */ + for(i = 0; i < 4; i++) { + if(_iv !== null) { + if(encrypt) { + /* We're encrypting in CBC-mode, feed back encrypted bytes into + IV buffer to carry it forward to next block. */ + _iv.putInt16Le(R[i]); + } else { + R[i] ^= _iv.getInt16Le(); + } + } + + _output.putInt16Le(R[i]); + } + }; + + /* Create cipher object */ + var cipher = null; + cipher = { + /** + * Starts or restarts the encryption or decryption process, whichever + * was previously configured. + * + * To use the cipher in CBC mode, iv may be given either as a string + * of bytes, or as a byte buffer. For ECB mode, give null as iv. + * + * @param iv the initialization vector to use, null for ECB mode. + * @param output the output the buffer to write to, null to create one. + */ + start: function(iv, output) { + if(iv) { + /* CBC mode */ + if(typeof iv === 'string') { + iv = forge.util.createBuffer(iv); + } + } + + _finish = false; + _input = forge.util.createBuffer(); + _output = output || new forge.util.createBuffer(); + _iv = iv; + + cipher.output = _output; + }, + + /** + * Updates the next block. + * + * @param input the buffer to read from. + */ + update: function(input) { + if(!_finish) { + // not finishing, so fill the input buffer with more input + _input.putBuffer(input); + } + + while(_input.length() >= 8) { + runPlan([ + [ 5, mixRound ], + [ 1, mashRound ], + [ 6, mixRound ], + [ 1, mashRound ], + [ 5, mixRound ] + ]); + } + }, + + /** + * Finishes encrypting or decrypting. + * + * @param pad a padding function to use, null for PKCS#7 padding, + * signature(blockSize, buffer, decrypt). + * + * @return true if successful, false on error. + */ + finish: function(pad) { + var rval = true; + + if(encrypt) { + if(pad) { + rval = pad(8, _input, !encrypt); + } else { + // add PKCS#7 padding to block (each pad byte is the + // value of the number of pad bytes) + var padding = (_input.length() === 8) ? 8 : (8 - _input.length()); + _input.fillWithByte(padding, padding); + } + } + + if(rval) { + // do final update + _finish = true; + cipher.update(); + } + + if(!encrypt) { + // check for error: input data not a multiple of block size + rval = (_input.length() === 0); + if(rval) { + if(pad) { + rval = pad(8, _output, !encrypt); + } else { + // ensure padding byte count is valid + var len = _output.length(); + var count = _output.at(len - 1); + + if(count > len) { + rval = false; + } else { + // trim off padding bytes + _output.truncate(count); + } + } + } + } + + return rval; + } + }; + + return cipher; +}; + +/** + * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the + * given symmetric key. The output will be stored in the 'output' member + * of the returned cipher. + * + * The key and iv may be given as a string of bytes or a byte buffer. + * The cipher is initialized to use 128 effective key bits. + * + * @param key the symmetric key to use. + * @param iv the initialization vector to use. + * @param output the buffer to write to, null to create one. + * + * @return the cipher. + */ +forge.rc2.startEncrypting = function(key, iv, output) { + var cipher = forge.rc2.createEncryptionCipher(key, 128); + cipher.start(iv, output); + return cipher; +}; + +/** + * Creates an RC2 cipher object to encrypt data in ECB or CBC mode using the + * given symmetric key. + * + * The key may be given as a string of bytes or a byte buffer. + * + * To start encrypting call start() on the cipher with an iv and optional + * output buffer. + * + * @param key the symmetric key to use. + * + * @return the cipher. + */ +forge.rc2.createEncryptionCipher = function(key, bits) { + return createCipher(key, bits, true); +}; + +/** + * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the + * given symmetric key. The output will be stored in the 'output' member + * of the returned cipher. + * + * The key and iv may be given as a string of bytes or a byte buffer. + * The cipher is initialized to use 128 effective key bits. + * + * @param key the symmetric key to use. + * @param iv the initialization vector to use. + * @param output the buffer to write to, null to create one. + * + * @return the cipher. + */ +forge.rc2.startDecrypting = function(key, iv, output) { + var cipher = forge.rc2.createDecryptionCipher(key, 128); + cipher.start(iv, output); + return cipher; +}; + +/** + * Creates an RC2 cipher object to decrypt data in ECB or CBC mode using the + * given symmetric key. + * + * The key may be given as a string of bytes or a byte buffer. + * + * To start decrypting call start() on the cipher with an iv and optional + * output buffer. + * + * @param key the symmetric key to use. + * + * @return the cipher. + */ +forge.rc2.createDecryptionCipher = function(key, bits) { + return createCipher(key, bits, false); +}; diff --git a/node_modules/node-forge/lib/rsa.js b/node_modules/node-forge/lib/rsa.js new file mode 100644 index 0000000..7c67917 --- /dev/null +++ b/node_modules/node-forge/lib/rsa.js @@ -0,0 +1,1858 @@ +/** + * Javascript implementation of basic RSA algorithms. + * + * @author Dave Longley + * + * Copyright (c) 2010-2014 Digital Bazaar, Inc. + * + * The only algorithm currently supported for PKI is RSA. + * + * An RSA key is often stored in ASN.1 DER format. The SubjectPublicKeyInfo + * ASN.1 structure is composed of an algorithm of type AlgorithmIdentifier + * and a subjectPublicKey of type bit string. + * + * The AlgorithmIdentifier contains an Object Identifier (OID) and parameters + * for the algorithm, if any. In the case of RSA, there aren't any. + * + * SubjectPublicKeyInfo ::= SEQUENCE { + * algorithm AlgorithmIdentifier, + * subjectPublicKey BIT STRING + * } + * + * AlgorithmIdentifer ::= SEQUENCE { + * algorithm OBJECT IDENTIFIER, + * parameters ANY DEFINED BY algorithm OPTIONAL + * } + * + * For an RSA public key, the subjectPublicKey is: + * + * RSAPublicKey ::= SEQUENCE { + * modulus INTEGER, -- n + * publicExponent INTEGER -- e + * } + * + * PrivateKeyInfo ::= SEQUENCE { + * version Version, + * privateKeyAlgorithm PrivateKeyAlgorithmIdentifier, + * privateKey PrivateKey, + * attributes [0] IMPLICIT Attributes OPTIONAL + * } + * + * Version ::= INTEGER + * PrivateKeyAlgorithmIdentifier ::= AlgorithmIdentifier + * PrivateKey ::= OCTET STRING + * Attributes ::= SET OF Attribute + * + * An RSA private key as the following structure: + * + * RSAPrivateKey ::= SEQUENCE { + * version Version, + * modulus INTEGER, -- n + * publicExponent INTEGER, -- e + * privateExponent INTEGER, -- d + * prime1 INTEGER, -- p + * prime2 INTEGER, -- q + * exponent1 INTEGER, -- d mod (p-1) + * exponent2 INTEGER, -- d mod (q-1) + * coefficient INTEGER -- (inverse of q) mod p + * } + * + * Version ::= INTEGER + * + * The OID for the RSA key algorithm is: 1.2.840.113549.1.1.1 + */ +var forge = require('./forge'); +require('./asn1'); +require('./jsbn'); +require('./oids'); +require('./pkcs1'); +require('./prime'); +require('./random'); +require('./util'); + +if(typeof BigInteger === 'undefined') { + var BigInteger = forge.jsbn.BigInteger; +} + +var _crypto = forge.util.isNodejs ? require('crypto') : null; + +// shortcut for asn.1 API +var asn1 = forge.asn1; + +// shortcut for util API +var util = forge.util; + +/* + * RSA encryption and decryption, see RFC 2313. + */ +forge.pki = forge.pki || {}; +module.exports = forge.pki.rsa = forge.rsa = forge.rsa || {}; +var pki = forge.pki; + +// for finding primes, which are 30k+i for i = 1, 7, 11, 13, 17, 19, 23, 29 +var GCD_30_DELTA = [6, 4, 2, 4, 2, 4, 6, 2]; + +// validator for a PrivateKeyInfo structure +var privateKeyValidator = { + // PrivateKeyInfo + name: 'PrivateKeyInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + // Version (INTEGER) + name: 'PrivateKeyInfo.version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyVersion' + }, { + // privateKeyAlgorithm + name: 'PrivateKeyInfo.privateKeyAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'AlgorithmIdentifier.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'privateKeyOid' + }] + }, { + // PrivateKey + name: 'PrivateKeyInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OCTETSTRING, + constructed: false, + capture: 'privateKey' + }] +}; + +// validator for an RSA private key +var rsaPrivateKeyValidator = { + // RSAPrivateKey + name: 'RSAPrivateKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + // Version (INTEGER) + name: 'RSAPrivateKey.version', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyVersion' + }, { + // modulus (n) + name: 'RSAPrivateKey.modulus', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyModulus' + }, { + // publicExponent (e) + name: 'RSAPrivateKey.publicExponent', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyPublicExponent' + }, { + // privateExponent (d) + name: 'RSAPrivateKey.privateExponent', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyPrivateExponent' + }, { + // prime1 (p) + name: 'RSAPrivateKey.prime1', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyPrime1' + }, { + // prime2 (q) + name: 'RSAPrivateKey.prime2', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyPrime2' + }, { + // exponent1 (d mod (p-1)) + name: 'RSAPrivateKey.exponent1', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyExponent1' + }, { + // exponent2 (d mod (q-1)) + name: 'RSAPrivateKey.exponent2', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyExponent2' + }, { + // coefficient ((inverse of q) mod p) + name: 'RSAPrivateKey.coefficient', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'privateKeyCoefficient' + }] +}; + +// validator for an RSA public key +var rsaPublicKeyValidator = { + // RSAPublicKey + name: 'RSAPublicKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + // modulus (n) + name: 'RSAPublicKey.modulus', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'publicKeyModulus' + }, { + // publicExponent (e) + name: 'RSAPublicKey.exponent', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'publicKeyExponent' + }] +}; + +// validator for an SubjectPublicKeyInfo structure +// Note: Currently only works with an RSA public key +var publicKeyValidator = forge.pki.rsa.publicKeyValidator = { + name: 'SubjectPublicKeyInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'subjectPublicKeyInfo', + value: [{ + name: 'SubjectPublicKeyInfo.AlgorithmIdentifier', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'AlgorithmIdentifier.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'publicKeyOid' + }] + }, { + // subjectPublicKey + name: 'SubjectPublicKeyInfo.subjectPublicKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + value: [{ + // RSAPublicKey + name: 'SubjectPublicKeyInfo.subjectPublicKey.RSAPublicKey', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + optional: true, + captureAsn1: 'rsaPublicKey' + }] + }] +}; + +/** + * Wrap digest in DigestInfo object. + * + * This function implements EMSA-PKCS1-v1_5-ENCODE as per RFC 3447. + * + * DigestInfo ::= SEQUENCE { + * digestAlgorithm DigestAlgorithmIdentifier, + * digest Digest + * } + * + * DigestAlgorithmIdentifier ::= AlgorithmIdentifier + * Digest ::= OCTET STRING + * + * @param md the message digest object with the hash to sign. + * + * @return the encoded message (ready for RSA encrytion) + */ +var emsaPkcs1v15encode = function(md) { + // get the oid for the algorithm + var oid; + if(md.algorithm in pki.oids) { + oid = pki.oids[md.algorithm]; + } else { + var error = new Error('Unknown message digest algorithm.'); + error.algorithm = md.algorithm; + throw error; + } + var oidBytes = asn1.oidToDer(oid).getBytes(); + + // create the digest info + var digestInfo = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + var digestAlgorithm = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + digestAlgorithm.value.push(asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OID, false, oidBytes)); + digestAlgorithm.value.push(asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '')); + var digest = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, + false, md.digest().getBytes()); + digestInfo.value.push(digestAlgorithm); + digestInfo.value.push(digest); + + // encode digest info + return asn1.toDer(digestInfo).getBytes(); +}; + +/** + * Performs x^c mod n (RSA encryption or decryption operation). + * + * @param x the number to raise and mod. + * @param key the key to use. + * @param pub true if the key is public, false if private. + * + * @return the result of x^c mod n. + */ +var _modPow = function(x, key, pub) { + if(pub) { + return x.modPow(key.e, key.n); + } + + if(!key.p || !key.q) { + // allow calculation without CRT params (slow) + return x.modPow(key.d, key.n); + } + + // pre-compute dP, dQ, and qInv if necessary + if(!key.dP) { + key.dP = key.d.mod(key.p.subtract(BigInteger.ONE)); + } + if(!key.dQ) { + key.dQ = key.d.mod(key.q.subtract(BigInteger.ONE)); + } + if(!key.qInv) { + key.qInv = key.q.modInverse(key.p); + } + + /* Chinese remainder theorem (CRT) states: + + Suppose n1, n2, ..., nk are positive integers which are pairwise + coprime (n1 and n2 have no common factors other than 1). For any + integers x1, x2, ..., xk there exists an integer x solving the + system of simultaneous congruences (where ~= means modularly + congruent so a ~= b mod n means a mod n = b mod n): + + x ~= x1 mod n1 + x ~= x2 mod n2 + ... + x ~= xk mod nk + + This system of congruences has a single simultaneous solution x + between 0 and n - 1. Furthermore, each xk solution and x itself + is congruent modulo the product n = n1*n2*...*nk. + So x1 mod n = x2 mod n = xk mod n = x mod n. + + The single simultaneous solution x can be solved with the following + equation: + + x = sum(xi*ri*si) mod n where ri = n/ni and si = ri^-1 mod ni. + + Where x is less than n, xi = x mod ni. + + For RSA we are only concerned with k = 2. The modulus n = pq, where + p and q are coprime. The RSA decryption algorithm is: + + y = x^d mod n + + Given the above: + + x1 = x^d mod p + r1 = n/p = q + s1 = q^-1 mod p + x2 = x^d mod q + r2 = n/q = p + s2 = p^-1 mod q + + So y = (x1r1s1 + x2r2s2) mod n + = ((x^d mod p)q(q^-1 mod p) + (x^d mod q)p(p^-1 mod q)) mod n + + According to Fermat's Little Theorem, if the modulus P is prime, + for any integer A not evenly divisible by P, A^(P-1) ~= 1 mod P. + Since A is not divisible by P it follows that if: + N ~= M mod (P - 1), then A^N mod P = A^M mod P. Therefore: + + A^N mod P = A^(M mod (P - 1)) mod P. (The latter takes less effort + to calculate). In order to calculate x^d mod p more quickly the + exponent d mod (p - 1) is stored in the RSA private key (the same + is done for x^d mod q). These values are referred to as dP and dQ + respectively. Therefore we now have: + + y = ((x^dP mod p)q(q^-1 mod p) + (x^dQ mod q)p(p^-1 mod q)) mod n + + Since we'll be reducing x^dP by modulo p (same for q) we can also + reduce x by p (and q respectively) before hand. Therefore, let + + xp = ((x mod p)^dP mod p), and + xq = ((x mod q)^dQ mod q), yielding: + + y = (xp*q*(q^-1 mod p) + xq*p*(p^-1 mod q)) mod n + + This can be further reduced to a simple algorithm that only + requires 1 inverse (the q inverse is used) to be used and stored. + The algorithm is called Garner's algorithm. If qInv is the + inverse of q, we simply calculate: + + y = (qInv*(xp - xq) mod p) * q + xq + + However, there are two further complications. First, we need to + ensure that xp > xq to prevent signed BigIntegers from being used + so we add p until this is true (since we will be mod'ing with + p anyway). Then, there is a known timing attack on algorithms + using the CRT. To mitigate this risk, "cryptographic blinding" + should be used. This requires simply generating a random number r + between 0 and n-1 and its inverse and multiplying x by r^e before + calculating y and then multiplying y by r^-1 afterwards. Note that + r must be coprime with n (gcd(r, n) === 1) in order to have an + inverse. + */ + + // cryptographic blinding + var r; + do { + r = new BigInteger( + forge.util.bytesToHex(forge.random.getBytes(key.n.bitLength() / 8)), + 16); + } while(r.compareTo(key.n) >= 0 || !r.gcd(key.n).equals(BigInteger.ONE)); + x = x.multiply(r.modPow(key.e, key.n)).mod(key.n); + + // calculate xp and xq + var xp = x.mod(key.p).modPow(key.dP, key.p); + var xq = x.mod(key.q).modPow(key.dQ, key.q); + + // xp must be larger than xq to avoid signed bit usage + while(xp.compareTo(xq) < 0) { + xp = xp.add(key.p); + } + + // do last step + var y = xp.subtract(xq) + .multiply(key.qInv).mod(key.p) + .multiply(key.q).add(xq); + + // remove effect of random for cryptographic blinding + y = y.multiply(r.modInverse(key.n)).mod(key.n); + + return y; +}; + +/** + * NOTE: THIS METHOD IS DEPRECATED, use 'sign' on a private key object or + * 'encrypt' on a public key object instead. + * + * Performs RSA encryption. + * + * The parameter bt controls whether to put padding bytes before the + * message passed in. Set bt to either true or false to disable padding + * completely (in order to handle e.g. EMSA-PSS encoding seperately before), + * signaling whether the encryption operation is a public key operation + * (i.e. encrypting data) or not, i.e. private key operation (data signing). + * + * For PKCS#1 v1.5 padding pass in the block type to use, i.e. either 0x01 + * (for signing) or 0x02 (for encryption). The key operation mode (private + * or public) is derived from this flag in that case). + * + * @param m the message to encrypt as a byte string. + * @param key the RSA key to use. + * @param bt for PKCS#1 v1.5 padding, the block type to use + * (0x01 for private key, 0x02 for public), + * to disable padding: true = public key, false = private key. + * + * @return the encrypted bytes as a string. + */ +pki.rsa.encrypt = function(m, key, bt) { + var pub = bt; + var eb; + + // get the length of the modulus in bytes + var k = Math.ceil(key.n.bitLength() / 8); + + if(bt !== false && bt !== true) { + // legacy, default to PKCS#1 v1.5 padding + pub = (bt === 0x02); + eb = _encodePkcs1_v1_5(m, key, bt); + } else { + eb = forge.util.createBuffer(); + eb.putBytes(m); + } + + // load encryption block as big integer 'x' + // FIXME: hex conversion inefficient, get BigInteger w/byte strings + var x = new BigInteger(eb.toHex(), 16); + + // do RSA encryption + var y = _modPow(x, key, pub); + + // convert y into the encrypted data byte string, if y is shorter in + // bytes than k, then prepend zero bytes to fill up ed + // FIXME: hex conversion inefficient, get BigInteger w/byte strings + var yhex = y.toString(16); + var ed = forge.util.createBuffer(); + var zeros = k - Math.ceil(yhex.length / 2); + while(zeros > 0) { + ed.putByte(0x00); + --zeros; + } + ed.putBytes(forge.util.hexToBytes(yhex)); + return ed.getBytes(); +}; + +/** + * NOTE: THIS METHOD IS DEPRECATED, use 'decrypt' on a private key object or + * 'verify' on a public key object instead. + * + * Performs RSA decryption. + * + * The parameter ml controls whether to apply PKCS#1 v1.5 padding + * or not. Set ml = false to disable padding removal completely + * (in order to handle e.g. EMSA-PSS later on) and simply pass back + * the RSA encryption block. + * + * @param ed the encrypted data to decrypt in as a byte string. + * @param key the RSA key to use. + * @param pub true for a public key operation, false for private. + * @param ml the message length, if known, false to disable padding. + * + * @return the decrypted message as a byte string. + */ +pki.rsa.decrypt = function(ed, key, pub, ml) { + // get the length of the modulus in bytes + var k = Math.ceil(key.n.bitLength() / 8); + + // error if the length of the encrypted data ED is not k + if(ed.length !== k) { + var error = new Error('Encrypted message length is invalid.'); + error.length = ed.length; + error.expected = k; + throw error; + } + + // convert encrypted data into a big integer + // FIXME: hex conversion inefficient, get BigInteger w/byte strings + var y = new BigInteger(forge.util.createBuffer(ed).toHex(), 16); + + // y must be less than the modulus or it wasn't the result of + // a previous mod operation (encryption) using that modulus + if(y.compareTo(key.n) >= 0) { + throw new Error('Encrypted message is invalid.'); + } + + // do RSA decryption + var x = _modPow(y, key, pub); + + // create the encryption block, if x is shorter in bytes than k, then + // prepend zero bytes to fill up eb + // FIXME: hex conversion inefficient, get BigInteger w/byte strings + var xhex = x.toString(16); + var eb = forge.util.createBuffer(); + var zeros = k - Math.ceil(xhex.length / 2); + while(zeros > 0) { + eb.putByte(0x00); + --zeros; + } + eb.putBytes(forge.util.hexToBytes(xhex)); + + if(ml !== false) { + // legacy, default to PKCS#1 v1.5 padding + return _decodePkcs1_v1_5(eb.getBytes(), key, pub); + } + + // return message + return eb.getBytes(); +}; + +/** + * Creates an RSA key-pair generation state object. It is used to allow + * key-generation to be performed in steps. It also allows for a UI to + * display progress updates. + * + * @param bits the size for the private key in bits, defaults to 2048. + * @param e the public exponent to use, defaults to 65537 (0x10001). + * @param [options] the options to use. + * prng a custom crypto-secure pseudo-random number generator to use, + * that must define "getBytesSync". + * algorithm the algorithm to use (default: 'PRIMEINC'). + * + * @return the state object to use to generate the key-pair. + */ +pki.rsa.createKeyPairGenerationState = function(bits, e, options) { + // TODO: migrate step-based prime generation code to forge.prime + + // set default bits + if(typeof(bits) === 'string') { + bits = parseInt(bits, 10); + } + bits = bits || 2048; + + // create prng with api that matches BigInteger secure random + options = options || {}; + var prng = options.prng || forge.random; + var rng = { + // x is an array to fill with bytes + nextBytes: function(x) { + var b = prng.getBytesSync(x.length); + for(var i = 0; i < x.length; ++i) { + x[i] = b.charCodeAt(i); + } + } + }; + + var algorithm = options.algorithm || 'PRIMEINC'; + + // create PRIMEINC algorithm state + var rval; + if(algorithm === 'PRIMEINC') { + rval = { + algorithm: algorithm, + state: 0, + bits: bits, + rng: rng, + eInt: e || 65537, + e: new BigInteger(null), + p: null, + q: null, + qBits: bits >> 1, + pBits: bits - (bits >> 1), + pqState: 0, + num: null, + keys: null + }; + rval.e.fromInt(rval.eInt); + } else { + throw new Error('Invalid key generation algorithm: ' + algorithm); + } + + return rval; +}; + +/** + * Attempts to runs the key-generation algorithm for at most n seconds + * (approximately) using the given state. When key-generation has completed, + * the keys will be stored in state.keys. + * + * To use this function to update a UI while generating a key or to prevent + * causing browser lockups/warnings, set "n" to a value other than 0. A + * simple pattern for generating a key and showing a progress indicator is: + * + * var state = pki.rsa.createKeyPairGenerationState(2048); + * var step = function() { + * // step key-generation, run algorithm for 100 ms, repeat + * if(!forge.pki.rsa.stepKeyPairGenerationState(state, 100)) { + * setTimeout(step, 1); + * } else { + * // key-generation complete + * // TODO: turn off progress indicator here + * // TODO: use the generated key-pair in "state.keys" + * } + * }; + * // TODO: turn on progress indicator here + * setTimeout(step, 0); + * + * @param state the state to use. + * @param n the maximum number of milliseconds to run the algorithm for, 0 + * to run the algorithm to completion. + * + * @return true if the key-generation completed, false if not. + */ +pki.rsa.stepKeyPairGenerationState = function(state, n) { + // set default algorithm if not set + if(!('algorithm' in state)) { + state.algorithm = 'PRIMEINC'; + } + + // TODO: migrate step-based prime generation code to forge.prime + // TODO: abstract as PRIMEINC algorithm + + // do key generation (based on Tom Wu's rsa.js, see jsbn.js license) + // with some minor optimizations and designed to run in steps + + // local state vars + var THIRTY = new BigInteger(null); + THIRTY.fromInt(30); + var deltaIdx = 0; + var op_or = function(x, y) {return x | y;}; + + // keep stepping until time limit is reached or done + var t1 = +new Date(); + var t2; + var total = 0; + while(state.keys === null && (n <= 0 || total < n)) { + // generate p or q + if(state.state === 0) { + /* Note: All primes are of the form: + + 30k+i, for i < 30 and gcd(30, i)=1, where there are 8 values for i + + When we generate a random number, we always align it at 30k + 1. Each + time the number is determined not to be prime we add to get to the + next 'i', eg: if the number was at 30k + 1 we add 6. */ + var bits = (state.p === null) ? state.pBits : state.qBits; + var bits1 = bits - 1; + + // get a random number + if(state.pqState === 0) { + state.num = new BigInteger(bits, state.rng); + // force MSB set + if(!state.num.testBit(bits1)) { + state.num.bitwiseTo( + BigInteger.ONE.shiftLeft(bits1), op_or, state.num); + } + // align number on 30k+1 boundary + state.num.dAddOffset(31 - state.num.mod(THIRTY).byteValue(), 0); + deltaIdx = 0; + + ++state.pqState; + } else if(state.pqState === 1) { + // try to make the number a prime + if(state.num.bitLength() > bits) { + // overflow, try again + state.pqState = 0; + // do primality test + } else if(state.num.isProbablePrime( + _getMillerRabinTests(state.num.bitLength()))) { + ++state.pqState; + } else { + // get next potential prime + state.num.dAddOffset(GCD_30_DELTA[deltaIdx++ % 8], 0); + } + } else if(state.pqState === 2) { + // ensure number is coprime with e + state.pqState = + (state.num.subtract(BigInteger.ONE).gcd(state.e) + .compareTo(BigInteger.ONE) === 0) ? 3 : 0; + } else if(state.pqState === 3) { + // store p or q + state.pqState = 0; + if(state.p === null) { + state.p = state.num; + } else { + state.q = state.num; + } + + // advance state if both p and q are ready + if(state.p !== null && state.q !== null) { + ++state.state; + } + state.num = null; + } + } else if(state.state === 1) { + // ensure p is larger than q (swap them if not) + if(state.p.compareTo(state.q) < 0) { + state.num = state.p; + state.p = state.q; + state.q = state.num; + } + ++state.state; + } else if(state.state === 2) { + // compute phi: (p - 1)(q - 1) (Euler's totient function) + state.p1 = state.p.subtract(BigInteger.ONE); + state.q1 = state.q.subtract(BigInteger.ONE); + state.phi = state.p1.multiply(state.q1); + ++state.state; + } else if(state.state === 3) { + // ensure e and phi are coprime + if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) === 0) { + // phi and e are coprime, advance + ++state.state; + } else { + // phi and e aren't coprime, so generate a new p and q + state.p = null; + state.q = null; + state.state = 0; + } + } else if(state.state === 4) { + // create n, ensure n is has the right number of bits + state.n = state.p.multiply(state.q); + + // ensure n is right number of bits + if(state.n.bitLength() === state.bits) { + // success, advance + ++state.state; + } else { + // failed, get new q + state.q = null; + state.state = 0; + } + } else if(state.state === 5) { + // set keys + var d = state.e.modInverse(state.phi); + state.keys = { + privateKey: pki.rsa.setPrivateKey( + state.n, state.e, d, state.p, state.q, + d.mod(state.p1), d.mod(state.q1), + state.q.modInverse(state.p)), + publicKey: pki.rsa.setPublicKey(state.n, state.e) + }; + } + + // update timing + t2 = +new Date(); + total += t2 - t1; + t1 = t2; + } + + return state.keys !== null; +}; + +/** + * Generates an RSA public-private key pair in a single call. + * + * To generate a key-pair in steps (to allow for progress updates and to + * prevent blocking or warnings in slow browsers) then use the key-pair + * generation state functions. + * + * To generate a key-pair asynchronously (either through web-workers, if + * available, or by breaking up the work on the main thread), pass a + * callback function. + * + * @param [bits] the size for the private key in bits, defaults to 2048. + * @param [e] the public exponent to use, defaults to 65537. + * @param [options] options for key-pair generation, if given then 'bits' + * and 'e' must *not* be given: + * bits the size for the private key in bits, (default: 2048). + * e the public exponent to use, (default: 65537 (0x10001)). + * workerScript the worker script URL. + * workers the number of web workers (if supported) to use, + * (default: 2). + * workLoad the size of the work load, ie: number of possible prime + * numbers for each web worker to check per work assignment, + * (default: 100). + * prng a custom crypto-secure pseudo-random number generator to use, + * that must define "getBytesSync". Disables use of native APIs. + * algorithm the algorithm to use (default: 'PRIMEINC'). + * @param [callback(err, keypair)] called once the operation completes. + * + * @return an object with privateKey and publicKey properties. + */ +pki.rsa.generateKeyPair = function(bits, e, options, callback) { + // (bits), (options), (callback) + if(arguments.length === 1) { + if(typeof bits === 'object') { + options = bits; + bits = undefined; + } else if(typeof bits === 'function') { + callback = bits; + bits = undefined; + } + } else if(arguments.length === 2) { + // (bits, e), (bits, options), (bits, callback), (options, callback) + if(typeof bits === 'number') { + if(typeof e === 'function') { + callback = e; + e = undefined; + } else if(typeof e !== 'number') { + options = e; + e = undefined; + } + } else { + options = bits; + callback = e; + bits = undefined; + e = undefined; + } + } else if(arguments.length === 3) { + // (bits, e, options), (bits, e, callback), (bits, options, callback) + if(typeof e === 'number') { + if(typeof options === 'function') { + callback = options; + options = undefined; + } + } else { + callback = options; + options = e; + e = undefined; + } + } + options = options || {}; + if(bits === undefined) { + bits = options.bits || 2048; + } + if(e === undefined) { + e = options.e || 0x10001; + } + + // use native code if permitted, available, and parameters are acceptable + if(!forge.options.usePureJavaScript && !options.prng && + bits >= 256 && bits <= 16384 && (e === 0x10001 || e === 3)) { + if(callback) { + // try native async + if(_detectNodeCrypto('generateKeyPair')) { + return _crypto.generateKeyPair('rsa', { + modulusLength: bits, + publicExponent: e, + publicKeyEncoding: { + type: 'spki', + format: 'pem' + }, + privateKeyEncoding: { + type: 'pkcs8', + format: 'pem' + } + }, function(err, pub, priv) { + if(err) { + return callback(err); + } + callback(null, { + privateKey: pki.privateKeyFromPem(priv), + publicKey: pki.publicKeyFromPem(pub) + }); + }); + } + if(_detectSubtleCrypto('generateKey') && + _detectSubtleCrypto('exportKey')) { + // use standard native generateKey + return util.globalScope.crypto.subtle.generateKey({ + name: 'RSASSA-PKCS1-v1_5', + modulusLength: bits, + publicExponent: _intToUint8Array(e), + hash: {name: 'SHA-256'} + }, true /* key can be exported*/, ['sign', 'verify']) + .then(function(pair) { + return util.globalScope.crypto.subtle.exportKey( + 'pkcs8', pair.privateKey); + // avoiding catch(function(err) {...}) to support IE <= 8 + }).then(undefined, function(err) { + callback(err); + }).then(function(pkcs8) { + if(pkcs8) { + var privateKey = pki.privateKeyFromAsn1( + asn1.fromDer(forge.util.createBuffer(pkcs8))); + callback(null, { + privateKey: privateKey, + publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e) + }); + } + }); + } + if(_detectSubtleMsCrypto('generateKey') && + _detectSubtleMsCrypto('exportKey')) { + var genOp = util.globalScope.msCrypto.subtle.generateKey({ + name: 'RSASSA-PKCS1-v1_5', + modulusLength: bits, + publicExponent: _intToUint8Array(e), + hash: {name: 'SHA-256'} + }, true /* key can be exported*/, ['sign', 'verify']); + genOp.oncomplete = function(e) { + var pair = e.target.result; + var exportOp = util.globalScope.msCrypto.subtle.exportKey( + 'pkcs8', pair.privateKey); + exportOp.oncomplete = function(e) { + var pkcs8 = e.target.result; + var privateKey = pki.privateKeyFromAsn1( + asn1.fromDer(forge.util.createBuffer(pkcs8))); + callback(null, { + privateKey: privateKey, + publicKey: pki.setRsaPublicKey(privateKey.n, privateKey.e) + }); + }; + exportOp.onerror = function(err) { + callback(err); + }; + }; + genOp.onerror = function(err) { + callback(err); + }; + return; + } + } else { + // try native sync + if(_detectNodeCrypto('generateKeyPairSync')) { + var keypair = _crypto.generateKeyPairSync('rsa', { + modulusLength: bits, + publicExponent: e, + publicKeyEncoding: { + type: 'spki', + format: 'pem' + }, + privateKeyEncoding: { + type: 'pkcs8', + format: 'pem' + } + }); + return { + privateKey: pki.privateKeyFromPem(keypair.privateKey), + publicKey: pki.publicKeyFromPem(keypair.publicKey) + }; + } + } + } + + // use JavaScript implementation + var state = pki.rsa.createKeyPairGenerationState(bits, e, options); + if(!callback) { + pki.rsa.stepKeyPairGenerationState(state, 0); + return state.keys; + } + _generateKeyPair(state, options, callback); +}; + +/** + * Sets an RSA public key from BigIntegers modulus and exponent. + * + * @param n the modulus. + * @param e the exponent. + * + * @return the public key. + */ +pki.setRsaPublicKey = pki.rsa.setPublicKey = function(n, e) { + var key = { + n: n, + e: e + }; + + /** + * Encrypts the given data with this public key. Newer applications + * should use the 'RSA-OAEP' decryption scheme, 'RSAES-PKCS1-V1_5' is for + * legacy applications. + * + * @param data the byte string to encrypt. + * @param scheme the encryption scheme to use: + * 'RSAES-PKCS1-V1_5' (default), + * 'RSA-OAEP', + * 'RAW', 'NONE', or null to perform raw RSA encryption, + * an object with an 'encode' property set to a function + * with the signature 'function(data, key)' that returns + * a binary-encoded string representing the encoded data. + * @param schemeOptions any scheme-specific options. + * + * @return the encrypted byte string. + */ + key.encrypt = function(data, scheme, schemeOptions) { + if(typeof scheme === 'string') { + scheme = scheme.toUpperCase(); + } else if(scheme === undefined) { + scheme = 'RSAES-PKCS1-V1_5'; + } + + if(scheme === 'RSAES-PKCS1-V1_5') { + scheme = { + encode: function(m, key, pub) { + return _encodePkcs1_v1_5(m, key, 0x02).getBytes(); + } + }; + } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') { + scheme = { + encode: function(m, key) { + return forge.pkcs1.encode_rsa_oaep(key, m, schemeOptions); + } + }; + } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) { + scheme = {encode: function(e) {return e;}}; + } else if(typeof scheme === 'string') { + throw new Error('Unsupported encryption scheme: "' + scheme + '".'); + } + + // do scheme-based encoding then rsa encryption + var e = scheme.encode(data, key, true); + return pki.rsa.encrypt(e, key, true); + }; + + /** + * Verifies the given signature against the given digest. + * + * PKCS#1 supports multiple (currently two) signature schemes: + * RSASSA-PKCS1-V1_5 and RSASSA-PSS. + * + * By default this implementation uses the "old scheme", i.e. + * RSASSA-PKCS1-V1_5, in which case once RSA-decrypted, the + * signature is an OCTET STRING that holds a DigestInfo. + * + * DigestInfo ::= SEQUENCE { + * digestAlgorithm DigestAlgorithmIdentifier, + * digest Digest + * } + * DigestAlgorithmIdentifier ::= AlgorithmIdentifier + * Digest ::= OCTET STRING + * + * To perform PSS signature verification, provide an instance + * of Forge PSS object as the scheme parameter. + * + * @param digest the message digest hash to compare against the signature, + * as a binary-encoded string. + * @param signature the signature to verify, as a binary-encoded string. + * @param scheme signature verification scheme to use: + * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5, + * a Forge PSS object for RSASSA-PSS, + * 'NONE' or null for none, DigestInfo will not be expected, but + * PKCS#1 v1.5 padding will still be used. + * + * @return true if the signature was verified, false if not. + */ + key.verify = function(digest, signature, scheme) { + if(typeof scheme === 'string') { + scheme = scheme.toUpperCase(); + } else if(scheme === undefined) { + scheme = 'RSASSA-PKCS1-V1_5'; + } + + if(scheme === 'RSASSA-PKCS1-V1_5') { + scheme = { + verify: function(digest, d) { + // remove padding + d = _decodePkcs1_v1_5(d, key, true); + // d is ASN.1 BER-encoded DigestInfo + var obj = asn1.fromDer(d); + // compare the given digest to the decrypted one + return digest === obj.value[1].value; + } + }; + } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) { + scheme = { + verify: function(digest, d) { + // remove padding + d = _decodePkcs1_v1_5(d, key, true); + return digest === d; + } + }; + } + + // do rsa decryption w/o any decoding, then verify -- which does decoding + var d = pki.rsa.decrypt(signature, key, true, false); + return scheme.verify(digest, d, key.n.bitLength()); + }; + + return key; +}; + +/** + * Sets an RSA private key from BigIntegers modulus, exponent, primes, + * prime exponents, and modular multiplicative inverse. + * + * @param n the modulus. + * @param e the public exponent. + * @param d the private exponent ((inverse of e) mod n). + * @param p the first prime. + * @param q the second prime. + * @param dP exponent1 (d mod (p-1)). + * @param dQ exponent2 (d mod (q-1)). + * @param qInv ((inverse of q) mod p) + * + * @return the private key. + */ +pki.setRsaPrivateKey = pki.rsa.setPrivateKey = function( + n, e, d, p, q, dP, dQ, qInv) { + var key = { + n: n, + e: e, + d: d, + p: p, + q: q, + dP: dP, + dQ: dQ, + qInv: qInv + }; + + /** + * Decrypts the given data with this private key. The decryption scheme + * must match the one used to encrypt the data. + * + * @param data the byte string to decrypt. + * @param scheme the decryption scheme to use: + * 'RSAES-PKCS1-V1_5' (default), + * 'RSA-OAEP', + * 'RAW', 'NONE', or null to perform raw RSA decryption. + * @param schemeOptions any scheme-specific options. + * + * @return the decrypted byte string. + */ + key.decrypt = function(data, scheme, schemeOptions) { + if(typeof scheme === 'string') { + scheme = scheme.toUpperCase(); + } else if(scheme === undefined) { + scheme = 'RSAES-PKCS1-V1_5'; + } + + // do rsa decryption w/o any decoding + var d = pki.rsa.decrypt(data, key, false, false); + + if(scheme === 'RSAES-PKCS1-V1_5') { + scheme = {decode: _decodePkcs1_v1_5}; + } else if(scheme === 'RSA-OAEP' || scheme === 'RSAES-OAEP') { + scheme = { + decode: function(d, key) { + return forge.pkcs1.decode_rsa_oaep(key, d, schemeOptions); + } + }; + } else if(['RAW', 'NONE', 'NULL', null].indexOf(scheme) !== -1) { + scheme = {decode: function(d) {return d;}}; + } else { + throw new Error('Unsupported encryption scheme: "' + scheme + '".'); + } + + // decode according to scheme + return scheme.decode(d, key, false); + }; + + /** + * Signs the given digest, producing a signature. + * + * PKCS#1 supports multiple (currently two) signature schemes: + * RSASSA-PKCS1-V1_5 and RSASSA-PSS. + * + * By default this implementation uses the "old scheme", i.e. + * RSASSA-PKCS1-V1_5. In order to generate a PSS signature, provide + * an instance of Forge PSS object as the scheme parameter. + * + * @param md the message digest object with the hash to sign. + * @param scheme the signature scheme to use: + * 'RSASSA-PKCS1-V1_5' or undefined for RSASSA PKCS#1 v1.5, + * a Forge PSS object for RSASSA-PSS, + * 'NONE' or null for none, DigestInfo will not be used but + * PKCS#1 v1.5 padding will still be used. + * + * @return the signature as a byte string. + */ + key.sign = function(md, scheme) { + /* Note: The internal implementation of RSA operations is being + transitioned away from a PKCS#1 v1.5 hard-coded scheme. Some legacy + code like the use of an encoding block identifier 'bt' will eventually + be removed. */ + + // private key operation + var bt = false; + + if(typeof scheme === 'string') { + scheme = scheme.toUpperCase(); + } + + if(scheme === undefined || scheme === 'RSASSA-PKCS1-V1_5') { + scheme = {encode: emsaPkcs1v15encode}; + bt = 0x01; + } else if(scheme === 'NONE' || scheme === 'NULL' || scheme === null) { + scheme = {encode: function() {return md;}}; + bt = 0x01; + } + + // encode and then encrypt + var d = scheme.encode(md, key.n.bitLength()); + return pki.rsa.encrypt(d, key, bt); + }; + + return key; +}; + +/** + * Wraps an RSAPrivateKey ASN.1 object in an ASN.1 PrivateKeyInfo object. + * + * @param rsaKey the ASN.1 RSAPrivateKey. + * + * @return the ASN.1 PrivateKeyInfo. + */ +pki.wrapRsaPrivateKey = function(rsaKey) { + // PrivateKeyInfo + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // version (0) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(0).getBytes()), + // privateKeyAlgorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(pki.oids.rsaEncryption).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ]), + // PrivateKey + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, + asn1.toDer(rsaKey).getBytes()) + ]); +}; + +/** + * Converts a private key from an ASN.1 object. + * + * @param obj the ASN.1 representation of a PrivateKeyInfo containing an + * RSAPrivateKey or an RSAPrivateKey. + * + * @return the private key. + */ +pki.privateKeyFromAsn1 = function(obj) { + // get PrivateKeyInfo + var capture = {}; + var errors = []; + if(asn1.validate(obj, privateKeyValidator, capture, errors)) { + obj = asn1.fromDer(forge.util.createBuffer(capture.privateKey)); + } + + // get RSAPrivateKey + capture = {}; + errors = []; + if(!asn1.validate(obj, rsaPrivateKeyValidator, capture, errors)) { + var error = new Error('Cannot read private key. ' + + 'ASN.1 object does not contain an RSAPrivateKey.'); + error.errors = errors; + throw error; + } + + // Note: Version is currently ignored. + // capture.privateKeyVersion + // FIXME: inefficient, get a BigInteger that uses byte strings + var n, e, d, p, q, dP, dQ, qInv; + n = forge.util.createBuffer(capture.privateKeyModulus).toHex(); + e = forge.util.createBuffer(capture.privateKeyPublicExponent).toHex(); + d = forge.util.createBuffer(capture.privateKeyPrivateExponent).toHex(); + p = forge.util.createBuffer(capture.privateKeyPrime1).toHex(); + q = forge.util.createBuffer(capture.privateKeyPrime2).toHex(); + dP = forge.util.createBuffer(capture.privateKeyExponent1).toHex(); + dQ = forge.util.createBuffer(capture.privateKeyExponent2).toHex(); + qInv = forge.util.createBuffer(capture.privateKeyCoefficient).toHex(); + + // set private key + return pki.setRsaPrivateKey( + new BigInteger(n, 16), + new BigInteger(e, 16), + new BigInteger(d, 16), + new BigInteger(p, 16), + new BigInteger(q, 16), + new BigInteger(dP, 16), + new BigInteger(dQ, 16), + new BigInteger(qInv, 16)); +}; + +/** + * Converts a private key to an ASN.1 RSAPrivateKey. + * + * @param key the private key. + * + * @return the ASN.1 representation of an RSAPrivateKey. + */ +pki.privateKeyToAsn1 = pki.privateKeyToRSAPrivateKey = function(key) { + // RSAPrivateKey + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // version (0 = only 2 primes, 1 multiple primes) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(0).getBytes()), + // modulus (n) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + _bnToBytes(key.n)), + // publicExponent (e) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + _bnToBytes(key.e)), + // privateExponent (d) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + _bnToBytes(key.d)), + // privateKeyPrime1 (p) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + _bnToBytes(key.p)), + // privateKeyPrime2 (q) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + _bnToBytes(key.q)), + // privateKeyExponent1 (dP) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + _bnToBytes(key.dP)), + // privateKeyExponent2 (dQ) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + _bnToBytes(key.dQ)), + // coefficient (qInv) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + _bnToBytes(key.qInv)) + ]); +}; + +/** + * Converts a public key from an ASN.1 SubjectPublicKeyInfo or RSAPublicKey. + * + * @param obj the asn1 representation of a SubjectPublicKeyInfo or RSAPublicKey. + * + * @return the public key. + */ +pki.publicKeyFromAsn1 = function(obj) { + // get SubjectPublicKeyInfo + var capture = {}; + var errors = []; + if(asn1.validate(obj, publicKeyValidator, capture, errors)) { + // get oid + var oid = asn1.derToOid(capture.publicKeyOid); + if(oid !== pki.oids.rsaEncryption) { + var error = new Error('Cannot read public key. Unknown OID.'); + error.oid = oid; + throw error; + } + obj = capture.rsaPublicKey; + } + + // get RSA params + errors = []; + if(!asn1.validate(obj, rsaPublicKeyValidator, capture, errors)) { + var error = new Error('Cannot read public key. ' + + 'ASN.1 object does not contain an RSAPublicKey.'); + error.errors = errors; + throw error; + } + + // FIXME: inefficient, get a BigInteger that uses byte strings + var n = forge.util.createBuffer(capture.publicKeyModulus).toHex(); + var e = forge.util.createBuffer(capture.publicKeyExponent).toHex(); + + // set public key + return pki.setRsaPublicKey( + new BigInteger(n, 16), + new BigInteger(e, 16)); +}; + +/** + * Converts a public key to an ASN.1 SubjectPublicKeyInfo. + * + * @param key the public key. + * + * @return the asn1 representation of a SubjectPublicKeyInfo. + */ +pki.publicKeyToAsn1 = pki.publicKeyToSubjectPublicKeyInfo = function(key) { + // SubjectPublicKeyInfo + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // AlgorithmIdentifier + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(pki.oids.rsaEncryption).getBytes()), + // parameters (null) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ]), + // subjectPublicKey + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, [ + pki.publicKeyToRSAPublicKey(key) + ]) + ]); +}; + +/** + * Converts a public key to an ASN.1 RSAPublicKey. + * + * @param key the public key. + * + * @return the asn1 representation of a RSAPublicKey. + */ +pki.publicKeyToRSAPublicKey = function(key) { + // RSAPublicKey + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // modulus (n) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + _bnToBytes(key.n)), + // publicExponent (e) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + _bnToBytes(key.e)) + ]); +}; + +/** + * Encodes a message using PKCS#1 v1.5 padding. + * + * @param m the message to encode. + * @param key the RSA key to use. + * @param bt the block type to use, i.e. either 0x01 (for signing) or 0x02 + * (for encryption). + * + * @return the padded byte buffer. + */ +function _encodePkcs1_v1_5(m, key, bt) { + var eb = forge.util.createBuffer(); + + // get the length of the modulus in bytes + var k = Math.ceil(key.n.bitLength() / 8); + + /* use PKCS#1 v1.5 padding */ + if(m.length > (k - 11)) { + var error = new Error('Message is too long for PKCS#1 v1.5 padding.'); + error.length = m.length; + error.max = k - 11; + throw error; + } + + /* A block type BT, a padding string PS, and the data D shall be + formatted into an octet string EB, the encryption block: + + EB = 00 || BT || PS || 00 || D + + The block type BT shall be a single octet indicating the structure of + the encryption block. For this version of the document it shall have + value 00, 01, or 02. For a private-key operation, the block type + shall be 00 or 01. For a public-key operation, it shall be 02. + + The padding string PS shall consist of k-3-||D|| octets. For block + type 00, the octets shall have value 00; for block type 01, they + shall have value FF; and for block type 02, they shall be + pseudorandomly generated and nonzero. This makes the length of the + encryption block EB equal to k. */ + + // build the encryption block + eb.putByte(0x00); + eb.putByte(bt); + + // create the padding + var padNum = k - 3 - m.length; + var padByte; + // private key op + if(bt === 0x00 || bt === 0x01) { + padByte = (bt === 0x00) ? 0x00 : 0xFF; + for(var i = 0; i < padNum; ++i) { + eb.putByte(padByte); + } + } else { + // public key op + // pad with random non-zero values + while(padNum > 0) { + var numZeros = 0; + var padBytes = forge.random.getBytes(padNum); + for(var i = 0; i < padNum; ++i) { + padByte = padBytes.charCodeAt(i); + if(padByte === 0) { + ++numZeros; + } else { + eb.putByte(padByte); + } + } + padNum = numZeros; + } + } + + // zero followed by message + eb.putByte(0x00); + eb.putBytes(m); + + return eb; +} + +/** + * Decodes a message using PKCS#1 v1.5 padding. + * + * @param em the message to decode. + * @param key the RSA key to use. + * @param pub true if the key is a public key, false if it is private. + * @param ml the message length, if specified. + * + * @return the decoded bytes. + */ +function _decodePkcs1_v1_5(em, key, pub, ml) { + // get the length of the modulus in bytes + var k = Math.ceil(key.n.bitLength() / 8); + + /* It is an error if any of the following conditions occurs: + + 1. The encryption block EB cannot be parsed unambiguously. + 2. The padding string PS consists of fewer than eight octets + or is inconsisent with the block type BT. + 3. The decryption process is a public-key operation and the block + type BT is not 00 or 01, or the decryption process is a + private-key operation and the block type is not 02. + */ + + // parse the encryption block + var eb = forge.util.createBuffer(em); + var first = eb.getByte(); + var bt = eb.getByte(); + if(first !== 0x00 || + (pub && bt !== 0x00 && bt !== 0x01) || + (!pub && bt != 0x02) || + (pub && bt === 0x00 && typeof(ml) === 'undefined')) { + throw new Error('Encryption block is invalid.'); + } + + var padNum = 0; + if(bt === 0x00) { + // check all padding bytes for 0x00 + padNum = k - 3 - ml; + for(var i = 0; i < padNum; ++i) { + if(eb.getByte() !== 0x00) { + throw new Error('Encryption block is invalid.'); + } + } + } else if(bt === 0x01) { + // find the first byte that isn't 0xFF, should be after all padding + padNum = 0; + while(eb.length() > 1) { + if(eb.getByte() !== 0xFF) { + --eb.read; + break; + } + ++padNum; + } + } else if(bt === 0x02) { + // look for 0x00 byte + padNum = 0; + while(eb.length() > 1) { + if(eb.getByte() === 0x00) { + --eb.read; + break; + } + ++padNum; + } + } + + // zero must be 0x00 and padNum must be (k - 3 - message length) + var zero = eb.getByte(); + if(zero !== 0x00 || padNum !== (k - 3 - eb.length())) { + throw new Error('Encryption block is invalid.'); + } + + return eb.getBytes(); +} + +/** + * Runs the key-generation algorithm asynchronously, either in the background + * via Web Workers, or using the main thread and setImmediate. + * + * @param state the key-pair generation state. + * @param [options] options for key-pair generation: + * workerScript the worker script URL. + * workers the number of web workers (if supported) to use, + * (default: 2, -1 to use estimated cores minus one). + * workLoad the size of the work load, ie: number of possible prime + * numbers for each web worker to check per work assignment, + * (default: 100). + * @param callback(err, keypair) called once the operation completes. + */ +function _generateKeyPair(state, options, callback) { + if(typeof options === 'function') { + callback = options; + options = {}; + } + options = options || {}; + + var opts = { + algorithm: { + name: options.algorithm || 'PRIMEINC', + options: { + workers: options.workers || 2, + workLoad: options.workLoad || 100, + workerScript: options.workerScript + } + } + }; + if('prng' in options) { + opts.prng = options.prng; + } + + generate(); + + function generate() { + // find p and then q (done in series to simplify) + getPrime(state.pBits, function(err, num) { + if(err) { + return callback(err); + } + state.p = num; + if(state.q !== null) { + return finish(err, state.q); + } + getPrime(state.qBits, finish); + }); + } + + function getPrime(bits, callback) { + forge.prime.generateProbablePrime(bits, opts, callback); + } + + function finish(err, num) { + if(err) { + return callback(err); + } + + // set q + state.q = num; + + // ensure p is larger than q (swap them if not) + if(state.p.compareTo(state.q) < 0) { + var tmp = state.p; + state.p = state.q; + state.q = tmp; + } + + // ensure p is coprime with e + if(state.p.subtract(BigInteger.ONE).gcd(state.e) + .compareTo(BigInteger.ONE) !== 0) { + state.p = null; + generate(); + return; + } + + // ensure q is coprime with e + if(state.q.subtract(BigInteger.ONE).gcd(state.e) + .compareTo(BigInteger.ONE) !== 0) { + state.q = null; + getPrime(state.qBits, finish); + return; + } + + // compute phi: (p - 1)(q - 1) (Euler's totient function) + state.p1 = state.p.subtract(BigInteger.ONE); + state.q1 = state.q.subtract(BigInteger.ONE); + state.phi = state.p1.multiply(state.q1); + + // ensure e and phi are coprime + if(state.phi.gcd(state.e).compareTo(BigInteger.ONE) !== 0) { + // phi and e aren't coprime, so generate a new p and q + state.p = state.q = null; + generate(); + return; + } + + // create n, ensure n is has the right number of bits + state.n = state.p.multiply(state.q); + if(state.n.bitLength() !== state.bits) { + // failed, get new q + state.q = null; + getPrime(state.qBits, finish); + return; + } + + // set keys + var d = state.e.modInverse(state.phi); + state.keys = { + privateKey: pki.rsa.setPrivateKey( + state.n, state.e, d, state.p, state.q, + d.mod(state.p1), d.mod(state.q1), + state.q.modInverse(state.p)), + publicKey: pki.rsa.setPublicKey(state.n, state.e) + }; + + callback(null, state.keys); + } +} + +/** + * Converts a positive BigInteger into 2's-complement big-endian bytes. + * + * @param b the big integer to convert. + * + * @return the bytes. + */ +function _bnToBytes(b) { + // prepend 0x00 if first byte >= 0x80 + var hex = b.toString(16); + if(hex[0] >= '8') { + hex = '00' + hex; + } + var bytes = forge.util.hexToBytes(hex); + + // ensure integer is minimally-encoded + if(bytes.length > 1 && + // leading 0x00 for positive integer + ((bytes.charCodeAt(0) === 0 && + (bytes.charCodeAt(1) & 0x80) === 0) || + // leading 0xFF for negative integer + (bytes.charCodeAt(0) === 0xFF && + (bytes.charCodeAt(1) & 0x80) === 0x80))) { + return bytes.substr(1); + } + return bytes; +} + +/** + * Returns the required number of Miller-Rabin tests to generate a + * prime with an error probability of (1/2)^80. + * + * See Handbook of Applied Cryptography Chapter 4, Table 4.4. + * + * @param bits the bit size. + * + * @return the required number of iterations. + */ +function _getMillerRabinTests(bits) { + if(bits <= 100) return 27; + if(bits <= 150) return 18; + if(bits <= 200) return 15; + if(bits <= 250) return 12; + if(bits <= 300) return 9; + if(bits <= 350) return 8; + if(bits <= 400) return 7; + if(bits <= 500) return 6; + if(bits <= 600) return 5; + if(bits <= 800) return 4; + if(bits <= 1250) return 3; + return 2; +} + +/** + * Performs feature detection on the Node crypto interface. + * + * @param fn the feature (function) to detect. + * + * @return true if detected, false if not. + */ +function _detectNodeCrypto(fn) { + return forge.util.isNodejs && typeof _crypto[fn] === 'function'; +} + +/** + * Performs feature detection on the SubtleCrypto interface. + * + * @param fn the feature (function) to detect. + * + * @return true if detected, false if not. + */ +function _detectSubtleCrypto(fn) { + return (typeof util.globalScope !== 'undefined' && + typeof util.globalScope.crypto === 'object' && + typeof util.globalScope.crypto.subtle === 'object' && + typeof util.globalScope.crypto.subtle[fn] === 'function'); +} + +/** + * Performs feature detection on the deprecated Microsoft Internet Explorer + * outdated SubtleCrypto interface. This function should only be used after + * checking for the modern, standard SubtleCrypto interface. + * + * @param fn the feature (function) to detect. + * + * @return true if detected, false if not. + */ +function _detectSubtleMsCrypto(fn) { + return (typeof util.globalScope !== 'undefined' && + typeof util.globalScope.msCrypto === 'object' && + typeof util.globalScope.msCrypto.subtle === 'object' && + typeof util.globalScope.msCrypto.subtle[fn] === 'function'); +} + +function _intToUint8Array(x) { + var bytes = forge.util.hexToBytes(x.toString(16)); + var buffer = new Uint8Array(bytes.length); + for(var i = 0; i < bytes.length; ++i) { + buffer[i] = bytes.charCodeAt(i); + } + return buffer; +} + +function _privateKeyFromJwk(jwk) { + if(jwk.kty !== 'RSA') { + throw new Error( + 'Unsupported key algorithm "' + jwk.kty + '"; algorithm must be "RSA".'); + } + return pki.setRsaPrivateKey( + _base64ToBigInt(jwk.n), + _base64ToBigInt(jwk.e), + _base64ToBigInt(jwk.d), + _base64ToBigInt(jwk.p), + _base64ToBigInt(jwk.q), + _base64ToBigInt(jwk.dp), + _base64ToBigInt(jwk.dq), + _base64ToBigInt(jwk.qi)); +} + +function _publicKeyFromJwk(jwk) { + if(jwk.kty !== 'RSA') { + throw new Error('Key algorithm must be "RSA".'); + } + return pki.setRsaPublicKey( + _base64ToBigInt(jwk.n), + _base64ToBigInt(jwk.e)); +} + +function _base64ToBigInt(b64) { + return new BigInteger(forge.util.bytesToHex(forge.util.decode64(b64)), 16); +} diff --git a/node_modules/node-forge/lib/sha1.js b/node_modules/node-forge/lib/sha1.js new file mode 100644 index 0000000..5f84eb6 --- /dev/null +++ b/node_modules/node-forge/lib/sha1.js @@ -0,0 +1,319 @@ +/** + * Secure Hash Algorithm with 160-bit digest (SHA-1) implementation. + * + * @author Dave Longley + * + * Copyright (c) 2010-2015 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./md'); +require('./util'); + +var sha1 = module.exports = forge.sha1 = forge.sha1 || {}; +forge.md.sha1 = forge.md.algorithms.sha1 = sha1; + +/** + * Creates a SHA-1 message digest object. + * + * @return a message digest object. + */ +sha1.create = function() { + // do initialization as necessary + if(!_initialized) { + _init(); + } + + // SHA-1 state contains five 32-bit integers + var _state = null; + + // input buffer + var _input = forge.util.createBuffer(); + + // used for word storage + var _w = new Array(80); + + // message digest object + var md = { + algorithm: 'sha1', + blockLength: 64, + digestLength: 20, + // 56-bit length of message so far (does not including padding) + messageLength: 0, + // true message length + fullMessageLength: null, + // size of message length in bytes + messageLengthSize: 8 + }; + + /** + * Starts the digest. + * + * @return this digest object. + */ + md.start = function() { + // up to 56-bit message length for convenience + md.messageLength = 0; + + // full message length (set md.messageLength64 for backwards-compatibility) + md.fullMessageLength = md.messageLength64 = []; + var int32s = md.messageLengthSize / 4; + for(var i = 0; i < int32s; ++i) { + md.fullMessageLength.push(0); + } + _input = forge.util.createBuffer(); + _state = { + h0: 0x67452301, + h1: 0xEFCDAB89, + h2: 0x98BADCFE, + h3: 0x10325476, + h4: 0xC3D2E1F0 + }; + return md; + }; + // start digest automatically for first time + md.start(); + + /** + * Updates the digest with the given message input. The given input can + * treated as raw input (no encoding will be applied) or an encoding of + * 'utf8' maybe given to encode the input using UTF-8. + * + * @param msg the message input to update with. + * @param encoding the encoding to use (default: 'raw', other: 'utf8'). + * + * @return this digest object. + */ + md.update = function(msg, encoding) { + if(encoding === 'utf8') { + msg = forge.util.encodeUtf8(msg); + } + + // update message length + var len = msg.length; + md.messageLength += len; + len = [(len / 0x100000000) >>> 0, len >>> 0]; + for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { + md.fullMessageLength[i] += len[1]; + len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0); + md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; + len[0] = ((len[1] / 0x100000000) >>> 0); + } + + // add bytes to input buffer + _input.putBytes(msg); + + // process bytes + _update(_state, _w, _input); + + // compact input buffer every 2K or if empty + if(_input.read > 2048 || _input.length() === 0) { + _input.compact(); + } + + return md; + }; + + /** + * Produces the digest. + * + * @return a byte buffer containing the digest value. + */ + md.digest = function() { + /* Note: Here we copy the remaining bytes in the input buffer and + add the appropriate SHA-1 padding. Then we do the final update + on a copy of the state so that if the user wants to get + intermediate digests they can do so. */ + + /* Determine the number of bytes that must be added to the message + to ensure its length is congruent to 448 mod 512. In other words, + the data to be digested must be a multiple of 512 bits (or 128 bytes). + This data includes the message, some padding, and the length of the + message. Since the length of the message will be encoded as 8 bytes (64 + bits), that means that the last segment of the data must have 56 bytes + (448 bits) of message and padding. Therefore, the length of the message + plus the padding must be congruent to 448 mod 512 because + 512 - 128 = 448. + + In order to fill up the message length it must be filled with + padding that begins with 1 bit followed by all 0 bits. Padding + must *always* be present, so if the message length is already + congruent to 448 mod 512, then 512 padding bits must be added. */ + + var finalBlock = forge.util.createBuffer(); + finalBlock.putBytes(_input.bytes()); + + // compute remaining size to be digested (include message length size) + var remaining = ( + md.fullMessageLength[md.fullMessageLength.length - 1] + + md.messageLengthSize); + + // add padding for overflow blockSize - overflow + // _padding starts with 1 byte with first bit is set (byte value 128), then + // there may be up to (blockSize - 1) other pad bytes + var overflow = remaining & (md.blockLength - 1); + finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); + + // serialize message length in bits in big-endian order; since length + // is stored in bytes we multiply by 8 and add carry from next int + var next, carry; + var bits = md.fullMessageLength[0] * 8; + for(var i = 0; i < md.fullMessageLength.length - 1; ++i) { + next = md.fullMessageLength[i + 1] * 8; + carry = (next / 0x100000000) >>> 0; + bits += carry; + finalBlock.putInt32(bits >>> 0); + bits = next >>> 0; + } + finalBlock.putInt32(bits); + + var s2 = { + h0: _state.h0, + h1: _state.h1, + h2: _state.h2, + h3: _state.h3, + h4: _state.h4 + }; + _update(s2, _w, finalBlock); + var rval = forge.util.createBuffer(); + rval.putInt32(s2.h0); + rval.putInt32(s2.h1); + rval.putInt32(s2.h2); + rval.putInt32(s2.h3); + rval.putInt32(s2.h4); + return rval; + }; + + return md; +}; + +// sha-1 padding bytes not initialized yet +var _padding = null; +var _initialized = false; + +/** + * Initializes the constant tables. + */ +function _init() { + // create padding + _padding = String.fromCharCode(128); + _padding += forge.util.fillString(String.fromCharCode(0x00), 64); + + // now initialized + _initialized = true; +} + +/** + * Updates a SHA-1 state with the given byte buffer. + * + * @param s the SHA-1 state to update. + * @param w the array to use to store words. + * @param bytes the byte buffer to update with. + */ +function _update(s, w, bytes) { + // consume 512 bit (64 byte) chunks + var t, a, b, c, d, e, f, i; + var len = bytes.length(); + while(len >= 64) { + // the w array will be populated with sixteen 32-bit big-endian words + // and then extended into 80 32-bit words according to SHA-1 algorithm + // and for 32-79 using Max Locktyukhin's optimization + + // initialize hash value for this chunk + a = s.h0; + b = s.h1; + c = s.h2; + d = s.h3; + e = s.h4; + + // round 1 + for(i = 0; i < 16; ++i) { + t = bytes.getInt32(); + w[i] = t; + f = d ^ (b & (c ^ d)); + t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t; + e = d; + d = c; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + c = ((b << 30) | (b >>> 2)) >>> 0; + b = a; + a = t; + } + for(; i < 20; ++i) { + t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]); + t = (t << 1) | (t >>> 31); + w[i] = t; + f = d ^ (b & (c ^ d)); + t = ((a << 5) | (a >>> 27)) + f + e + 0x5A827999 + t; + e = d; + d = c; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + c = ((b << 30) | (b >>> 2)) >>> 0; + b = a; + a = t; + } + // round 2 + for(; i < 32; ++i) { + t = (w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16]); + t = (t << 1) | (t >>> 31); + w[i] = t; + f = b ^ c ^ d; + t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t; + e = d; + d = c; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + c = ((b << 30) | (b >>> 2)) >>> 0; + b = a; + a = t; + } + for(; i < 40; ++i) { + t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]); + t = (t << 2) | (t >>> 30); + w[i] = t; + f = b ^ c ^ d; + t = ((a << 5) | (a >>> 27)) + f + e + 0x6ED9EBA1 + t; + e = d; + d = c; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + c = ((b << 30) | (b >>> 2)) >>> 0; + b = a; + a = t; + } + // round 3 + for(; i < 60; ++i) { + t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]); + t = (t << 2) | (t >>> 30); + w[i] = t; + f = (b & c) | (d & (b ^ c)); + t = ((a << 5) | (a >>> 27)) + f + e + 0x8F1BBCDC + t; + e = d; + d = c; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + c = ((b << 30) | (b >>> 2)) >>> 0; + b = a; + a = t; + } + // round 4 + for(; i < 80; ++i) { + t = (w[i - 6] ^ w[i - 16] ^ w[i - 28] ^ w[i - 32]); + t = (t << 2) | (t >>> 30); + w[i] = t; + f = b ^ c ^ d; + t = ((a << 5) | (a >>> 27)) + f + e + 0xCA62C1D6 + t; + e = d; + d = c; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + c = ((b << 30) | (b >>> 2)) >>> 0; + b = a; + a = t; + } + + // update hash state + s.h0 = (s.h0 + a) | 0; + s.h1 = (s.h1 + b) | 0; + s.h2 = (s.h2 + c) | 0; + s.h3 = (s.h3 + d) | 0; + s.h4 = (s.h4 + e) | 0; + + len -= 64; + } +} diff --git a/node_modules/node-forge/lib/sha256.js b/node_modules/node-forge/lib/sha256.js new file mode 100644 index 0000000..0659ad7 --- /dev/null +++ b/node_modules/node-forge/lib/sha256.js @@ -0,0 +1,327 @@ +/** + * Secure Hash Algorithm with 256-bit digest (SHA-256) implementation. + * + * See FIPS 180-2 for details. + * + * @author Dave Longley + * + * Copyright (c) 2010-2015 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./md'); +require('./util'); + +var sha256 = module.exports = forge.sha256 = forge.sha256 || {}; +forge.md.sha256 = forge.md.algorithms.sha256 = sha256; + +/** + * Creates a SHA-256 message digest object. + * + * @return a message digest object. + */ +sha256.create = function() { + // do initialization as necessary + if(!_initialized) { + _init(); + } + + // SHA-256 state contains eight 32-bit integers + var _state = null; + + // input buffer + var _input = forge.util.createBuffer(); + + // used for word storage + var _w = new Array(64); + + // message digest object + var md = { + algorithm: 'sha256', + blockLength: 64, + digestLength: 32, + // 56-bit length of message so far (does not including padding) + messageLength: 0, + // true message length + fullMessageLength: null, + // size of message length in bytes + messageLengthSize: 8 + }; + + /** + * Starts the digest. + * + * @return this digest object. + */ + md.start = function() { + // up to 56-bit message length for convenience + md.messageLength = 0; + + // full message length (set md.messageLength64 for backwards-compatibility) + md.fullMessageLength = md.messageLength64 = []; + var int32s = md.messageLengthSize / 4; + for(var i = 0; i < int32s; ++i) { + md.fullMessageLength.push(0); + } + _input = forge.util.createBuffer(); + _state = { + h0: 0x6A09E667, + h1: 0xBB67AE85, + h2: 0x3C6EF372, + h3: 0xA54FF53A, + h4: 0x510E527F, + h5: 0x9B05688C, + h6: 0x1F83D9AB, + h7: 0x5BE0CD19 + }; + return md; + }; + // start digest automatically for first time + md.start(); + + /** + * Updates the digest with the given message input. The given input can + * treated as raw input (no encoding will be applied) or an encoding of + * 'utf8' maybe given to encode the input using UTF-8. + * + * @param msg the message input to update with. + * @param encoding the encoding to use (default: 'raw', other: 'utf8'). + * + * @return this digest object. + */ + md.update = function(msg, encoding) { + if(encoding === 'utf8') { + msg = forge.util.encodeUtf8(msg); + } + + // update message length + var len = msg.length; + md.messageLength += len; + len = [(len / 0x100000000) >>> 0, len >>> 0]; + for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { + md.fullMessageLength[i] += len[1]; + len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0); + md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; + len[0] = ((len[1] / 0x100000000) >>> 0); + } + + // add bytes to input buffer + _input.putBytes(msg); + + // process bytes + _update(_state, _w, _input); + + // compact input buffer every 2K or if empty + if(_input.read > 2048 || _input.length() === 0) { + _input.compact(); + } + + return md; + }; + + /** + * Produces the digest. + * + * @return a byte buffer containing the digest value. + */ + md.digest = function() { + /* Note: Here we copy the remaining bytes in the input buffer and + add the appropriate SHA-256 padding. Then we do the final update + on a copy of the state so that if the user wants to get + intermediate digests they can do so. */ + + /* Determine the number of bytes that must be added to the message + to ensure its length is congruent to 448 mod 512. In other words, + the data to be digested must be a multiple of 512 bits (or 128 bytes). + This data includes the message, some padding, and the length of the + message. Since the length of the message will be encoded as 8 bytes (64 + bits), that means that the last segment of the data must have 56 bytes + (448 bits) of message and padding. Therefore, the length of the message + plus the padding must be congruent to 448 mod 512 because + 512 - 128 = 448. + + In order to fill up the message length it must be filled with + padding that begins with 1 bit followed by all 0 bits. Padding + must *always* be present, so if the message length is already + congruent to 448 mod 512, then 512 padding bits must be added. */ + + var finalBlock = forge.util.createBuffer(); + finalBlock.putBytes(_input.bytes()); + + // compute remaining size to be digested (include message length size) + var remaining = ( + md.fullMessageLength[md.fullMessageLength.length - 1] + + md.messageLengthSize); + + // add padding for overflow blockSize - overflow + // _padding starts with 1 byte with first bit is set (byte value 128), then + // there may be up to (blockSize - 1) other pad bytes + var overflow = remaining & (md.blockLength - 1); + finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); + + // serialize message length in bits in big-endian order; since length + // is stored in bytes we multiply by 8 and add carry from next int + var next, carry; + var bits = md.fullMessageLength[0] * 8; + for(var i = 0; i < md.fullMessageLength.length - 1; ++i) { + next = md.fullMessageLength[i + 1] * 8; + carry = (next / 0x100000000) >>> 0; + bits += carry; + finalBlock.putInt32(bits >>> 0); + bits = next >>> 0; + } + finalBlock.putInt32(bits); + + var s2 = { + h0: _state.h0, + h1: _state.h1, + h2: _state.h2, + h3: _state.h3, + h4: _state.h4, + h5: _state.h5, + h6: _state.h6, + h7: _state.h7 + }; + _update(s2, _w, finalBlock); + var rval = forge.util.createBuffer(); + rval.putInt32(s2.h0); + rval.putInt32(s2.h1); + rval.putInt32(s2.h2); + rval.putInt32(s2.h3); + rval.putInt32(s2.h4); + rval.putInt32(s2.h5); + rval.putInt32(s2.h6); + rval.putInt32(s2.h7); + return rval; + }; + + return md; +}; + +// sha-256 padding bytes not initialized yet +var _padding = null; +var _initialized = false; + +// table of constants +var _k = null; + +/** + * Initializes the constant tables. + */ +function _init() { + // create padding + _padding = String.fromCharCode(128); + _padding += forge.util.fillString(String.fromCharCode(0x00), 64); + + // create K table for SHA-256 + _k = [ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, + 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, + 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, + 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, + 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 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]; + + // now initialized + _initialized = true; +} + +/** + * Updates a SHA-256 state with the given byte buffer. + * + * @param s the SHA-256 state to update. + * @param w the array to use to store words. + * @param bytes the byte buffer to update with. + */ +function _update(s, w, bytes) { + // consume 512 bit (64 byte) chunks + var t1, t2, s0, s1, ch, maj, i, a, b, c, d, e, f, g, h; + var len = bytes.length(); + while(len >= 64) { + // the w array will be populated with sixteen 32-bit big-endian words + // and then extended into 64 32-bit words according to SHA-256 + for(i = 0; i < 16; ++i) { + w[i] = bytes.getInt32(); + } + for(; i < 64; ++i) { + // XOR word 2 words ago rot right 17, rot right 19, shft right 10 + t1 = w[i - 2]; + t1 = + ((t1 >>> 17) | (t1 << 15)) ^ + ((t1 >>> 19) | (t1 << 13)) ^ + (t1 >>> 10); + // XOR word 15 words ago rot right 7, rot right 18, shft right 3 + t2 = w[i - 15]; + t2 = + ((t2 >>> 7) | (t2 << 25)) ^ + ((t2 >>> 18) | (t2 << 14)) ^ + (t2 >>> 3); + // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^32 + w[i] = (t1 + w[i - 7] + t2 + w[i - 16]) | 0; + } + + // initialize hash value for this chunk + a = s.h0; + b = s.h1; + c = s.h2; + d = s.h3; + e = s.h4; + f = s.h5; + g = s.h6; + h = s.h7; + + // round function + for(i = 0; i < 64; ++i) { + // Sum1(e) + s1 = + ((e >>> 6) | (e << 26)) ^ + ((e >>> 11) | (e << 21)) ^ + ((e >>> 25) | (e << 7)); + // Ch(e, f, g) (optimized the same way as SHA-1) + ch = g ^ (e & (f ^ g)); + // Sum0(a) + s0 = + ((a >>> 2) | (a << 30)) ^ + ((a >>> 13) | (a << 19)) ^ + ((a >>> 22) | (a << 10)); + // Maj(a, b, c) (optimized the same way as SHA-1) + maj = (a & b) | (c & (a ^ b)); + + // main algorithm + t1 = h + s1 + ch + _k[i] + w[i]; + t2 = s0 + maj; + h = g; + g = f; + f = e; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + // can't truncate with `| 0` + e = (d + t1) >>> 0; + d = c; + c = b; + b = a; + // `>>> 0` necessary to avoid iOS/Safari 10 optimization bug + // can't truncate with `| 0` + a = (t1 + t2) >>> 0; + } + + // update hash state + s.h0 = (s.h0 + a) | 0; + s.h1 = (s.h1 + b) | 0; + s.h2 = (s.h2 + c) | 0; + s.h3 = (s.h3 + d) | 0; + s.h4 = (s.h4 + e) | 0; + s.h5 = (s.h5 + f) | 0; + s.h6 = (s.h6 + g) | 0; + s.h7 = (s.h7 + h) | 0; + len -= 64; + } +} diff --git a/node_modules/node-forge/lib/sha512.js b/node_modules/node-forge/lib/sha512.js new file mode 100644 index 0000000..e09b442 --- /dev/null +++ b/node_modules/node-forge/lib/sha512.js @@ -0,0 +1,561 @@ +/** + * Secure Hash Algorithm with a 1024-bit block size implementation. + * + * This includes: SHA-512, SHA-384, SHA-512/224, and SHA-512/256. For + * SHA-256 (block size 512 bits), see sha256.js. + * + * See FIPS 180-4 for details. + * + * @author Dave Longley + * + * Copyright (c) 2014-2015 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./md'); +require('./util'); + +var sha512 = module.exports = forge.sha512 = forge.sha512 || {}; + +// SHA-512 +forge.md.sha512 = forge.md.algorithms.sha512 = sha512; + +// SHA-384 +var sha384 = forge.sha384 = forge.sha512.sha384 = forge.sha512.sha384 || {}; +sha384.create = function() { + return sha512.create('SHA-384'); +}; +forge.md.sha384 = forge.md.algorithms.sha384 = sha384; + +// SHA-512/256 +forge.sha512.sha256 = forge.sha512.sha256 || { + create: function() { + return sha512.create('SHA-512/256'); + } +}; +forge.md['sha512/256'] = forge.md.algorithms['sha512/256'] = + forge.sha512.sha256; + +// SHA-512/224 +forge.sha512.sha224 = forge.sha512.sha224 || { + create: function() { + return sha512.create('SHA-512/224'); + } +}; +forge.md['sha512/224'] = forge.md.algorithms['sha512/224'] = + forge.sha512.sha224; + +/** + * Creates a SHA-2 message digest object. + * + * @param algorithm the algorithm to use (SHA-512, SHA-384, SHA-512/224, + * SHA-512/256). + * + * @return a message digest object. + */ +sha512.create = function(algorithm) { + // do initialization as necessary + if(!_initialized) { + _init(); + } + + if(typeof algorithm === 'undefined') { + algorithm = 'SHA-512'; + } + + if(!(algorithm in _states)) { + throw new Error('Invalid SHA-512 algorithm: ' + algorithm); + } + + // SHA-512 state contains eight 64-bit integers (each as two 32-bit ints) + var _state = _states[algorithm]; + var _h = null; + + // input buffer + var _input = forge.util.createBuffer(); + + // used for 64-bit word storage + var _w = new Array(80); + for(var wi = 0; wi < 80; ++wi) { + _w[wi] = new Array(2); + } + + // determine digest length by algorithm name (default) + var digestLength = 64; + switch(algorithm) { + case 'SHA-384': + digestLength = 48; + break; + case 'SHA-512/256': + digestLength = 32; + break; + case 'SHA-512/224': + digestLength = 28; + break; + } + + // message digest object + var md = { + // SHA-512 => sha512 + algorithm: algorithm.replace('-', '').toLowerCase(), + blockLength: 128, + digestLength: digestLength, + // 56-bit length of message so far (does not including padding) + messageLength: 0, + // true message length + fullMessageLength: null, + // size of message length in bytes + messageLengthSize: 16 + }; + + /** + * Starts the digest. + * + * @return this digest object. + */ + md.start = function() { + // up to 56-bit message length for convenience + md.messageLength = 0; + + // full message length (set md.messageLength128 for backwards-compatibility) + md.fullMessageLength = md.messageLength128 = []; + var int32s = md.messageLengthSize / 4; + for(var i = 0; i < int32s; ++i) { + md.fullMessageLength.push(0); + } + _input = forge.util.createBuffer(); + _h = new Array(_state.length); + for(var i = 0; i < _state.length; ++i) { + _h[i] = _state[i].slice(0); + } + return md; + }; + // start digest automatically for first time + md.start(); + + /** + * Updates the digest with the given message input. The given input can + * treated as raw input (no encoding will be applied) or an encoding of + * 'utf8' maybe given to encode the input using UTF-8. + * + * @param msg the message input to update with. + * @param encoding the encoding to use (default: 'raw', other: 'utf8'). + * + * @return this digest object. + */ + md.update = function(msg, encoding) { + if(encoding === 'utf8') { + msg = forge.util.encodeUtf8(msg); + } + + // update message length + var len = msg.length; + md.messageLength += len; + len = [(len / 0x100000000) >>> 0, len >>> 0]; + for(var i = md.fullMessageLength.length - 1; i >= 0; --i) { + md.fullMessageLength[i] += len[1]; + len[1] = len[0] + ((md.fullMessageLength[i] / 0x100000000) >>> 0); + md.fullMessageLength[i] = md.fullMessageLength[i] >>> 0; + len[0] = ((len[1] / 0x100000000) >>> 0); + } + + // add bytes to input buffer + _input.putBytes(msg); + + // process bytes + _update(_h, _w, _input); + + // compact input buffer every 2K or if empty + if(_input.read > 2048 || _input.length() === 0) { + _input.compact(); + } + + return md; + }; + + /** + * Produces the digest. + * + * @return a byte buffer containing the digest value. + */ + md.digest = function() { + /* Note: Here we copy the remaining bytes in the input buffer and + add the appropriate SHA-512 padding. Then we do the final update + on a copy of the state so that if the user wants to get + intermediate digests they can do so. */ + + /* Determine the number of bytes that must be added to the message + to ensure its length is congruent to 896 mod 1024. In other words, + the data to be digested must be a multiple of 1024 bits (or 128 bytes). + This data includes the message, some padding, and the length of the + message. Since the length of the message will be encoded as 16 bytes (128 + bits), that means that the last segment of the data must have 112 bytes + (896 bits) of message and padding. Therefore, the length of the message + plus the padding must be congruent to 896 mod 1024 because + 1024 - 128 = 896. + + In order to fill up the message length it must be filled with + padding that begins with 1 bit followed by all 0 bits. Padding + must *always* be present, so if the message length is already + congruent to 896 mod 1024, then 1024 padding bits must be added. */ + + var finalBlock = forge.util.createBuffer(); + finalBlock.putBytes(_input.bytes()); + + // compute remaining size to be digested (include message length size) + var remaining = ( + md.fullMessageLength[md.fullMessageLength.length - 1] + + md.messageLengthSize); + + // add padding for overflow blockSize - overflow + // _padding starts with 1 byte with first bit is set (byte value 128), then + // there may be up to (blockSize - 1) other pad bytes + var overflow = remaining & (md.blockLength - 1); + finalBlock.putBytes(_padding.substr(0, md.blockLength - overflow)); + + // serialize message length in bits in big-endian order; since length + // is stored in bytes we multiply by 8 and add carry from next int + var next, carry; + var bits = md.fullMessageLength[0] * 8; + for(var i = 0; i < md.fullMessageLength.length - 1; ++i) { + next = md.fullMessageLength[i + 1] * 8; + carry = (next / 0x100000000) >>> 0; + bits += carry; + finalBlock.putInt32(bits >>> 0); + bits = next >>> 0; + } + finalBlock.putInt32(bits); + + var h = new Array(_h.length); + for(var i = 0; i < _h.length; ++i) { + h[i] = _h[i].slice(0); + } + _update(h, _w, finalBlock); + var rval = forge.util.createBuffer(); + var hlen; + if(algorithm === 'SHA-512') { + hlen = h.length; + } else if(algorithm === 'SHA-384') { + hlen = h.length - 2; + } else { + hlen = h.length - 4; + } + for(var i = 0; i < hlen; ++i) { + rval.putInt32(h[i][0]); + if(i !== hlen - 1 || algorithm !== 'SHA-512/224') { + rval.putInt32(h[i][1]); + } + } + return rval; + }; + + return md; +}; + +// sha-512 padding bytes not initialized yet +var _padding = null; +var _initialized = false; + +// table of constants +var _k = null; + +// initial hash states +var _states = null; + +/** + * Initializes the constant tables. + */ +function _init() { + // create padding + _padding = String.fromCharCode(128); + _padding += forge.util.fillString(String.fromCharCode(0x00), 128); + + // create K table for SHA-512 + _k = [ + [0x428a2f98, 0xd728ae22], [0x71374491, 0x23ef65cd], + [0xb5c0fbcf, 0xec4d3b2f], [0xe9b5dba5, 0x8189dbbc], + [0x3956c25b, 0xf348b538], [0x59f111f1, 0xb605d019], + [0x923f82a4, 0xaf194f9b], [0xab1c5ed5, 0xda6d8118], + [0xd807aa98, 0xa3030242], [0x12835b01, 0x45706fbe], + [0x243185be, 0x4ee4b28c], [0x550c7dc3, 0xd5ffb4e2], + [0x72be5d74, 0xf27b896f], [0x80deb1fe, 0x3b1696b1], + [0x9bdc06a7, 0x25c71235], [0xc19bf174, 0xcf692694], + [0xe49b69c1, 0x9ef14ad2], [0xefbe4786, 0x384f25e3], + [0x0fc19dc6, 0x8b8cd5b5], [0x240ca1cc, 0x77ac9c65], + [0x2de92c6f, 0x592b0275], [0x4a7484aa, 0x6ea6e483], + [0x5cb0a9dc, 0xbd41fbd4], [0x76f988da, 0x831153b5], + [0x983e5152, 0xee66dfab], [0xa831c66d, 0x2db43210], + [0xb00327c8, 0x98fb213f], [0xbf597fc7, 0xbeef0ee4], + [0xc6e00bf3, 0x3da88fc2], [0xd5a79147, 0x930aa725], + [0x06ca6351, 0xe003826f], [0x14292967, 0x0a0e6e70], + [0x27b70a85, 0x46d22ffc], [0x2e1b2138, 0x5c26c926], + [0x4d2c6dfc, 0x5ac42aed], [0x53380d13, 0x9d95b3df], + [0x650a7354, 0x8baf63de], [0x766a0abb, 0x3c77b2a8], + [0x81c2c92e, 0x47edaee6], [0x92722c85, 0x1482353b], + [0xa2bfe8a1, 0x4cf10364], [0xa81a664b, 0xbc423001], + [0xc24b8b70, 0xd0f89791], [0xc76c51a3, 0x0654be30], + [0xd192e819, 0xd6ef5218], [0xd6990624, 0x5565a910], + [0xf40e3585, 0x5771202a], [0x106aa070, 0x32bbd1b8], + [0x19a4c116, 0xb8d2d0c8], [0x1e376c08, 0x5141ab53], + [0x2748774c, 0xdf8eeb99], [0x34b0bcb5, 0xe19b48a8], + [0x391c0cb3, 0xc5c95a63], [0x4ed8aa4a, 0xe3418acb], + [0x5b9cca4f, 0x7763e373], [0x682e6ff3, 0xd6b2b8a3], + [0x748f82ee, 0x5defb2fc], [0x78a5636f, 0x43172f60], + [0x84c87814, 0xa1f0ab72], [0x8cc70208, 0x1a6439ec], + [0x90befffa, 0x23631e28], [0xa4506ceb, 0xde82bde9], + [0xbef9a3f7, 0xb2c67915], [0xc67178f2, 0xe372532b], + [0xca273ece, 0xea26619c], [0xd186b8c7, 0x21c0c207], + [0xeada7dd6, 0xcde0eb1e], [0xf57d4f7f, 0xee6ed178], + [0x06f067aa, 0x72176fba], [0x0a637dc5, 0xa2c898a6], + [0x113f9804, 0xbef90dae], [0x1b710b35, 0x131c471b], + [0x28db77f5, 0x23047d84], [0x32caab7b, 0x40c72493], + [0x3c9ebe0a, 0x15c9bebc], [0x431d67c4, 0x9c100d4c], + [0x4cc5d4be, 0xcb3e42b6], [0x597f299c, 0xfc657e2a], + [0x5fcb6fab, 0x3ad6faec], [0x6c44198c, 0x4a475817] + ]; + + // initial hash states + _states = {}; + _states['SHA-512'] = [ + [0x6a09e667, 0xf3bcc908], + [0xbb67ae85, 0x84caa73b], + [0x3c6ef372, 0xfe94f82b], + [0xa54ff53a, 0x5f1d36f1], + [0x510e527f, 0xade682d1], + [0x9b05688c, 0x2b3e6c1f], + [0x1f83d9ab, 0xfb41bd6b], + [0x5be0cd19, 0x137e2179] + ]; + _states['SHA-384'] = [ + [0xcbbb9d5d, 0xc1059ed8], + [0x629a292a, 0x367cd507], + [0x9159015a, 0x3070dd17], + [0x152fecd8, 0xf70e5939], + [0x67332667, 0xffc00b31], + [0x8eb44a87, 0x68581511], + [0xdb0c2e0d, 0x64f98fa7], + [0x47b5481d, 0xbefa4fa4] + ]; + _states['SHA-512/256'] = [ + [0x22312194, 0xFC2BF72C], + [0x9F555FA3, 0xC84C64C2], + [0x2393B86B, 0x6F53B151], + [0x96387719, 0x5940EABD], + [0x96283EE2, 0xA88EFFE3], + [0xBE5E1E25, 0x53863992], + [0x2B0199FC, 0x2C85B8AA], + [0x0EB72DDC, 0x81C52CA2] + ]; + _states['SHA-512/224'] = [ + [0x8C3D37C8, 0x19544DA2], + [0x73E19966, 0x89DCD4D6], + [0x1DFAB7AE, 0x32FF9C82], + [0x679DD514, 0x582F9FCF], + [0x0F6D2B69, 0x7BD44DA8], + [0x77E36F73, 0x04C48942], + [0x3F9D85A8, 0x6A1D36C8], + [0x1112E6AD, 0x91D692A1] + ]; + + // now initialized + _initialized = true; +} + +/** + * Updates a SHA-512 state with the given byte buffer. + * + * @param s the SHA-512 state to update. + * @param w the array to use to store words. + * @param bytes the byte buffer to update with. + */ +function _update(s, w, bytes) { + // consume 512 bit (128 byte) chunks + var t1_hi, t1_lo; + var t2_hi, t2_lo; + var s0_hi, s0_lo; + var s1_hi, s1_lo; + var ch_hi, ch_lo; + var maj_hi, maj_lo; + var a_hi, a_lo; + var b_hi, b_lo; + var c_hi, c_lo; + var d_hi, d_lo; + var e_hi, e_lo; + var f_hi, f_lo; + var g_hi, g_lo; + var h_hi, h_lo; + var i, hi, lo, w2, w7, w15, w16; + var len = bytes.length(); + while(len >= 128) { + // the w array will be populated with sixteen 64-bit big-endian words + // and then extended into 64 64-bit words according to SHA-512 + for(i = 0; i < 16; ++i) { + w[i][0] = bytes.getInt32() >>> 0; + w[i][1] = bytes.getInt32() >>> 0; + } + for(; i < 80; ++i) { + // for word 2 words ago: ROTR 19(x) ^ ROTR 61(x) ^ SHR 6(x) + w2 = w[i - 2]; + hi = w2[0]; + lo = w2[1]; + + // high bits + t1_hi = ( + ((hi >>> 19) | (lo << 13)) ^ // ROTR 19 + ((lo >>> 29) | (hi << 3)) ^ // ROTR 61/(swap + ROTR 29) + (hi >>> 6)) >>> 0; // SHR 6 + // low bits + t1_lo = ( + ((hi << 13) | (lo >>> 19)) ^ // ROTR 19 + ((lo << 3) | (hi >>> 29)) ^ // ROTR 61/(swap + ROTR 29) + ((hi << 26) | (lo >>> 6))) >>> 0; // SHR 6 + + // for word 15 words ago: ROTR 1(x) ^ ROTR 8(x) ^ SHR 7(x) + w15 = w[i - 15]; + hi = w15[0]; + lo = w15[1]; + + // high bits + t2_hi = ( + ((hi >>> 1) | (lo << 31)) ^ // ROTR 1 + ((hi >>> 8) | (lo << 24)) ^ // ROTR 8 + (hi >>> 7)) >>> 0; // SHR 7 + // low bits + t2_lo = ( + ((hi << 31) | (lo >>> 1)) ^ // ROTR 1 + ((hi << 24) | (lo >>> 8)) ^ // ROTR 8 + ((hi << 25) | (lo >>> 7))) >>> 0; // SHR 7 + + // sum(t1, word 7 ago, t2, word 16 ago) modulo 2^64 (carry lo overflow) + w7 = w[i - 7]; + w16 = w[i - 16]; + lo = (t1_lo + w7[1] + t2_lo + w16[1]); + w[i][0] = (t1_hi + w7[0] + t2_hi + w16[0] + + ((lo / 0x100000000) >>> 0)) >>> 0; + w[i][1] = lo >>> 0; + } + + // initialize hash value for this chunk + a_hi = s[0][0]; + a_lo = s[0][1]; + b_hi = s[1][0]; + b_lo = s[1][1]; + c_hi = s[2][0]; + c_lo = s[2][1]; + d_hi = s[3][0]; + d_lo = s[3][1]; + e_hi = s[4][0]; + e_lo = s[4][1]; + f_hi = s[5][0]; + f_lo = s[5][1]; + g_hi = s[6][0]; + g_lo = s[6][1]; + h_hi = s[7][0]; + h_lo = s[7][1]; + + // round function + for(i = 0; i < 80; ++i) { + // Sum1(e) = ROTR 14(e) ^ ROTR 18(e) ^ ROTR 41(e) + s1_hi = ( + ((e_hi >>> 14) | (e_lo << 18)) ^ // ROTR 14 + ((e_hi >>> 18) | (e_lo << 14)) ^ // ROTR 18 + ((e_lo >>> 9) | (e_hi << 23))) >>> 0; // ROTR 41/(swap + ROTR 9) + s1_lo = ( + ((e_hi << 18) | (e_lo >>> 14)) ^ // ROTR 14 + ((e_hi << 14) | (e_lo >>> 18)) ^ // ROTR 18 + ((e_lo << 23) | (e_hi >>> 9))) >>> 0; // ROTR 41/(swap + ROTR 9) + + // Ch(e, f, g) (optimized the same way as SHA-1) + ch_hi = (g_hi ^ (e_hi & (f_hi ^ g_hi))) >>> 0; + ch_lo = (g_lo ^ (e_lo & (f_lo ^ g_lo))) >>> 0; + + // Sum0(a) = ROTR 28(a) ^ ROTR 34(a) ^ ROTR 39(a) + s0_hi = ( + ((a_hi >>> 28) | (a_lo << 4)) ^ // ROTR 28 + ((a_lo >>> 2) | (a_hi << 30)) ^ // ROTR 34/(swap + ROTR 2) + ((a_lo >>> 7) | (a_hi << 25))) >>> 0; // ROTR 39/(swap + ROTR 7) + s0_lo = ( + ((a_hi << 4) | (a_lo >>> 28)) ^ // ROTR 28 + ((a_lo << 30) | (a_hi >>> 2)) ^ // ROTR 34/(swap + ROTR 2) + ((a_lo << 25) | (a_hi >>> 7))) >>> 0; // ROTR 39/(swap + ROTR 7) + + // Maj(a, b, c) (optimized the same way as SHA-1) + maj_hi = ((a_hi & b_hi) | (c_hi & (a_hi ^ b_hi))) >>> 0; + maj_lo = ((a_lo & b_lo) | (c_lo & (a_lo ^ b_lo))) >>> 0; + + // main algorithm + // t1 = (h + s1 + ch + _k[i] + _w[i]) modulo 2^64 (carry lo overflow) + lo = (h_lo + s1_lo + ch_lo + _k[i][1] + w[i][1]); + t1_hi = (h_hi + s1_hi + ch_hi + _k[i][0] + w[i][0] + + ((lo / 0x100000000) >>> 0)) >>> 0; + t1_lo = lo >>> 0; + + // t2 = s0 + maj modulo 2^64 (carry lo overflow) + lo = s0_lo + maj_lo; + t2_hi = (s0_hi + maj_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + t2_lo = lo >>> 0; + + h_hi = g_hi; + h_lo = g_lo; + + g_hi = f_hi; + g_lo = f_lo; + + f_hi = e_hi; + f_lo = e_lo; + + // e = (d + t1) modulo 2^64 (carry lo overflow) + lo = d_lo + t1_lo; + e_hi = (d_hi + t1_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + e_lo = lo >>> 0; + + d_hi = c_hi; + d_lo = c_lo; + + c_hi = b_hi; + c_lo = b_lo; + + b_hi = a_hi; + b_lo = a_lo; + + // a = (t1 + t2) modulo 2^64 (carry lo overflow) + lo = t1_lo + t2_lo; + a_hi = (t1_hi + t2_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + a_lo = lo >>> 0; + } + + // update hash state (additional modulo 2^64) + lo = s[0][1] + a_lo; + s[0][0] = (s[0][0] + a_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + s[0][1] = lo >>> 0; + + lo = s[1][1] + b_lo; + s[1][0] = (s[1][0] + b_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + s[1][1] = lo >>> 0; + + lo = s[2][1] + c_lo; + s[2][0] = (s[2][0] + c_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + s[2][1] = lo >>> 0; + + lo = s[3][1] + d_lo; + s[3][0] = (s[3][0] + d_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + s[3][1] = lo >>> 0; + + lo = s[4][1] + e_lo; + s[4][0] = (s[4][0] + e_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + s[4][1] = lo >>> 0; + + lo = s[5][1] + f_lo; + s[5][0] = (s[5][0] + f_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + s[5][1] = lo >>> 0; + + lo = s[6][1] + g_lo; + s[6][0] = (s[6][0] + g_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + s[6][1] = lo >>> 0; + + lo = s[7][1] + h_lo; + s[7][0] = (s[7][0] + h_hi + ((lo / 0x100000000) >>> 0)) >>> 0; + s[7][1] = lo >>> 0; + + len -= 128; + } +} diff --git a/node_modules/node-forge/lib/socket.js b/node_modules/node-forge/lib/socket.js new file mode 100644 index 0000000..3a1d7ff --- /dev/null +++ b/node_modules/node-forge/lib/socket.js @@ -0,0 +1,287 @@ +/** + * Socket implementation that uses flash SocketPool class as a backend. + * + * @author Dave Longley + * + * Copyright (c) 2010-2013 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./util'); + +// define net namespace +var net = module.exports = forge.net = forge.net || {}; + +// map of flash ID to socket pool +net.socketPools = {}; + +/** + * Creates a flash socket pool. + * + * @param options: + * flashId: the dom ID for the flash object element. + * policyPort: the default policy port for sockets, 0 to use the + * flash default. + * policyUrl: the default policy file URL for sockets (if provided + * used instead of a policy port). + * msie: true if the browser is msie, false if not. + * + * @return the created socket pool. + */ +net.createSocketPool = function(options) { + // set default + options.msie = options.msie || false; + + // initialize the flash interface + var spId = options.flashId; + var api = document.getElementById(spId); + api.init({marshallExceptions: !options.msie}); + + // create socket pool entry + var sp = { + // ID of the socket pool + id: spId, + // flash interface + flashApi: api, + // map of socket ID to sockets + sockets: {}, + // default policy port + policyPort: options.policyPort || 0, + // default policy URL + policyUrl: options.policyUrl || null + }; + net.socketPools[spId] = sp; + + // create event handler, subscribe to flash events + if(options.msie === true) { + sp.handler = function(e) { + if(e.id in sp.sockets) { + // get handler function + var f; + switch(e.type) { + case 'connect': + f = 'connected'; + break; + case 'close': + f = 'closed'; + break; + case 'socketData': + f = 'data'; + break; + default: + f = 'error'; + break; + } + /* IE calls javascript on the thread of the external object + that triggered the event (in this case flash) ... which will + either run concurrently with other javascript or pre-empt any + running javascript in the middle of its execution (BAD!) ... + calling setTimeout() will schedule the javascript to run on + the javascript thread and solve this EVIL problem. */ + setTimeout(function() {sp.sockets[e.id][f](e);}, 0); + } + }; + } else { + sp.handler = function(e) { + if(e.id in sp.sockets) { + // get handler function + var f; + switch(e.type) { + case 'connect': + f = 'connected'; + break; + case 'close': + f = 'closed'; + break; + case 'socketData': + f = 'data'; + break; + default: + f = 'error'; + break; + } + sp.sockets[e.id][f](e); + } + }; + } + var handler = 'forge.net.socketPools[\'' + spId + '\'].handler'; + api.subscribe('connect', handler); + api.subscribe('close', handler); + api.subscribe('socketData', handler); + api.subscribe('ioError', handler); + api.subscribe('securityError', handler); + + /** + * Destroys a socket pool. The socket pool still needs to be cleaned + * up via net.cleanup(). + */ + sp.destroy = function() { + delete net.socketPools[options.flashId]; + for(var id in sp.sockets) { + sp.sockets[id].destroy(); + } + sp.sockets = {}; + api.cleanup(); + }; + + /** + * Creates a new socket. + * + * @param options: + * connected: function(event) called when the socket connects. + * closed: function(event) called when the socket closes. + * data: function(event) called when socket data has arrived, + * it can be read from the socket using receive(). + * error: function(event) called when a socket error occurs. + */ + sp.createSocket = function(options) { + // default to empty options + options = options || {}; + + // create flash socket + var id = api.create(); + + // create javascript socket wrapper + var socket = { + id: id, + // set handlers + connected: options.connected || function(e) {}, + closed: options.closed || function(e) {}, + data: options.data || function(e) {}, + error: options.error || function(e) {} + }; + + /** + * Destroys this socket. + */ + socket.destroy = function() { + api.destroy(id); + delete sp.sockets[id]; + }; + + /** + * Connects this socket. + * + * @param options: + * host: the host to connect to. + * port: the port to connect to. + * policyPort: the policy port to use (if non-default), 0 to + * use the flash default. + * policyUrl: the policy file URL to use (instead of port). + */ + socket.connect = function(options) { + // give precedence to policy URL over policy port + // if no policy URL and passed port isn't 0, use default port, + // otherwise use 0 for the port + var policyUrl = options.policyUrl || null; + var policyPort = 0; + if(policyUrl === null && options.policyPort !== 0) { + policyPort = options.policyPort || sp.policyPort; + } + api.connect(id, options.host, options.port, policyPort, policyUrl); + }; + + /** + * Closes this socket. + */ + socket.close = function() { + api.close(id); + socket.closed({ + id: socket.id, + type: 'close', + bytesAvailable: 0 + }); + }; + + /** + * Determines if the socket is connected or not. + * + * @return true if connected, false if not. + */ + socket.isConnected = function() { + return api.isConnected(id); + }; + + /** + * Writes bytes to this socket. + * + * @param bytes the bytes (as a string) to write. + * + * @return true on success, false on failure. + */ + socket.send = function(bytes) { + return api.send(id, forge.util.encode64(bytes)); + }; + + /** + * Reads bytes from this socket (non-blocking). Fewer than the number + * of bytes requested may be read if enough bytes are not available. + * + * This method should be called from the data handler if there are + * enough bytes available. To see how many bytes are available, check + * the 'bytesAvailable' property on the event in the data handler or + * call the bytesAvailable() function on the socket. If the browser is + * msie, then the bytesAvailable() function should be used to avoid + * race conditions. Otherwise, using the property on the data handler's + * event may be quicker. + * + * @param count the maximum number of bytes to read. + * + * @return the bytes read (as a string) or null on error. + */ + socket.receive = function(count) { + var rval = api.receive(id, count).rval; + return (rval === null) ? null : forge.util.decode64(rval); + }; + + /** + * Gets the number of bytes available for receiving on the socket. + * + * @return the number of bytes available for receiving. + */ + socket.bytesAvailable = function() { + return api.getBytesAvailable(id); + }; + + // store and return socket + sp.sockets[id] = socket; + return socket; + }; + + return sp; +}; + +/** + * Destroys a flash socket pool. + * + * @param options: + * flashId: the dom ID for the flash object element. + */ +net.destroySocketPool = function(options) { + if(options.flashId in net.socketPools) { + var sp = net.socketPools[options.flashId]; + sp.destroy(); + } +}; + +/** + * Creates a new socket. + * + * @param options: + * flashId: the dom ID for the flash object element. + * connected: function(event) called when the socket connects. + * closed: function(event) called when the socket closes. + * data: function(event) called when socket data has arrived, it + * can be read from the socket using receive(). + * error: function(event) called when a socket error occurs. + * + * @return the created socket. + */ +net.createSocket = function(options) { + var socket = null; + if(options.flashId in net.socketPools) { + // get related socket pool + var sp = net.socketPools[options.flashId]; + socket = sp.createSocket(options); + } + return socket; +}; diff --git a/node_modules/node-forge/lib/ssh.js b/node_modules/node-forge/lib/ssh.js new file mode 100644 index 0000000..6480203 --- /dev/null +++ b/node_modules/node-forge/lib/ssh.js @@ -0,0 +1,236 @@ +/** + * Functions to output keys in SSH-friendly formats. + * + * This is part of the Forge project which may be used under the terms of + * either the BSD License or the GNU General Public License (GPL) Version 2. + * + * See: https://github.com/digitalbazaar/forge/blob/cbebca3780658703d925b61b2caffb1d263a6c1d/LICENSE + * + * @author https://github.com/shellac + */ +var forge = require('./forge'); +require('./aes'); +require('./hmac'); +require('./md5'); +require('./sha1'); +require('./util'); + +var ssh = module.exports = forge.ssh = forge.ssh || {}; + +/** + * Encodes (and optionally encrypts) a private RSA key as a Putty PPK file. + * + * @param privateKey the key. + * @param passphrase a passphrase to protect the key (falsy for no encryption). + * @param comment a comment to include in the key file. + * + * @return the PPK file as a string. + */ +ssh.privateKeyToPutty = function(privateKey, passphrase, comment) { + comment = comment || ''; + passphrase = passphrase || ''; + var algorithm = 'ssh-rsa'; + var encryptionAlgorithm = (passphrase === '') ? 'none' : 'aes256-cbc'; + + var ppk = 'PuTTY-User-Key-File-2: ' + algorithm + '\r\n'; + ppk += 'Encryption: ' + encryptionAlgorithm + '\r\n'; + ppk += 'Comment: ' + comment + '\r\n'; + + // public key into buffer for ppk + var pubbuffer = forge.util.createBuffer(); + _addStringToBuffer(pubbuffer, algorithm); + _addBigIntegerToBuffer(pubbuffer, privateKey.e); + _addBigIntegerToBuffer(pubbuffer, privateKey.n); + + // write public key + var pub = forge.util.encode64(pubbuffer.bytes(), 64); + var length = Math.floor(pub.length / 66) + 1; // 66 = 64 + \r\n + ppk += 'Public-Lines: ' + length + '\r\n'; + ppk += pub; + + // private key into a buffer + var privbuffer = forge.util.createBuffer(); + _addBigIntegerToBuffer(privbuffer, privateKey.d); + _addBigIntegerToBuffer(privbuffer, privateKey.p); + _addBigIntegerToBuffer(privbuffer, privateKey.q); + _addBigIntegerToBuffer(privbuffer, privateKey.qInv); + + // optionally encrypt the private key + var priv; + if(!passphrase) { + // use the unencrypted buffer + priv = forge.util.encode64(privbuffer.bytes(), 64); + } else { + // encrypt RSA key using passphrase + var encLen = privbuffer.length() + 16 - 1; + encLen -= encLen % 16; + + // pad private key with sha1-d data -- needs to be a multiple of 16 + var padding = _sha1(privbuffer.bytes()); + + padding.truncate(padding.length() - encLen + privbuffer.length()); + privbuffer.putBuffer(padding); + + var aeskey = forge.util.createBuffer(); + aeskey.putBuffer(_sha1('\x00\x00\x00\x00', passphrase)); + aeskey.putBuffer(_sha1('\x00\x00\x00\x01', passphrase)); + + // encrypt some bytes using CBC mode + // key is 40 bytes, so truncate *by* 8 bytes + var cipher = forge.aes.createEncryptionCipher(aeskey.truncate(8), 'CBC'); + cipher.start(forge.util.createBuffer().fillWithByte(0, 16)); + cipher.update(privbuffer.copy()); + cipher.finish(); + var encrypted = cipher.output; + + // Note: this appears to differ from Putty -- is forge wrong, or putty? + // due to padding we finish as an exact multiple of 16 + encrypted.truncate(16); // all padding + + priv = forge.util.encode64(encrypted.bytes(), 64); + } + + // output private key + length = Math.floor(priv.length / 66) + 1; // 64 + \r\n + ppk += '\r\nPrivate-Lines: ' + length + '\r\n'; + ppk += priv; + + // MAC + var mackey = _sha1('putty-private-key-file-mac-key', passphrase); + + var macbuffer = forge.util.createBuffer(); + _addStringToBuffer(macbuffer, algorithm); + _addStringToBuffer(macbuffer, encryptionAlgorithm); + _addStringToBuffer(macbuffer, comment); + macbuffer.putInt32(pubbuffer.length()); + macbuffer.putBuffer(pubbuffer); + macbuffer.putInt32(privbuffer.length()); + macbuffer.putBuffer(privbuffer); + + var hmac = forge.hmac.create(); + hmac.start('sha1', mackey); + hmac.update(macbuffer.bytes()); + + ppk += '\r\nPrivate-MAC: ' + hmac.digest().toHex() + '\r\n'; + + return ppk; +}; + +/** + * Encodes a public RSA key as an OpenSSH file. + * + * @param key the key. + * @param comment a comment. + * + * @return the public key in OpenSSH format. + */ +ssh.publicKeyToOpenSSH = function(key, comment) { + var type = 'ssh-rsa'; + comment = comment || ''; + + var buffer = forge.util.createBuffer(); + _addStringToBuffer(buffer, type); + _addBigIntegerToBuffer(buffer, key.e); + _addBigIntegerToBuffer(buffer, key.n); + + return type + ' ' + forge.util.encode64(buffer.bytes()) + ' ' + comment; +}; + +/** + * Encodes a private RSA key as an OpenSSH file. + * + * @param key the key. + * @param passphrase a passphrase to protect the key (falsy for no encryption). + * + * @return the public key in OpenSSH format. + */ +ssh.privateKeyToOpenSSH = function(privateKey, passphrase) { + if(!passphrase) { + return forge.pki.privateKeyToPem(privateKey); + } + // OpenSSH private key is just a legacy format, it seems + return forge.pki.encryptRsaPrivateKey(privateKey, passphrase, + {legacy: true, algorithm: 'aes128'}); +}; + +/** + * Gets the SSH fingerprint for the given public key. + * + * @param options the options to use. + * [md] the message digest object to use (defaults to forge.md.md5). + * [encoding] an alternative output encoding, such as 'hex' + * (defaults to none, outputs a byte buffer). + * [delimiter] the delimiter to use between bytes for 'hex' encoded + * output, eg: ':' (defaults to none). + * + * @return the fingerprint as a byte buffer or other encoding based on options. + */ +ssh.getPublicKeyFingerprint = function(key, options) { + options = options || {}; + var md = options.md || forge.md.md5.create(); + + var type = 'ssh-rsa'; + var buffer = forge.util.createBuffer(); + _addStringToBuffer(buffer, type); + _addBigIntegerToBuffer(buffer, key.e); + _addBigIntegerToBuffer(buffer, key.n); + + // hash public key bytes + md.start(); + md.update(buffer.getBytes()); + var digest = md.digest(); + if(options.encoding === 'hex') { + var hex = digest.toHex(); + if(options.delimiter) { + return hex.match(/.{2}/g).join(options.delimiter); + } + return hex; + } else if(options.encoding === 'binary') { + return digest.getBytes(); + } else if(options.encoding) { + throw new Error('Unknown encoding "' + options.encoding + '".'); + } + return digest; +}; + +/** + * Adds len(val) then val to a buffer. + * + * @param buffer the buffer to add to. + * @param val a big integer. + */ +function _addBigIntegerToBuffer(buffer, val) { + var hexVal = val.toString(16); + // ensure 2s complement +ve + if(hexVal[0] >= '8') { + hexVal = '00' + hexVal; + } + var bytes = forge.util.hexToBytes(hexVal); + buffer.putInt32(bytes.length); + buffer.putBytes(bytes); +} + +/** + * Adds len(val) then val to a buffer. + * + * @param buffer the buffer to add to. + * @param val a string. + */ +function _addStringToBuffer(buffer, val) { + buffer.putInt32(val.length); + buffer.putString(val); +} + +/** + * Hashes the arguments into one value using SHA-1. + * + * @return the sha1 hash of the provided arguments. + */ +function _sha1() { + var sha = forge.md.sha1.create(); + var num = arguments.length; + for (var i = 0; i < num; ++i) { + sha.update(arguments[i]); + } + return sha.digest(); +} diff --git a/node_modules/node-forge/lib/task.js b/node_modules/node-forge/lib/task.js new file mode 100644 index 0000000..df48660 --- /dev/null +++ b/node_modules/node-forge/lib/task.js @@ -0,0 +1,725 @@ +/** + * Support for concurrent task management and synchronization in web + * applications. + * + * @author Dave Longley + * @author David I. Lehn + * + * Copyright (c) 2009-2013 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./debug'); +require('./log'); +require('./util'); + +// logging category +var cat = 'forge.task'; + +// verbose level +// 0: off, 1: a little, 2: a whole lot +// Verbose debug logging is surrounded by a level check to avoid the +// performance issues with even calling the logging code regardless if it +// is actually logged. For performance reasons this should not be set to 2 +// for production use. +// ex: if(sVL >= 2) forge.log.verbose(....) +var sVL = 0; + +// track tasks for debugging +var sTasks = {}; +var sNextTaskId = 0; +// debug access +forge.debug.set(cat, 'tasks', sTasks); + +// a map of task type to task queue +var sTaskQueues = {}; +// debug access +forge.debug.set(cat, 'queues', sTaskQueues); + +// name for unnamed tasks +var sNoTaskName = '?'; + +// maximum number of doNext() recursions before a context swap occurs +// FIXME: might need to tweak this based on the browser +var sMaxRecursions = 30; + +// time slice for doing tasks before a context swap occurs +// FIXME: might need to tweak this based on the browser +var sTimeSlice = 20; + +/** + * Task states. + * + * READY: ready to start processing + * RUNNING: task or a subtask is running + * BLOCKED: task is waiting to acquire N permits to continue + * SLEEPING: task is sleeping for a period of time + * DONE: task is done + * ERROR: task has an error + */ +var READY = 'ready'; +var RUNNING = 'running'; +var BLOCKED = 'blocked'; +var SLEEPING = 'sleeping'; +var DONE = 'done'; +var ERROR = 'error'; + +/** + * Task actions. Used to control state transitions. + * + * STOP: stop processing + * START: start processing tasks + * BLOCK: block task from continuing until 1 or more permits are released + * UNBLOCK: release one or more permits + * SLEEP: sleep for a period of time + * WAKEUP: wakeup early from SLEEPING state + * CANCEL: cancel further tasks + * FAIL: a failure occured + */ +var STOP = 'stop'; +var START = 'start'; +var BLOCK = 'block'; +var UNBLOCK = 'unblock'; +var SLEEP = 'sleep'; +var WAKEUP = 'wakeup'; +var CANCEL = 'cancel'; +var FAIL = 'fail'; + +/** + * State transition table. + * + * nextState = sStateTable[currentState][action] + */ +var sStateTable = {}; + +sStateTable[READY] = {}; +sStateTable[READY][STOP] = READY; +sStateTable[READY][START] = RUNNING; +sStateTable[READY][CANCEL] = DONE; +sStateTable[READY][FAIL] = ERROR; + +sStateTable[RUNNING] = {}; +sStateTable[RUNNING][STOP] = READY; +sStateTable[RUNNING][START] = RUNNING; +sStateTable[RUNNING][BLOCK] = BLOCKED; +sStateTable[RUNNING][UNBLOCK] = RUNNING; +sStateTable[RUNNING][SLEEP] = SLEEPING; +sStateTable[RUNNING][WAKEUP] = RUNNING; +sStateTable[RUNNING][CANCEL] = DONE; +sStateTable[RUNNING][FAIL] = ERROR; + +sStateTable[BLOCKED] = {}; +sStateTable[BLOCKED][STOP] = BLOCKED; +sStateTable[BLOCKED][START] = BLOCKED; +sStateTable[BLOCKED][BLOCK] = BLOCKED; +sStateTable[BLOCKED][UNBLOCK] = BLOCKED; +sStateTable[BLOCKED][SLEEP] = BLOCKED; +sStateTable[BLOCKED][WAKEUP] = BLOCKED; +sStateTable[BLOCKED][CANCEL] = DONE; +sStateTable[BLOCKED][FAIL] = ERROR; + +sStateTable[SLEEPING] = {}; +sStateTable[SLEEPING][STOP] = SLEEPING; +sStateTable[SLEEPING][START] = SLEEPING; +sStateTable[SLEEPING][BLOCK] = SLEEPING; +sStateTable[SLEEPING][UNBLOCK] = SLEEPING; +sStateTable[SLEEPING][SLEEP] = SLEEPING; +sStateTable[SLEEPING][WAKEUP] = SLEEPING; +sStateTable[SLEEPING][CANCEL] = DONE; +sStateTable[SLEEPING][FAIL] = ERROR; + +sStateTable[DONE] = {}; +sStateTable[DONE][STOP] = DONE; +sStateTable[DONE][START] = DONE; +sStateTable[DONE][BLOCK] = DONE; +sStateTable[DONE][UNBLOCK] = DONE; +sStateTable[DONE][SLEEP] = DONE; +sStateTable[DONE][WAKEUP] = DONE; +sStateTable[DONE][CANCEL] = DONE; +sStateTable[DONE][FAIL] = ERROR; + +sStateTable[ERROR] = {}; +sStateTable[ERROR][STOP] = ERROR; +sStateTable[ERROR][START] = ERROR; +sStateTable[ERROR][BLOCK] = ERROR; +sStateTable[ERROR][UNBLOCK] = ERROR; +sStateTable[ERROR][SLEEP] = ERROR; +sStateTable[ERROR][WAKEUP] = ERROR; +sStateTable[ERROR][CANCEL] = ERROR; +sStateTable[ERROR][FAIL] = ERROR; + +/** + * Creates a new task. + * + * @param options options for this task + * run: the run function for the task (required) + * name: the run function for the task (optional) + * parent: parent of this task (optional) + * + * @return the empty task. + */ +var Task = function(options) { + // task id + this.id = -1; + + // task name + this.name = options.name || sNoTaskName; + + // task has no parent + this.parent = options.parent || null; + + // save run function + this.run = options.run; + + // create a queue of subtasks to run + this.subtasks = []; + + // error flag + this.error = false; + + // state of the task + this.state = READY; + + // number of times the task has been blocked (also the number + // of permits needed to be released to continue running) + this.blocks = 0; + + // timeout id when sleeping + this.timeoutId = null; + + // no swap time yet + this.swapTime = null; + + // no user data + this.userData = null; + + // initialize task + // FIXME: deal with overflow + this.id = sNextTaskId++; + sTasks[this.id] = this; + if(sVL >= 1) { + forge.log.verbose(cat, '[%s][%s] init', this.id, this.name, this); + } +}; + +/** + * Logs debug information on this task and the system state. + */ +Task.prototype.debug = function(msg) { + msg = msg || ''; + forge.log.debug(cat, msg, + '[%s][%s] task:', this.id, this.name, this, + 'subtasks:', this.subtasks.length, + 'queue:', sTaskQueues); +}; + +/** + * Adds a subtask to run after task.doNext() or task.fail() is called. + * + * @param name human readable name for this task (optional). + * @param subrun a function to run that takes the current task as + * its first parameter. + * + * @return the current task (useful for chaining next() calls). + */ +Task.prototype.next = function(name, subrun) { + // juggle parameters if it looks like no name is given + if(typeof(name) === 'function') { + subrun = name; + + // inherit parent's name + name = this.name; + } + // create subtask, set parent to this task, propagate callbacks + var subtask = new Task({ + run: subrun, + name: name, + parent: this + }); + // start subtasks running + subtask.state = RUNNING; + subtask.type = this.type; + subtask.successCallback = this.successCallback || null; + subtask.failureCallback = this.failureCallback || null; + + // queue a new subtask + this.subtasks.push(subtask); + + return this; +}; + +/** + * Adds subtasks to run in parallel after task.doNext() or task.fail() + * is called. + * + * @param name human readable name for this task (optional). + * @param subrun functions to run that take the current task as + * their first parameter. + * + * @return the current task (useful for chaining next() calls). + */ +Task.prototype.parallel = function(name, subrun) { + // juggle parameters if it looks like no name is given + if(forge.util.isArray(name)) { + subrun = name; + + // inherit parent's name + name = this.name; + } + // Wrap parallel tasks in a regular task so they are started at the + // proper time. + return this.next(name, function(task) { + // block waiting for subtasks + var ptask = task; + ptask.block(subrun.length); + + // we pass the iterator from the loop below as a parameter + // to a function because it is otherwise included in the + // closure and changes as the loop changes -- causing i + // to always be set to its highest value + var startParallelTask = function(pname, pi) { + forge.task.start({ + type: pname, + run: function(task) { + subrun[pi](task); + }, + success: function(task) { + ptask.unblock(); + }, + failure: function(task) { + ptask.unblock(); + } + }); + }; + + for(var i = 0; i < subrun.length; i++) { + // Type must be unique so task starts in parallel: + // name + private string + task id + sub-task index + // start tasks in parallel and unblock when the finish + var pname = name + '__parallel-' + task.id + '-' + i; + var pi = i; + startParallelTask(pname, pi); + } + }); +}; + +/** + * Stops a running task. + */ +Task.prototype.stop = function() { + this.state = sStateTable[this.state][STOP]; +}; + +/** + * Starts running a task. + */ +Task.prototype.start = function() { + this.error = false; + this.state = sStateTable[this.state][START]; + + // try to restart + if(this.state === RUNNING) { + this.start = new Date(); + this.run(this); + runNext(this, 0); + } +}; + +/** + * Blocks a task until it one or more permits have been released. The + * task will not resume until the requested number of permits have + * been released with call(s) to unblock(). + * + * @param n number of permits to wait for(default: 1). + */ +Task.prototype.block = function(n) { + n = typeof(n) === 'undefined' ? 1 : n; + this.blocks += n; + if(this.blocks > 0) { + this.state = sStateTable[this.state][BLOCK]; + } +}; + +/** + * Releases a permit to unblock a task. If a task was blocked by + * requesting N permits via block(), then it will only continue + * running once enough permits have been released via unblock() calls. + * + * If multiple processes need to synchronize with a single task then + * use a condition variable (see forge.task.createCondition). It is + * an error to unblock a task more times than it has been blocked. + * + * @param n number of permits to release (default: 1). + * + * @return the current block count (task is unblocked when count is 0) + */ +Task.prototype.unblock = function(n) { + n = typeof(n) === 'undefined' ? 1 : n; + this.blocks -= n; + if(this.blocks === 0 && this.state !== DONE) { + this.state = RUNNING; + runNext(this, 0); + } + return this.blocks; +}; + +/** + * Sleep for a period of time before resuming tasks. + * + * @param n number of milliseconds to sleep (default: 0). + */ +Task.prototype.sleep = function(n) { + n = typeof(n) === 'undefined' ? 0 : n; + this.state = sStateTable[this.state][SLEEP]; + var self = this; + this.timeoutId = setTimeout(function() { + self.timeoutId = null; + self.state = RUNNING; + runNext(self, 0); + }, n); +}; + +/** + * Waits on a condition variable until notified. The next task will + * not be scheduled until notification. A condition variable can be + * created with forge.task.createCondition(). + * + * Once cond.notify() is called, the task will continue. + * + * @param cond the condition variable to wait on. + */ +Task.prototype.wait = function(cond) { + cond.wait(this); +}; + +/** + * If sleeping, wakeup and continue running tasks. + */ +Task.prototype.wakeup = function() { + if(this.state === SLEEPING) { + cancelTimeout(this.timeoutId); + this.timeoutId = null; + this.state = RUNNING; + runNext(this, 0); + } +}; + +/** + * Cancel all remaining subtasks of this task. + */ +Task.prototype.cancel = function() { + this.state = sStateTable[this.state][CANCEL]; + // remove permits needed + this.permitsNeeded = 0; + // cancel timeouts + if(this.timeoutId !== null) { + cancelTimeout(this.timeoutId); + this.timeoutId = null; + } + // remove subtasks + this.subtasks = []; +}; + +/** + * Finishes this task with failure and sets error flag. The entire + * task will be aborted unless the next task that should execute + * is passed as a parameter. This allows levels of subtasks to be + * skipped. For instance, to abort only this tasks's subtasks, then + * call fail(task.parent). To abort this task's subtasks and its + * parent's subtasks, call fail(task.parent.parent). To abort + * all tasks and simply call the task callback, call fail() or + * fail(null). + * + * The task callback (success or failure) will always, eventually, be + * called. + * + * @param next the task to continue at, or null to abort entirely. + */ +Task.prototype.fail = function(next) { + // set error flag + this.error = true; + + // finish task + finish(this, true); + + if(next) { + // propagate task info + next.error = this.error; + next.swapTime = this.swapTime; + next.userData = this.userData; + + // do next task as specified + runNext(next, 0); + } else { + if(this.parent !== null) { + // finish root task (ensures it is removed from task queue) + var parent = this.parent; + while(parent.parent !== null) { + // propagate task info + parent.error = this.error; + parent.swapTime = this.swapTime; + parent.userData = this.userData; + parent = parent.parent; + } + finish(parent, true); + } + + // call failure callback if one exists + if(this.failureCallback) { + this.failureCallback(this); + } + } +}; + +/** + * Asynchronously start a task. + * + * @param task the task to start. + */ +var start = function(task) { + task.error = false; + task.state = sStateTable[task.state][START]; + setTimeout(function() { + if(task.state === RUNNING) { + task.swapTime = +new Date(); + task.run(task); + runNext(task, 0); + } + }, 0); +}; + +/** + * Run the next subtask or finish this task. + * + * @param task the task to process. + * @param recurse the recursion count. + */ +var runNext = function(task, recurse) { + // get time since last context swap (ms), if enough time has passed set + // swap to true to indicate that doNext was performed asynchronously + // also, if recurse is too high do asynchronously + var swap = + (recurse > sMaxRecursions) || + (+new Date() - task.swapTime) > sTimeSlice; + + var doNext = function(recurse) { + recurse++; + if(task.state === RUNNING) { + if(swap) { + // update swap time + task.swapTime = +new Date(); + } + + if(task.subtasks.length > 0) { + // run next subtask + var subtask = task.subtasks.shift(); + subtask.error = task.error; + subtask.swapTime = task.swapTime; + subtask.userData = task.userData; + subtask.run(subtask); + if(!subtask.error) { + runNext(subtask, recurse); + } + } else { + finish(task); + + if(!task.error) { + // chain back up and run parent + if(task.parent !== null) { + // propagate task info + task.parent.error = task.error; + task.parent.swapTime = task.swapTime; + task.parent.userData = task.userData; + + // no subtasks left, call run next subtask on parent + runNext(task.parent, recurse); + } + } + } + } + }; + + if(swap) { + // we're swapping, so run asynchronously + setTimeout(doNext, 0); + } else { + // not swapping, so run synchronously + doNext(recurse); + } +}; + +/** + * Finishes a task and looks for the next task in the queue to start. + * + * @param task the task to finish. + * @param suppressCallbacks true to suppress callbacks. + */ +var finish = function(task, suppressCallbacks) { + // subtask is now done + task.state = DONE; + + delete sTasks[task.id]; + if(sVL >= 1) { + forge.log.verbose(cat, '[%s][%s] finish', + task.id, task.name, task); + } + + // only do queue processing for root tasks + if(task.parent === null) { + // report error if queue is missing + if(!(task.type in sTaskQueues)) { + forge.log.error(cat, + '[%s][%s] task queue missing [%s]', + task.id, task.name, task.type); + } else if(sTaskQueues[task.type].length === 0) { + // report error if queue is empty + forge.log.error(cat, + '[%s][%s] task queue empty [%s]', + task.id, task.name, task.type); + } else if(sTaskQueues[task.type][0] !== task) { + // report error if this task isn't the first in the queue + forge.log.error(cat, + '[%s][%s] task not first in queue [%s]', + task.id, task.name, task.type); + } else { + // remove ourselves from the queue + sTaskQueues[task.type].shift(); + // clean up queue if it is empty + if(sTaskQueues[task.type].length === 0) { + if(sVL >= 1) { + forge.log.verbose(cat, '[%s][%s] delete queue [%s]', + task.id, task.name, task.type); + } + /* Note: Only a task can delete a queue of its own type. This + is used as a way to synchronize tasks. If a queue for a certain + task type exists, then a task of that type is running. + */ + delete sTaskQueues[task.type]; + } else { + // dequeue the next task and start it + if(sVL >= 1) { + forge.log.verbose(cat, + '[%s][%s] queue start next [%s] remain:%s', + task.id, task.name, task.type, + sTaskQueues[task.type].length); + } + sTaskQueues[task.type][0].start(); + } + } + + if(!suppressCallbacks) { + // call final callback if one exists + if(task.error && task.failureCallback) { + task.failureCallback(task); + } else if(!task.error && task.successCallback) { + task.successCallback(task); + } + } + } +}; + +/* Tasks API */ +module.exports = forge.task = forge.task || {}; + +/** + * Starts a new task that will run the passed function asynchronously. + * + * In order to finish the task, either task.doNext() or task.fail() + * *must* be called. + * + * The task must have a type (a string identifier) that can be used to + * synchronize it with other tasks of the same type. That type can also + * be used to cancel tasks that haven't started yet. + * + * To start a task, the following object must be provided as a parameter + * (each function takes a task object as its first parameter): + * + * { + * type: the type of task. + * run: the function to run to execute the task. + * success: a callback to call when the task succeeds (optional). + * failure: a callback to call when the task fails (optional). + * } + * + * @param options the object as described above. + */ +forge.task.start = function(options) { + // create a new task + var task = new Task({ + run: options.run, + name: options.name || sNoTaskName + }); + task.type = options.type; + task.successCallback = options.success || null; + task.failureCallback = options.failure || null; + + // append the task onto the appropriate queue + if(!(task.type in sTaskQueues)) { + if(sVL >= 1) { + forge.log.verbose(cat, '[%s][%s] create queue [%s]', + task.id, task.name, task.type); + } + // create the queue with the new task + sTaskQueues[task.type] = [task]; + start(task); + } else { + // push the task onto the queue, it will be run after a task + // with the same type completes + sTaskQueues[options.type].push(task); + } +}; + +/** + * Cancels all tasks of the given type that haven't started yet. + * + * @param type the type of task to cancel. + */ +forge.task.cancel = function(type) { + // find the task queue + if(type in sTaskQueues) { + // empty all but the current task from the queue + sTaskQueues[type] = [sTaskQueues[type][0]]; + } +}; + +/** + * Creates a condition variable to synchronize tasks. To make a task wait + * on the condition variable, call task.wait(condition). To notify all + * tasks that are waiting, call condition.notify(). + * + * @return the condition variable. + */ +forge.task.createCondition = function() { + var cond = { + // all tasks that are blocked + tasks: {} + }; + + /** + * Causes the given task to block until notify is called. If the task + * is already waiting on this condition then this is a no-op. + * + * @param task the task to cause to wait. + */ + cond.wait = function(task) { + // only block once + if(!(task.id in cond.tasks)) { + task.block(); + cond.tasks[task.id] = task; + } + }; + + /** + * Notifies all waiting tasks to wake up. + */ + cond.notify = function() { + // since unblock() will run the next task from here, make sure to + // clear the condition's blocked task list before unblocking + var tmp = cond.tasks; + cond.tasks = {}; + for(var id in tmp) { + tmp[id].unblock(); + } + }; + + return cond; +}; diff --git a/node_modules/node-forge/lib/tls.js b/node_modules/node-forge/lib/tls.js new file mode 100644 index 0000000..fadfd64 --- /dev/null +++ b/node_modules/node-forge/lib/tls.js @@ -0,0 +1,4282 @@ +/** + * A Javascript implementation of Transport Layer Security (TLS). + * + * @author Dave Longley + * + * Copyright (c) 2009-2014 Digital Bazaar, Inc. + * + * The TLS Handshake Protocol involves the following steps: + * + * - Exchange hello messages to agree on algorithms, exchange random values, + * and check for session resumption. + * + * - Exchange the necessary cryptographic parameters to allow the client and + * server to agree on a premaster secret. + * + * - Exchange certificates and cryptographic information to allow the client + * and server to authenticate themselves. + * + * - Generate a master secret from the premaster secret and exchanged random + * values. + * + * - Provide security parameters to the record layer. + * + * - Allow the client and server to verify that their peer has calculated the + * same security parameters and that the handshake occurred without tampering + * by an attacker. + * + * Up to 4 different messages may be sent during a key exchange. The server + * certificate, the server key exchange, the client certificate, and the + * client key exchange. + * + * A typical handshake (from the client's perspective). + * + * 1. Client sends ClientHello. + * 2. Client receives ServerHello. + * 3. Client receives optional Certificate. + * 4. Client receives optional ServerKeyExchange. + * 5. Client receives ServerHelloDone. + * 6. Client sends optional Certificate. + * 7. Client sends ClientKeyExchange. + * 8. Client sends optional CertificateVerify. + * 9. Client sends ChangeCipherSpec. + * 10. Client sends Finished. + * 11. Client receives ChangeCipherSpec. + * 12. Client receives Finished. + * 13. Client sends/receives application data. + * + * To reuse an existing session: + * + * 1. Client sends ClientHello with session ID for reuse. + * 2. Client receives ServerHello with same session ID if reusing. + * 3. Client receives ChangeCipherSpec message if reusing. + * 4. Client receives Finished. + * 5. Client sends ChangeCipherSpec. + * 6. Client sends Finished. + * + * Note: Client ignores HelloRequest if in the middle of a handshake. + * + * Record Layer: + * + * The record layer fragments information blocks into TLSPlaintext records + * carrying data in chunks of 2^14 bytes or less. Client message boundaries are + * not preserved in the record layer (i.e., multiple client messages of the + * same ContentType MAY be coalesced into a single TLSPlaintext record, or a + * single message MAY be fragmented across several records). + * + * struct { + * uint8 major; + * uint8 minor; + * } ProtocolVersion; + * + * struct { + * ContentType type; + * ProtocolVersion version; + * uint16 length; + * opaque fragment[TLSPlaintext.length]; + * } TLSPlaintext; + * + * type: + * The higher-level protocol used to process the enclosed fragment. + * + * version: + * The version of the protocol being employed. TLS Version 1.2 uses version + * {3, 3}. TLS Version 1.0 uses version {3, 1}. Note that a client that + * supports multiple versions of TLS may not know what version will be + * employed before it receives the ServerHello. + * + * length: + * The length (in bytes) of the following TLSPlaintext.fragment. The length + * MUST NOT exceed 2^14 = 16384 bytes. + * + * fragment: + * The application data. This data is transparent and treated as an + * independent block to be dealt with by the higher-level protocol specified + * by the type field. + * + * Implementations MUST NOT send zero-length fragments of Handshake, Alert, or + * ChangeCipherSpec content types. Zero-length fragments of Application data + * MAY be sent as they are potentially useful as a traffic analysis + * countermeasure. + * + * Note: Data of different TLS record layer content types MAY be interleaved. + * Application data is generally of lower precedence for transmission than + * other content types. However, records MUST be delivered to the network in + * the same order as they are protected by the record layer. Recipients MUST + * receive and process interleaved application layer traffic during handshakes + * subsequent to the first one on a connection. + * + * struct { + * ContentType type; // same as TLSPlaintext.type + * ProtocolVersion version;// same as TLSPlaintext.version + * uint16 length; + * opaque fragment[TLSCompressed.length]; + * } TLSCompressed; + * + * length: + * The length (in bytes) of the following TLSCompressed.fragment. + * The length MUST NOT exceed 2^14 + 1024. + * + * fragment: + * The compressed form of TLSPlaintext.fragment. + * + * Note: A CompressionMethod.null operation is an identity operation; no fields + * are altered. In this implementation, since no compression is supported, + * uncompressed records are always the same as compressed records. + * + * Encryption Information: + * + * The encryption and MAC functions translate a TLSCompressed structure into a + * TLSCiphertext. The decryption functions reverse the process. The MAC of the + * record also includes a sequence number so that missing, extra, or repeated + * messages are detectable. + * + * struct { + * ContentType type; + * ProtocolVersion version; + * uint16 length; + * select (SecurityParameters.cipher_type) { + * case stream: GenericStreamCipher; + * case block: GenericBlockCipher; + * case aead: GenericAEADCipher; + * } fragment; + * } TLSCiphertext; + * + * type: + * The type field is identical to TLSCompressed.type. + * + * version: + * The version field is identical to TLSCompressed.version. + * + * length: + * The length (in bytes) of the following TLSCiphertext.fragment. + * The length MUST NOT exceed 2^14 + 2048. + * + * fragment: + * The encrypted form of TLSCompressed.fragment, with the MAC. + * + * Note: Only CBC Block Ciphers are supported by this implementation. + * + * The TLSCompressed.fragment structures are converted to/from block + * TLSCiphertext.fragment structures. + * + * struct { + * opaque IV[SecurityParameters.record_iv_length]; + * block-ciphered struct { + * opaque content[TLSCompressed.length]; + * opaque MAC[SecurityParameters.mac_length]; + * uint8 padding[GenericBlockCipher.padding_length]; + * uint8 padding_length; + * }; + * } GenericBlockCipher; + * + * The MAC is generated as described in Section 6.2.3.1. + * + * IV: + * The Initialization Vector (IV) SHOULD be chosen at random, and MUST be + * unpredictable. Note that in versions of TLS prior to 1.1, there was no + * IV field, and the last ciphertext block of the previous record (the "CBC + * residue") was used as the IV. This was changed to prevent the attacks + * described in [CBCATT]. For block ciphers, the IV length is of length + * SecurityParameters.record_iv_length, which is equal to the + * SecurityParameters.block_size. + * + * padding: + * Padding that is added to force the length of the plaintext to be an + * integral multiple of the block cipher's block length. The padding MAY be + * any length up to 255 bytes, as long as it results in the + * TLSCiphertext.length being an integral multiple of the block length. + * Lengths longer than necessary might be desirable to frustrate attacks on + * a protocol that are based on analysis of the lengths of exchanged + * messages. Each uint8 in the padding data vector MUST be filled with the + * padding length value. The receiver MUST check this padding and MUST use + * the bad_record_mac alert to indicate padding errors. + * + * padding_length: + * The padding length MUST be such that the total size of the + * GenericBlockCipher structure is a multiple of the cipher's block length. + * Legal values range from zero to 255, inclusive. This length specifies the + * length of the padding field exclusive of the padding_length field itself. + * + * The encrypted data length (TLSCiphertext.length) is one more than the sum of + * SecurityParameters.block_length, TLSCompressed.length, + * SecurityParameters.mac_length, and padding_length. + * + * Example: If the block length is 8 bytes, the content length + * (TLSCompressed.length) is 61 bytes, and the MAC length is 20 bytes, then the + * length before padding is 82 bytes (this does not include the IV. Thus, the + * padding length modulo 8 must be equal to 6 in order to make the total length + * an even multiple of 8 bytes (the block length). The padding length can be + * 6, 14, 22, and so on, through 254. If the padding length were the minimum + * necessary, 6, the padding would be 6 bytes, each containing the value 6. + * Thus, the last 8 octets of the GenericBlockCipher before block encryption + * would be xx 06 06 06 06 06 06 06, where xx is the last octet of the MAC. + * + * Note: With block ciphers in CBC mode (Cipher Block Chaining), it is critical + * that the entire plaintext of the record be known before any ciphertext is + * transmitted. Otherwise, it is possible for the attacker to mount the attack + * described in [CBCATT]. + * + * Implementation note: Canvel et al. [CBCTIME] have demonstrated a timing + * attack on CBC padding based on the time required to compute the MAC. In + * order to defend against this attack, implementations MUST ensure that + * record processing time is essentially the same whether or not the padding + * is correct. In general, the best way to do this is to compute the MAC even + * if the padding is incorrect, and only then reject the packet. For instance, + * if the pad appears to be incorrect, the implementation might assume a + * zero-length pad and then compute the MAC. This leaves a small timing + * channel, since MAC performance depends, to some extent, on the size of the + * data fragment, but it is not believed to be large enough to be exploitable, + * due to the large block size of existing MACs and the small size of the + * timing signal. + */ +var forge = require('./forge'); +require('./asn1'); +require('./hmac'); +require('./md5'); +require('./pem'); +require('./pki'); +require('./random'); +require('./sha1'); +require('./util'); + +/** + * Generates pseudo random bytes by mixing the result of two hash functions, + * MD5 and SHA-1. + * + * prf_TLS1(secret, label, seed) = + * P_MD5(S1, label + seed) XOR P_SHA-1(S2, label + seed); + * + * Each P_hash function functions as follows: + * + * P_hash(secret, seed) = HMAC_hash(secret, A(1) + seed) + + * HMAC_hash(secret, A(2) + seed) + + * HMAC_hash(secret, A(3) + seed) + ... + * A() is defined as: + * A(0) = seed + * A(i) = HMAC_hash(secret, A(i-1)) + * + * The '+' operator denotes concatenation. + * + * As many iterations A(N) as are needed are performed to generate enough + * pseudo random byte output. If an iteration creates more data than is + * necessary, then it is truncated. + * + * Therefore: + * A(1) = HMAC_hash(secret, A(0)) + * = HMAC_hash(secret, seed) + * A(2) = HMAC_hash(secret, A(1)) + * = HMAC_hash(secret, HMAC_hash(secret, seed)) + * + * Therefore: + * P_hash(secret, seed) = + * HMAC_hash(secret, HMAC_hash(secret, A(0)) + seed) + + * HMAC_hash(secret, HMAC_hash(secret, A(1)) + seed) + + * ... + * + * Therefore: + * P_hash(secret, seed) = + * HMAC_hash(secret, HMAC_hash(secret, seed) + seed) + + * HMAC_hash(secret, HMAC_hash(secret, HMAC_hash(secret, seed)) + seed) + + * ... + * + * @param secret the secret to use. + * @param label the label to use. + * @param seed the seed value to use. + * @param length the number of bytes to generate. + * + * @return the pseudo random bytes in a byte buffer. + */ +var prf_TLS1 = function(secret, label, seed, length) { + var rval = forge.util.createBuffer(); + + /* For TLS 1.0, the secret is split in half, into two secrets of equal + length. If the secret has an odd length then the last byte of the first + half will be the same as the first byte of the second. The length of the + two secrets is half of the secret rounded up. */ + var idx = (secret.length >> 1); + var slen = idx + (secret.length & 1); + var s1 = secret.substr(0, slen); + var s2 = secret.substr(idx, slen); + var ai = forge.util.createBuffer(); + var hmac = forge.hmac.create(); + seed = label + seed; + + // determine the number of iterations that must be performed to generate + // enough output bytes, md5 creates 16 byte hashes, sha1 creates 20 + var md5itr = Math.ceil(length / 16); + var sha1itr = Math.ceil(length / 20); + + // do md5 iterations + hmac.start('MD5', s1); + var md5bytes = forge.util.createBuffer(); + ai.putBytes(seed); + for(var i = 0; i < md5itr; ++i) { + // HMAC_hash(secret, A(i-1)) + hmac.start(null, null); + hmac.update(ai.getBytes()); + ai.putBuffer(hmac.digest()); + + // HMAC_hash(secret, A(i) + seed) + hmac.start(null, null); + hmac.update(ai.bytes() + seed); + md5bytes.putBuffer(hmac.digest()); + } + + // do sha1 iterations + hmac.start('SHA1', s2); + var sha1bytes = forge.util.createBuffer(); + ai.clear(); + ai.putBytes(seed); + for(var i = 0; i < sha1itr; ++i) { + // HMAC_hash(secret, A(i-1)) + hmac.start(null, null); + hmac.update(ai.getBytes()); + ai.putBuffer(hmac.digest()); + + // HMAC_hash(secret, A(i) + seed) + hmac.start(null, null); + hmac.update(ai.bytes() + seed); + sha1bytes.putBuffer(hmac.digest()); + } + + // XOR the md5 bytes with the sha1 bytes + rval.putBytes(forge.util.xorBytes( + md5bytes.getBytes(), sha1bytes.getBytes(), length)); + + return rval; +}; + +/** + * Generates pseudo random bytes using a SHA256 algorithm. For TLS 1.2. + * + * @param secret the secret to use. + * @param label the label to use. + * @param seed the seed value to use. + * @param length the number of bytes to generate. + * + * @return the pseudo random bytes in a byte buffer. + */ +var prf_sha256 = function(secret, label, seed, length) { + // FIXME: implement me for TLS 1.2 +}; + +/** + * Gets a MAC for a record using the SHA-1 hash algorithm. + * + * @param key the mac key. + * @param state the sequence number (array of two 32-bit integers). + * @param record the record. + * + * @return the sha-1 hash (20 bytes) for the given record. + */ +var hmac_sha1 = function(key, seqNum, record) { + /* MAC is computed like so: + HMAC_hash( + key, seqNum + + TLSCompressed.type + + TLSCompressed.version + + TLSCompressed.length + + TLSCompressed.fragment) + */ + var hmac = forge.hmac.create(); + hmac.start('SHA1', key); + var b = forge.util.createBuffer(); + b.putInt32(seqNum[0]); + b.putInt32(seqNum[1]); + b.putByte(record.type); + b.putByte(record.version.major); + b.putByte(record.version.minor); + b.putInt16(record.length); + b.putBytes(record.fragment.bytes()); + hmac.update(b.getBytes()); + return hmac.digest().getBytes(); +}; + +/** + * Compresses the TLSPlaintext record into a TLSCompressed record using the + * deflate algorithm. + * + * @param c the TLS connection. + * @param record the TLSPlaintext record to compress. + * @param s the ConnectionState to use. + * + * @return true on success, false on failure. + */ +var deflate = function(c, record, s) { + var rval = false; + + try { + var bytes = c.deflate(record.fragment.getBytes()); + record.fragment = forge.util.createBuffer(bytes); + record.length = bytes.length; + rval = true; + } catch(ex) { + // deflate error, fail out + } + + return rval; +}; + +/** + * Decompresses the TLSCompressed record into a TLSPlaintext record using the + * deflate algorithm. + * + * @param c the TLS connection. + * @param record the TLSCompressed record to decompress. + * @param s the ConnectionState to use. + * + * @return true on success, false on failure. + */ +var inflate = function(c, record, s) { + var rval = false; + + try { + var bytes = c.inflate(record.fragment.getBytes()); + record.fragment = forge.util.createBuffer(bytes); + record.length = bytes.length; + rval = true; + } catch(ex) { + // inflate error, fail out + } + + return rval; +}; + +/** + * Reads a TLS variable-length vector from a byte buffer. + * + * Variable-length vectors are defined by specifying a subrange of legal + * lengths, inclusively, using the notation . When these are + * encoded, the actual length precedes the vector's contents in the byte + * stream. The length will be in the form of a number consuming as many bytes + * as required to hold the vector's specified maximum (ceiling) length. A + * variable-length vector with an actual length field of zero is referred to + * as an empty vector. + * + * @param b the byte buffer. + * @param lenBytes the number of bytes required to store the length. + * + * @return the resulting byte buffer. + */ +var readVector = function(b, lenBytes) { + var len = 0; + switch(lenBytes) { + case 1: + len = b.getByte(); + break; + case 2: + len = b.getInt16(); + break; + case 3: + len = b.getInt24(); + break; + case 4: + len = b.getInt32(); + break; + } + + // read vector bytes into a new buffer + return forge.util.createBuffer(b.getBytes(len)); +}; + +/** + * Writes a TLS variable-length vector to a byte buffer. + * + * @param b the byte buffer. + * @param lenBytes the number of bytes required to store the length. + * @param v the byte buffer vector. + */ +var writeVector = function(b, lenBytes, v) { + // encode length at the start of the vector, where the number of bytes for + // the length is the maximum number of bytes it would take to encode the + // vector's ceiling + b.putInt(v.length(), lenBytes << 3); + b.putBuffer(v); +}; + +/** + * The tls implementation. + */ +var tls = {}; + +/** + * Version: TLS 1.2 = 3.3, TLS 1.1 = 3.2, TLS 1.0 = 3.1. Both TLS 1.1 and + * TLS 1.2 were still too new (ie: openSSL didn't implement them) at the time + * of this implementation so TLS 1.0 was implemented instead. + */ +tls.Versions = { + TLS_1_0: {major: 3, minor: 1}, + TLS_1_1: {major: 3, minor: 2}, + TLS_1_2: {major: 3, minor: 3} +}; +tls.SupportedVersions = [ + tls.Versions.TLS_1_1, + tls.Versions.TLS_1_0 +]; +tls.Version = tls.SupportedVersions[0]; + +/** + * Maximum fragment size. True maximum is 16384, but we fragment before that + * to allow for unusual small increases during compression. + */ +tls.MaxFragment = 16384 - 1024; + +/** + * Whether this entity is considered the "client" or "server". + * enum { server, client } ConnectionEnd; + */ +tls.ConnectionEnd = { + server: 0, + client: 1 +}; + +/** + * Pseudo-random function algorithm used to generate keys from the master + * secret. + * enum { tls_prf_sha256 } PRFAlgorithm; + */ +tls.PRFAlgorithm = { + tls_prf_sha256: 0 +}; + +/** + * Bulk encryption algorithms. + * enum { null, rc4, des3, aes } BulkCipherAlgorithm; + */ +tls.BulkCipherAlgorithm = { + none: null, + rc4: 0, + des3: 1, + aes: 2 +}; + +/** + * Cipher types. + * enum { stream, block, aead } CipherType; + */ +tls.CipherType = { + stream: 0, + block: 1, + aead: 2 +}; + +/** + * MAC (Message Authentication Code) algorithms. + * enum { null, hmac_md5, hmac_sha1, hmac_sha256, + * hmac_sha384, hmac_sha512} MACAlgorithm; + */ +tls.MACAlgorithm = { + none: null, + hmac_md5: 0, + hmac_sha1: 1, + hmac_sha256: 2, + hmac_sha384: 3, + hmac_sha512: 4 +}; + +/** + * Compression algorithms. + * enum { null(0), deflate(1), (255) } CompressionMethod; + */ +tls.CompressionMethod = { + none: 0, + deflate: 1 +}; + +/** + * TLS record content types. + * enum { + * change_cipher_spec(20), alert(21), handshake(22), + * application_data(23), (255) + * } ContentType; + */ +tls.ContentType = { + change_cipher_spec: 20, + alert: 21, + handshake: 22, + application_data: 23, + heartbeat: 24 +}; + +/** + * TLS handshake types. + * enum { + * hello_request(0), client_hello(1), server_hello(2), + * certificate(11), server_key_exchange (12), + * certificate_request(13), server_hello_done(14), + * certificate_verify(15), client_key_exchange(16), + * finished(20), (255) + * } HandshakeType; + */ +tls.HandshakeType = { + hello_request: 0, + client_hello: 1, + server_hello: 2, + certificate: 11, + server_key_exchange: 12, + certificate_request: 13, + server_hello_done: 14, + certificate_verify: 15, + client_key_exchange: 16, + finished: 20 +}; + +/** + * TLS Alert Protocol. + * + * enum { warning(1), fatal(2), (255) } AlertLevel; + * + * enum { + * close_notify(0), + * unexpected_message(10), + * bad_record_mac(20), + * decryption_failed(21), + * record_overflow(22), + * decompression_failure(30), + * handshake_failure(40), + * bad_certificate(42), + * unsupported_certificate(43), + * certificate_revoked(44), + * certificate_expired(45), + * certificate_unknown(46), + * illegal_parameter(47), + * unknown_ca(48), + * access_denied(49), + * decode_error(50), + * decrypt_error(51), + * export_restriction(60), + * protocol_version(70), + * insufficient_security(71), + * internal_error(80), + * user_canceled(90), + * no_renegotiation(100), + * (255) + * } AlertDescription; + * + * struct { + * AlertLevel level; + * AlertDescription description; + * } Alert; + */ +tls.Alert = {}; +tls.Alert.Level = { + warning: 1, + fatal: 2 +}; +tls.Alert.Description = { + close_notify: 0, + unexpected_message: 10, + bad_record_mac: 20, + decryption_failed: 21, + record_overflow: 22, + decompression_failure: 30, + handshake_failure: 40, + bad_certificate: 42, + unsupported_certificate: 43, + certificate_revoked: 44, + certificate_expired: 45, + certificate_unknown: 46, + illegal_parameter: 47, + unknown_ca: 48, + access_denied: 49, + decode_error: 50, + decrypt_error: 51, + export_restriction: 60, + protocol_version: 70, + insufficient_security: 71, + internal_error: 80, + user_canceled: 90, + no_renegotiation: 100 +}; + +/** + * TLS Heartbeat Message types. + * enum { + * heartbeat_request(1), + * heartbeat_response(2), + * (255) + * } HeartbeatMessageType; + */ +tls.HeartbeatMessageType = { + heartbeat_request: 1, + heartbeat_response: 2 +}; + +/** + * Supported cipher suites. + */ +tls.CipherSuites = {}; + +/** + * Gets a supported cipher suite from its 2 byte ID. + * + * @param twoBytes two bytes in a string. + * + * @return the matching supported cipher suite or null. + */ +tls.getCipherSuite = function(twoBytes) { + var rval = null; + for(var key in tls.CipherSuites) { + var cs = tls.CipherSuites[key]; + if(cs.id[0] === twoBytes.charCodeAt(0) && + cs.id[1] === twoBytes.charCodeAt(1)) { + rval = cs; + break; + } + } + return rval; +}; + +/** + * Called when an unexpected record is encountered. + * + * @param c the connection. + * @param record the record. + */ +tls.handleUnexpected = function(c, record) { + // if connection is client and closed, ignore unexpected messages + var ignore = (!c.open && c.entity === tls.ConnectionEnd.client); + if(!ignore) { + c.error(c, { + message: 'Unexpected message. Received TLS record out of order.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.unexpected_message + } + }); + } +}; + +/** + * Called when a client receives a HelloRequest record. + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. + */ +tls.handleHelloRequest = function(c, record, length) { + // ignore renegotiation requests from the server during a handshake, but + // if handshaking, send a warning alert that renegotation is denied + if(!c.handshaking && c.handshakes > 0) { + // send alert warning + tls.queue(c, tls.createAlert(c, { + level: tls.Alert.Level.warning, + description: tls.Alert.Description.no_renegotiation + })); + tls.flush(c); + } + + // continue + c.process(); +}; + +/** + * Parses a hello message from a ClientHello or ServerHello record. + * + * @param record the record to parse. + * + * @return the parsed message. + */ +tls.parseHelloMessage = function(c, record, length) { + var msg = null; + + var client = (c.entity === tls.ConnectionEnd.client); + + // minimum of 38 bytes in message + if(length < 38) { + c.error(c, { + message: client ? + 'Invalid ServerHello message. Message too short.' : + 'Invalid ClientHello message. Message too short.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } + }); + } else { + // use 'remaining' to calculate # of remaining bytes in the message + var b = record.fragment; + var remaining = b.length(); + msg = { + version: { + major: b.getByte(), + minor: b.getByte() + }, + random: forge.util.createBuffer(b.getBytes(32)), + session_id: readVector(b, 1), + extensions: [] + }; + if(client) { + msg.cipher_suite = b.getBytes(2); + msg.compression_method = b.getByte(); + } else { + msg.cipher_suites = readVector(b, 2); + msg.compression_methods = readVector(b, 1); + } + + // read extensions if there are any bytes left in the message + remaining = length - (remaining - b.length()); + if(remaining > 0) { + // parse extensions + var exts = readVector(b, 2); + while(exts.length() > 0) { + msg.extensions.push({ + type: [exts.getByte(), exts.getByte()], + data: readVector(exts, 2) + }); + } + + // TODO: make extension support modular + if(!client) { + for(var i = 0; i < msg.extensions.length; ++i) { + var ext = msg.extensions[i]; + + // support SNI extension + if(ext.type[0] === 0x00 && ext.type[1] === 0x00) { + // get server name list + var snl = readVector(ext.data, 2); + while(snl.length() > 0) { + // read server name type + var snType = snl.getByte(); + + // only HostName type (0x00) is known, break out if + // another type is detected + if(snType !== 0x00) { + break; + } + + // add host name to server name list + c.session.extensions.server_name.serverNameList.push( + readVector(snl, 2).getBytes()); + } + } + } + } + } + + // version already set, do not allow version change + if(c.session.version) { + if(msg.version.major !== c.session.version.major || + msg.version.minor !== c.session.version.minor) { + return c.error(c, { + message: 'TLS version change is disallowed during renegotiation.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.protocol_version + } + }); + } + } + + // get the chosen (ServerHello) cipher suite + if(client) { + // FIXME: should be checking configured acceptable cipher suites + c.session.cipherSuite = tls.getCipherSuite(msg.cipher_suite); + } else { + // get a supported preferred (ClientHello) cipher suite + // choose the first supported cipher suite + var tmp = forge.util.createBuffer(msg.cipher_suites.bytes()); + while(tmp.length() > 0) { + // FIXME: should be checking configured acceptable suites + // cipher suites take up 2 bytes + c.session.cipherSuite = tls.getCipherSuite(tmp.getBytes(2)); + if(c.session.cipherSuite !== null) { + break; + } + } + } + + // cipher suite not supported + if(c.session.cipherSuite === null) { + return c.error(c, { + message: 'No cipher suites in common.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.handshake_failure + }, + cipherSuite: forge.util.bytesToHex(msg.cipher_suite) + }); + } + + // TODO: handle compression methods + if(client) { + c.session.compressionMethod = msg.compression_method; + } else { + // no compression + c.session.compressionMethod = tls.CompressionMethod.none; + } + } + + return msg; +}; + +/** + * Creates security parameters for the given connection based on the given + * hello message. + * + * @param c the TLS connection. + * @param msg the hello message. + */ +tls.createSecurityParameters = function(c, msg) { + /* Note: security params are from TLS 1.2, some values like prf_algorithm + are ignored for TLS 1.0/1.1 and the builtin as specified in the spec is + used. */ + + // TODO: handle other options from server when more supported + + // get client and server randoms + var client = (c.entity === tls.ConnectionEnd.client); + var msgRandom = msg.random.bytes(); + var cRandom = client ? c.session.sp.client_random : msgRandom; + var sRandom = client ? msgRandom : tls.createRandom().getBytes(); + + // create new security parameters + c.session.sp = { + entity: c.entity, + prf_algorithm: tls.PRFAlgorithm.tls_prf_sha256, + bulk_cipher_algorithm: null, + cipher_type: null, + enc_key_length: null, + block_length: null, + fixed_iv_length: null, + record_iv_length: null, + mac_algorithm: null, + mac_length: null, + mac_key_length: null, + compression_algorithm: c.session.compressionMethod, + pre_master_secret: null, + master_secret: null, + client_random: cRandom, + server_random: sRandom + }; +}; + +/** + * Called when a client receives a ServerHello record. + * + * When a ServerHello message will be sent: + * The server will send this message in response to a client hello message + * when it was able to find an acceptable set of algorithms. If it cannot + * find such a match, it will respond with a handshake failure alert. + * + * uint24 length; + * struct { + * ProtocolVersion server_version; + * Random random; + * SessionID session_id; + * CipherSuite cipher_suite; + * CompressionMethod compression_method; + * select(extensions_present) { + * case false: + * struct {}; + * case true: + * Extension extensions<0..2^16-1>; + * }; + * } ServerHello; + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. + */ +tls.handleServerHello = function(c, record, length) { + var msg = tls.parseHelloMessage(c, record, length); + if(c.fail) { + return; + } + + // ensure server version is compatible + if(msg.version.minor <= c.version.minor) { + c.version.minor = msg.version.minor; + } else { + return c.error(c, { + message: 'Incompatible TLS version.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.protocol_version + } + }); + } + + // indicate session version has been set + c.session.version = c.version; + + // get the session ID from the message + var sessionId = msg.session_id.bytes(); + + // if the session ID is not blank and matches the cached one, resume + // the session + if(sessionId.length > 0 && sessionId === c.session.id) { + // resuming session, expect a ChangeCipherSpec next + c.expect = SCC; + c.session.resuming = true; + + // get new server random + c.session.sp.server_random = msg.random.bytes(); + } else { + // not resuming, expect a server Certificate message next + c.expect = SCE; + c.session.resuming = false; + + // create new security parameters + tls.createSecurityParameters(c, msg); + } + + // set new session ID + c.session.id = sessionId; + + // continue + c.process(); +}; + +/** + * Called when a server receives a ClientHello record. + * + * When a ClientHello message will be sent: + * When a client first connects to a server it is required to send the + * client hello as its first message. The client can also send a client + * hello in response to a hello request or on its own initiative in order + * to renegotiate the security parameters in an existing connection. + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. + */ +tls.handleClientHello = function(c, record, length) { + var msg = tls.parseHelloMessage(c, record, length); + if(c.fail) { + return; + } + + // get the session ID from the message + var sessionId = msg.session_id.bytes(); + + // see if the given session ID is in the cache + var session = null; + if(c.sessionCache) { + session = c.sessionCache.getSession(sessionId); + if(session === null) { + // session ID not found + sessionId = ''; + } else if(session.version.major !== msg.version.major || + session.version.minor > msg.version.minor) { + // if session version is incompatible with client version, do not resume + session = null; + sessionId = ''; + } + } + + // no session found to resume, generate a new session ID + if(sessionId.length === 0) { + sessionId = forge.random.getBytes(32); + } + + // update session + c.session.id = sessionId; + c.session.clientHelloVersion = msg.version; + c.session.sp = {}; + if(session) { + // use version and security parameters from resumed session + c.version = c.session.version = session.version; + c.session.sp = session.sp; + } else { + // use highest compatible minor version + var version; + for(var i = 1; i < tls.SupportedVersions.length; ++i) { + version = tls.SupportedVersions[i]; + if(version.minor <= msg.version.minor) { + break; + } + } + c.version = {major: version.major, minor: version.minor}; + c.session.version = c.version; + } + + // if a session is set, resume it + if(session !== null) { + // resuming session, expect a ChangeCipherSpec next + c.expect = CCC; + c.session.resuming = true; + + // get new client random + c.session.sp.client_random = msg.random.bytes(); + } else { + // not resuming, expect a Certificate or ClientKeyExchange + c.expect = (c.verifyClient !== false) ? CCE : CKE; + c.session.resuming = false; + + // create new security parameters + tls.createSecurityParameters(c, msg); + } + + // connection now open + c.open = true; + + // queue server hello + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createServerHello(c) + })); + + if(c.session.resuming) { + // queue change cipher spec message + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.change_cipher_spec, + data: tls.createChangeCipherSpec() + })); + + // create pending state + c.state.pending = tls.createConnectionState(c); + + // change current write state to pending write state + c.state.current.write = c.state.pending.write; + + // queue finished + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createFinished(c) + })); + } else { + // queue server certificate + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createCertificate(c) + })); + + if(!c.fail) { + // queue server key exchange + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createServerKeyExchange(c) + })); + + // request client certificate if set + if(c.verifyClient !== false) { + // queue certificate request + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createCertificateRequest(c) + })); + } + + // queue server hello done + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createServerHelloDone(c) + })); + } + } + + // send records + tls.flush(c); + + // continue + c.process(); +}; + +/** + * Called when a client receives a Certificate record. + * + * When this message will be sent: + * The server must send a certificate whenever the agreed-upon key exchange + * method is not an anonymous one. This message will always immediately + * follow the server hello message. + * + * Meaning of this message: + * The certificate type must be appropriate for the selected cipher suite's + * key exchange algorithm, and is generally an X.509v3 certificate. It must + * contain a key which matches the key exchange method, as follows. Unless + * otherwise specified, the signing algorithm for the certificate must be + * the same as the algorithm for the certificate key. Unless otherwise + * specified, the public key may be of any length. + * + * opaque ASN.1Cert<1..2^24-1>; + * struct { + * ASN.1Cert certificate_list<1..2^24-1>; + * } Certificate; + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. + */ +tls.handleCertificate = function(c, record, length) { + // minimum of 3 bytes in message + if(length < 3) { + return c.error(c, { + message: 'Invalid Certificate message. Message too short.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } + }); + } + + var b = record.fragment; + var msg = { + certificate_list: readVector(b, 3) + }; + + /* The sender's certificate will be first in the list (chain), each + subsequent one that follows will certify the previous one, but root + certificates (self-signed) that specify the certificate authority may + be omitted under the assumption that clients must already possess it. */ + var cert, asn1; + var certs = []; + try { + while(msg.certificate_list.length() > 0) { + // each entry in msg.certificate_list is a vector with 3 len bytes + cert = readVector(msg.certificate_list, 3); + asn1 = forge.asn1.fromDer(cert); + cert = forge.pki.certificateFromAsn1(asn1, true); + certs.push(cert); + } + } catch(ex) { + return c.error(c, { + message: 'Could not parse certificate list.', + cause: ex, + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.bad_certificate + } + }); + } + + // ensure at least 1 certificate was provided if in client-mode + // or if verifyClient was set to true to require a certificate + // (as opposed to 'optional') + var client = (c.entity === tls.ConnectionEnd.client); + if((client || c.verifyClient === true) && certs.length === 0) { + // error, no certificate + c.error(c, { + message: client ? + 'No server certificate provided.' : + 'No client certificate provided.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } + }); + } else if(certs.length === 0) { + // no certs to verify + // expect a ServerKeyExchange or ClientKeyExchange message next + c.expect = client ? SKE : CKE; + } else { + // save certificate in session + if(client) { + c.session.serverCertificate = certs[0]; + } else { + c.session.clientCertificate = certs[0]; + } + + if(tls.verifyCertificateChain(c, certs)) { + // expect a ServerKeyExchange or ClientKeyExchange message next + c.expect = client ? SKE : CKE; + } + } + + // continue + c.process(); +}; + +/** + * Called when a client receives a ServerKeyExchange record. + * + * When this message will be sent: + * This message will be sent immediately after the server certificate + * message (or the server hello message, if this is an anonymous + * negotiation). + * + * The server key exchange message is sent by the server only when the + * server certificate message (if sent) does not contain enough data to + * allow the client to exchange a premaster secret. + * + * Meaning of this message: + * This message conveys cryptographic information to allow the client to + * communicate the premaster secret: either an RSA public key to encrypt + * the premaster secret with, or a Diffie-Hellman public key with which the + * client can complete a key exchange (with the result being the premaster + * secret.) + * + * enum { + * dhe_dss, dhe_rsa, dh_anon, rsa, dh_dss, dh_rsa + * } KeyExchangeAlgorithm; + * + * struct { + * opaque dh_p<1..2^16-1>; + * opaque dh_g<1..2^16-1>; + * opaque dh_Ys<1..2^16-1>; + * } ServerDHParams; + * + * struct { + * select(KeyExchangeAlgorithm) { + * case dh_anon: + * ServerDHParams params; + * case dhe_dss: + * case dhe_rsa: + * ServerDHParams params; + * digitally-signed struct { + * opaque client_random[32]; + * opaque server_random[32]; + * ServerDHParams params; + * } signed_params; + * case rsa: + * case dh_dss: + * case dh_rsa: + * struct {}; + * }; + * } ServerKeyExchange; + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. + */ +tls.handleServerKeyExchange = function(c, record, length) { + // this implementation only supports RSA, no Diffie-Hellman support + // so any length > 0 is invalid + if(length > 0) { + return c.error(c, { + message: 'Invalid key parameters. Only RSA is supported.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.unsupported_certificate + } + }); + } + + // expect an optional CertificateRequest message next + c.expect = SCR; + + // continue + c.process(); +}; + +/** + * Called when a client receives a ClientKeyExchange record. + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. + */ +tls.handleClientKeyExchange = function(c, record, length) { + // this implementation only supports RSA, no Diffie-Hellman support + // so any length < 48 is invalid + if(length < 48) { + return c.error(c, { + message: 'Invalid key parameters. Only RSA is supported.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.unsupported_certificate + } + }); + } + + var b = record.fragment; + var msg = { + enc_pre_master_secret: readVector(b, 2).getBytes() + }; + + // do rsa decryption + var privateKey = null; + if(c.getPrivateKey) { + try { + privateKey = c.getPrivateKey(c, c.session.serverCertificate); + privateKey = forge.pki.privateKeyFromPem(privateKey); + } catch(ex) { + c.error(c, { + message: 'Could not get private key.', + cause: ex, + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error + } + }); + } + } + + if(privateKey === null) { + return c.error(c, { + message: 'No private key set.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error + } + }); + } + + try { + // decrypt 48-byte pre-master secret + var sp = c.session.sp; + sp.pre_master_secret = privateKey.decrypt(msg.enc_pre_master_secret); + + // ensure client hello version matches first 2 bytes + var version = c.session.clientHelloVersion; + if(version.major !== sp.pre_master_secret.charCodeAt(0) || + version.minor !== sp.pre_master_secret.charCodeAt(1)) { + // error, do not send alert (see BLEI attack below) + throw new Error('TLS version rollback attack detected.'); + } + } catch(ex) { + /* Note: Daniel Bleichenbacher [BLEI] can be used to attack a + TLS server which is using PKCS#1 encoded RSA, so instead of + failing here, we generate 48 random bytes and use that as + the pre-master secret. */ + sp.pre_master_secret = forge.random.getBytes(48); + } + + // expect a CertificateVerify message if a Certificate was received that + // does not have fixed Diffie-Hellman params, otherwise expect + // ChangeCipherSpec + c.expect = CCC; + if(c.session.clientCertificate !== null) { + // only RSA support, so expect CertificateVerify + // TODO: support Diffie-Hellman + c.expect = CCV; + } + + // continue + c.process(); +}; + +/** + * Called when a client receives a CertificateRequest record. + * + * When this message will be sent: + * A non-anonymous server can optionally request a certificate from the + * client, if appropriate for the selected cipher suite. This message, if + * sent, will immediately follow the Server Key Exchange message (if it is + * sent; otherwise, the Server Certificate message). + * + * enum { + * rsa_sign(1), dss_sign(2), rsa_fixed_dh(3), dss_fixed_dh(4), + * rsa_ephemeral_dh_RESERVED(5), dss_ephemeral_dh_RESERVED(6), + * fortezza_dms_RESERVED(20), (255) + * } ClientCertificateType; + * + * opaque DistinguishedName<1..2^16-1>; + * + * struct { + * ClientCertificateType certificate_types<1..2^8-1>; + * SignatureAndHashAlgorithm supported_signature_algorithms<2^16-1>; + * DistinguishedName certificate_authorities<0..2^16-1>; + * } CertificateRequest; + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. + */ +tls.handleCertificateRequest = function(c, record, length) { + // minimum of 3 bytes in message + if(length < 3) { + return c.error(c, { + message: 'Invalid CertificateRequest. Message too short.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } + }); + } + + // TODO: TLS 1.2+ has different format including + // SignatureAndHashAlgorithm after cert types + var b = record.fragment; + var msg = { + certificate_types: readVector(b, 1), + certificate_authorities: readVector(b, 2) + }; + + // save certificate request in session + c.session.certificateRequest = msg; + + // expect a ServerHelloDone message next + c.expect = SHD; + + // continue + c.process(); +}; + +/** + * Called when a server receives a CertificateVerify record. + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. + */ +tls.handleCertificateVerify = function(c, record, length) { + if(length < 2) { + return c.error(c, { + message: 'Invalid CertificateVerify. Message too short.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } + }); + } + + // rewind to get full bytes for message so it can be manually + // digested below (special case for CertificateVerify messages because + // they must be digested *after* handling as opposed to all others) + var b = record.fragment; + b.read -= 4; + var msgBytes = b.bytes(); + b.read += 4; + + var msg = { + signature: readVector(b, 2).getBytes() + }; + + // TODO: add support for DSA + + // generate data to verify + var verify = forge.util.createBuffer(); + verify.putBuffer(c.session.md5.digest()); + verify.putBuffer(c.session.sha1.digest()); + verify = verify.getBytes(); + + try { + var cert = c.session.clientCertificate; + /*b = forge.pki.rsa.decrypt( + msg.signature, cert.publicKey, true, verify.length); + if(b !== verify) {*/ + if(!cert.publicKey.verify(verify, msg.signature, 'NONE')) { + throw new Error('CertificateVerify signature does not match.'); + } + + // digest message now that it has been handled + c.session.md5.update(msgBytes); + c.session.sha1.update(msgBytes); + } catch(ex) { + return c.error(c, { + message: 'Bad signature in CertificateVerify.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.handshake_failure + } + }); + } + + // expect ChangeCipherSpec + c.expect = CCC; + + // continue + c.process(); +}; + +/** + * Called when a client receives a ServerHelloDone record. + * + * When this message will be sent: + * The server hello done message is sent by the server to indicate the end + * of the server hello and associated messages. After sending this message + * the server will wait for a client response. + * + * Meaning of this message: + * This message means that the server is done sending messages to support + * the key exchange, and the client can proceed with its phase of the key + * exchange. + * + * Upon receipt of the server hello done message the client should verify + * that the server provided a valid certificate if required and check that + * the server hello parameters are acceptable. + * + * struct {} ServerHelloDone; + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. + */ +tls.handleServerHelloDone = function(c, record, length) { + // len must be 0 bytes + if(length > 0) { + return c.error(c, { + message: 'Invalid ServerHelloDone message. Invalid length.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.record_overflow + } + }); + } + + if(c.serverCertificate === null) { + // no server certificate was provided + var error = { + message: 'No server certificate provided. Not enough security.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.insufficient_security + } + }; + + // call application callback + var depth = 0; + var ret = c.verify(c, error.alert.description, depth, []); + if(ret !== true) { + // check for custom alert info + if(ret || ret === 0) { + // set custom message and alert description + if(typeof ret === 'object' && !forge.util.isArray(ret)) { + if(ret.message) { + error.message = ret.message; + } + if(ret.alert) { + error.alert.description = ret.alert; + } + } else if(typeof ret === 'number') { + // set custom alert description + error.alert.description = ret; + } + } + + // send error + return c.error(c, error); + } + } + + // create client certificate message if requested + if(c.session.certificateRequest !== null) { + record = tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createCertificate(c) + }); + tls.queue(c, record); + } + + // create client key exchange message + record = tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createClientKeyExchange(c) + }); + tls.queue(c, record); + + // expect no messages until the following callback has been called + c.expect = SER; + + // create callback to handle client signature (for client-certs) + var callback = function(c, signature) { + if(c.session.certificateRequest !== null && + c.session.clientCertificate !== null) { + // create certificate verify message + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createCertificateVerify(c, signature) + })); + } + + // create change cipher spec message + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.change_cipher_spec, + data: tls.createChangeCipherSpec() + })); + + // create pending state + c.state.pending = tls.createConnectionState(c); + + // change current write state to pending write state + c.state.current.write = c.state.pending.write; + + // create finished message + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createFinished(c) + })); + + // expect a server ChangeCipherSpec message next + c.expect = SCC; + + // send records + tls.flush(c); + + // continue + c.process(); + }; + + // if there is no certificate request or no client certificate, do + // callback immediately + if(c.session.certificateRequest === null || + c.session.clientCertificate === null) { + return callback(c, null); + } + + // otherwise get the client signature + tls.getClientSignature(c, callback); +}; + +/** + * Called when a ChangeCipherSpec record is received. + * + * @param c the connection. + * @param record the record. + */ +tls.handleChangeCipherSpec = function(c, record) { + if(record.fragment.getByte() !== 0x01) { + return c.error(c, { + message: 'Invalid ChangeCipherSpec message received.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.illegal_parameter + } + }); + } + + // create pending state if: + // 1. Resuming session in client mode OR + // 2. NOT resuming session in server mode + var client = (c.entity === tls.ConnectionEnd.client); + if((c.session.resuming && client) || (!c.session.resuming && !client)) { + c.state.pending = tls.createConnectionState(c); + } + + // change current read state to pending read state + c.state.current.read = c.state.pending.read; + + // clear pending state if: + // 1. NOT resuming session in client mode OR + // 2. resuming a session in server mode + if((!c.session.resuming && client) || (c.session.resuming && !client)) { + c.state.pending = null; + } + + // expect a Finished record next + c.expect = client ? SFI : CFI; + + // continue + c.process(); +}; + +/** + * Called when a Finished record is received. + * + * When this message will be sent: + * A finished message is always sent immediately after a change + * cipher spec message to verify that the key exchange and + * authentication processes were successful. It is essential that a + * change cipher spec message be received between the other + * handshake messages and the Finished message. + * + * Meaning of this message: + * The finished message is the first protected with the just- + * negotiated algorithms, keys, and secrets. Recipients of finished + * messages must verify that the contents are correct. Once a side + * has sent its Finished message and received and validated the + * Finished message from its peer, it may begin to send and receive + * application data over the connection. + * + * struct { + * opaque verify_data[verify_data_length]; + * } Finished; + * + * verify_data + * PRF(master_secret, finished_label, Hash(handshake_messages)) + * [0..verify_data_length-1]; + * + * finished_label + * For Finished messages sent by the client, the string + * "client finished". For Finished messages sent by the server, the + * string "server finished". + * + * verify_data_length depends on the cipher suite. If it is not specified + * by the cipher suite, then it is 12. Versions of TLS < 1.2 always used + * 12 bytes. + * + * @param c the connection. + * @param record the record. + * @param length the length of the handshake message. + */ +tls.handleFinished = function(c, record, length) { + // rewind to get full bytes for message so it can be manually + // digested below (special case for Finished messages because they + // must be digested *after* handling as opposed to all others) + var b = record.fragment; + b.read -= 4; + var msgBytes = b.bytes(); + b.read += 4; + + // message contains only verify_data + var vd = record.fragment.getBytes(); + + // ensure verify data is correct + b = forge.util.createBuffer(); + b.putBuffer(c.session.md5.digest()); + b.putBuffer(c.session.sha1.digest()); + + // set label based on entity type + var client = (c.entity === tls.ConnectionEnd.client); + var label = client ? 'server finished' : 'client finished'; + + // TODO: determine prf function and verify length for TLS 1.2 + var sp = c.session.sp; + var vdl = 12; + var prf = prf_TLS1; + b = prf(sp.master_secret, label, b.getBytes(), vdl); + if(b.getBytes() !== vd) { + return c.error(c, { + message: 'Invalid verify_data in Finished message.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.decrypt_error + } + }); + } + + // digest finished message now that it has been handled + c.session.md5.update(msgBytes); + c.session.sha1.update(msgBytes); + + // resuming session as client or NOT resuming session as server + if((c.session.resuming && client) || (!c.session.resuming && !client)) { + // create change cipher spec message + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.change_cipher_spec, + data: tls.createChangeCipherSpec() + })); + + // change current write state to pending write state, clear pending + c.state.current.write = c.state.pending.write; + c.state.pending = null; + + // create finished message + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createFinished(c) + })); + } + + // expect application data next + c.expect = client ? SAD : CAD; + + // handshake complete + c.handshaking = false; + ++c.handshakes; + + // save access to peer certificate + c.peerCertificate = client ? + c.session.serverCertificate : c.session.clientCertificate; + + // send records + tls.flush(c); + + // now connected + c.isConnected = true; + c.connected(c); + + // continue + c.process(); +}; + +/** + * Called when an Alert record is received. + * + * @param c the connection. + * @param record the record. + */ +tls.handleAlert = function(c, record) { + // read alert + var b = record.fragment; + var alert = { + level: b.getByte(), + description: b.getByte() + }; + + // TODO: consider using a table? + // get appropriate message + var msg; + switch(alert.description) { + case tls.Alert.Description.close_notify: + msg = 'Connection closed.'; + break; + case tls.Alert.Description.unexpected_message: + msg = 'Unexpected message.'; + break; + case tls.Alert.Description.bad_record_mac: + msg = 'Bad record MAC.'; + break; + case tls.Alert.Description.decryption_failed: + msg = 'Decryption failed.'; + break; + case tls.Alert.Description.record_overflow: + msg = 'Record overflow.'; + break; + case tls.Alert.Description.decompression_failure: + msg = 'Decompression failed.'; + break; + case tls.Alert.Description.handshake_failure: + msg = 'Handshake failure.'; + break; + case tls.Alert.Description.bad_certificate: + msg = 'Bad certificate.'; + break; + case tls.Alert.Description.unsupported_certificate: + msg = 'Unsupported certificate.'; + break; + case tls.Alert.Description.certificate_revoked: + msg = 'Certificate revoked.'; + break; + case tls.Alert.Description.certificate_expired: + msg = 'Certificate expired.'; + break; + case tls.Alert.Description.certificate_unknown: + msg = 'Certificate unknown.'; + break; + case tls.Alert.Description.illegal_parameter: + msg = 'Illegal parameter.'; + break; + case tls.Alert.Description.unknown_ca: + msg = 'Unknown certificate authority.'; + break; + case tls.Alert.Description.access_denied: + msg = 'Access denied.'; + break; + case tls.Alert.Description.decode_error: + msg = 'Decode error.'; + break; + case tls.Alert.Description.decrypt_error: + msg = 'Decrypt error.'; + break; + case tls.Alert.Description.export_restriction: + msg = 'Export restriction.'; + break; + case tls.Alert.Description.protocol_version: + msg = 'Unsupported protocol version.'; + break; + case tls.Alert.Description.insufficient_security: + msg = 'Insufficient security.'; + break; + case tls.Alert.Description.internal_error: + msg = 'Internal error.'; + break; + case tls.Alert.Description.user_canceled: + msg = 'User canceled.'; + break; + case tls.Alert.Description.no_renegotiation: + msg = 'Renegotiation not supported.'; + break; + default: + msg = 'Unknown error.'; + break; + } + + // close connection on close_notify, not an error + if(alert.description === tls.Alert.Description.close_notify) { + return c.close(); + } + + // call error handler + c.error(c, { + message: msg, + send: false, + // origin is the opposite end + origin: (c.entity === tls.ConnectionEnd.client) ? 'server' : 'client', + alert: alert + }); + + // continue + c.process(); +}; + +/** + * Called when a Handshake record is received. + * + * @param c the connection. + * @param record the record. + */ +tls.handleHandshake = function(c, record) { + // get the handshake type and message length + var b = record.fragment; + var type = b.getByte(); + var length = b.getInt24(); + + // see if the record fragment doesn't yet contain the full message + if(length > b.length()) { + // cache the record, clear its fragment, and reset the buffer read + // pointer before the type and length were read + c.fragmented = record; + record.fragment = forge.util.createBuffer(); + b.read -= 4; + + // continue + return c.process(); + } + + // full message now available, clear cache, reset read pointer to + // before type and length + c.fragmented = null; + b.read -= 4; + + // save the handshake bytes for digestion after handler is found + // (include type and length of handshake msg) + var bytes = b.bytes(length + 4); + + // restore read pointer + b.read += 4; + + // handle expected message + if(type in hsTable[c.entity][c.expect]) { + // initialize server session + if(c.entity === tls.ConnectionEnd.server && !c.open && !c.fail) { + c.handshaking = true; + c.session = { + version: null, + extensions: { + server_name: { + serverNameList: [] + } + }, + cipherSuite: null, + compressionMethod: null, + serverCertificate: null, + clientCertificate: null, + md5: forge.md.md5.create(), + sha1: forge.md.sha1.create() + }; + } + + /* Update handshake messages digest. Finished and CertificateVerify + messages are not digested here. They can't be digested as part of + the verify_data that they contain. These messages are manually + digested in their handlers. HelloRequest messages are simply never + included in the handshake message digest according to spec. */ + if(type !== tls.HandshakeType.hello_request && + type !== tls.HandshakeType.certificate_verify && + type !== tls.HandshakeType.finished) { + c.session.md5.update(bytes); + c.session.sha1.update(bytes); + } + + // handle specific handshake type record + hsTable[c.entity][c.expect][type](c, record, length); + } else { + // unexpected record + tls.handleUnexpected(c, record); + } +}; + +/** + * Called when an ApplicationData record is received. + * + * @param c the connection. + * @param record the record. + */ +tls.handleApplicationData = function(c, record) { + // buffer data, notify that its ready + c.data.putBuffer(record.fragment); + c.dataReady(c); + + // continue + c.process(); +}; + +/** + * Called when a Heartbeat record is received. + * + * @param c the connection. + * @param record the record. + */ +tls.handleHeartbeat = function(c, record) { + // get the heartbeat type and payload + var b = record.fragment; + var type = b.getByte(); + var length = b.getInt16(); + var payload = b.getBytes(length); + + if(type === tls.HeartbeatMessageType.heartbeat_request) { + // discard request during handshake or if length is too large + if(c.handshaking || length > payload.length) { + // continue + return c.process(); + } + // retransmit payload + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.heartbeat, + data: tls.createHeartbeat( + tls.HeartbeatMessageType.heartbeat_response, payload) + })); + tls.flush(c); + } else if(type === tls.HeartbeatMessageType.heartbeat_response) { + // check payload against expected payload, discard heartbeat if no match + if(payload !== c.expectedHeartbeatPayload) { + // continue + return c.process(); + } + + // notify that a valid heartbeat was received + if(c.heartbeatReceived) { + c.heartbeatReceived(c, forge.util.createBuffer(payload)); + } + } + + // continue + c.process(); +}; + +/** + * The transistional state tables for receiving TLS records. It maps the + * current TLS engine state and a received record to a function to handle the + * record and update the state. + * + * For instance, if the current state is SHE, then the TLS engine is expecting + * a ServerHello record. Once a record is received, the handler function is + * looked up using the state SHE and the record's content type. + * + * The resulting function will either be an error handler or a record handler. + * The function will take whatever action is appropriate and update the state + * for the next record. + * + * The states are all based on possible server record types. Note that the + * client will never specifically expect to receive a HelloRequest or an alert + * from the server so there is no state that reflects this. These messages may + * occur at any time. + * + * There are two tables for mapping states because there is a second tier of + * types for handshake messages. Once a record with a content type of handshake + * is received, the handshake record handler will look up the handshake type in + * the secondary map to get its appropriate handler. + * + * Valid message orders are as follows: + * + * =======================FULL HANDSHAKE====================== + * Client Server + * + * ClientHello --------> + * ServerHello + * Certificate* + * ServerKeyExchange* + * CertificateRequest* + * <-------- ServerHelloDone + * Certificate* + * ClientKeyExchange + * CertificateVerify* + * [ChangeCipherSpec] + * Finished --------> + * [ChangeCipherSpec] + * <-------- Finished + * Application Data <-------> Application Data + * + * =====================SESSION RESUMPTION===================== + * Client Server + * + * ClientHello --------> + * ServerHello + * [ChangeCipherSpec] + * <-------- Finished + * [ChangeCipherSpec] + * Finished --------> + * Application Data <-------> Application Data + */ +// client expect states (indicate which records are expected to be received) +var SHE = 0; // rcv server hello +var SCE = 1; // rcv server certificate +var SKE = 2; // rcv server key exchange +var SCR = 3; // rcv certificate request +var SHD = 4; // rcv server hello done +var SCC = 5; // rcv change cipher spec +var SFI = 6; // rcv finished +var SAD = 7; // rcv application data +var SER = 8; // not expecting any messages at this point + +// server expect states +var CHE = 0; // rcv client hello +var CCE = 1; // rcv client certificate +var CKE = 2; // rcv client key exchange +var CCV = 3; // rcv certificate verify +var CCC = 4; // rcv change cipher spec +var CFI = 5; // rcv finished +var CAD = 6; // rcv application data +var CER = 7; // not expecting any messages at this point + +// map client current expect state and content type to function +var __ = tls.handleUnexpected; +var R0 = tls.handleChangeCipherSpec; +var R1 = tls.handleAlert; +var R2 = tls.handleHandshake; +var R3 = tls.handleApplicationData; +var R4 = tls.handleHeartbeat; +var ctTable = []; +ctTable[tls.ConnectionEnd.client] = [ +// CC,AL,HS,AD,HB +/*SHE*/[__,R1,R2,__,R4], +/*SCE*/[__,R1,R2,__,R4], +/*SKE*/[__,R1,R2,__,R4], +/*SCR*/[__,R1,R2,__,R4], +/*SHD*/[__,R1,R2,__,R4], +/*SCC*/[R0,R1,__,__,R4], +/*SFI*/[__,R1,R2,__,R4], +/*SAD*/[__,R1,R2,R3,R4], +/*SER*/[__,R1,R2,__,R4] +]; + +// map server current expect state and content type to function +ctTable[tls.ConnectionEnd.server] = [ +// CC,AL,HS,AD +/*CHE*/[__,R1,R2,__,R4], +/*CCE*/[__,R1,R2,__,R4], +/*CKE*/[__,R1,R2,__,R4], +/*CCV*/[__,R1,R2,__,R4], +/*CCC*/[R0,R1,__,__,R4], +/*CFI*/[__,R1,R2,__,R4], +/*CAD*/[__,R1,R2,R3,R4], +/*CER*/[__,R1,R2,__,R4] +]; + +// map client current expect state and handshake type to function +var H0 = tls.handleHelloRequest; +var H1 = tls.handleServerHello; +var H2 = tls.handleCertificate; +var H3 = tls.handleServerKeyExchange; +var H4 = tls.handleCertificateRequest; +var H5 = tls.handleServerHelloDone; +var H6 = tls.handleFinished; +var hsTable = []; +hsTable[tls.ConnectionEnd.client] = [ +// HR,01,SH,03,04,05,06,07,08,09,10,SC,SK,CR,HD,15,CK,17,18,19,FI +/*SHE*/[__,__,H1,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], +/*SCE*/[H0,__,__,__,__,__,__,__,__,__,__,H2,H3,H4,H5,__,__,__,__,__,__], +/*SKE*/[H0,__,__,__,__,__,__,__,__,__,__,__,H3,H4,H5,__,__,__,__,__,__], +/*SCR*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,H4,H5,__,__,__,__,__,__], +/*SHD*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,H5,__,__,__,__,__,__], +/*SCC*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], +/*SFI*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6], +/*SAD*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], +/*SER*/[H0,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__] +]; + +// map server current expect state and handshake type to function +// Note: CAD[CH] does not map to FB because renegotation is prohibited +var H7 = tls.handleClientHello; +var H8 = tls.handleClientKeyExchange; +var H9 = tls.handleCertificateVerify; +hsTable[tls.ConnectionEnd.server] = [ +// 01,CH,02,03,04,05,06,07,08,09,10,CC,12,13,14,CV,CK,17,18,19,FI +/*CHE*/[__,H7,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], +/*CCE*/[__,__,__,__,__,__,__,__,__,__,__,H2,__,__,__,__,__,__,__,__,__], +/*CKE*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H8,__,__,__,__], +/*CCV*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H9,__,__,__,__,__], +/*CCC*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], +/*CFI*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,H6], +/*CAD*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__], +/*CER*/[__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__,__] +]; + +/** + * Generates the master_secret and keys using the given security parameters. + * + * The security parameters for a TLS connection state are defined as such: + * + * struct { + * ConnectionEnd entity; + * PRFAlgorithm prf_algorithm; + * BulkCipherAlgorithm bulk_cipher_algorithm; + * CipherType cipher_type; + * uint8 enc_key_length; + * uint8 block_length; + * uint8 fixed_iv_length; + * uint8 record_iv_length; + * MACAlgorithm mac_algorithm; + * uint8 mac_length; + * uint8 mac_key_length; + * CompressionMethod compression_algorithm; + * opaque master_secret[48]; + * opaque client_random[32]; + * opaque server_random[32]; + * } SecurityParameters; + * + * Note that this definition is from TLS 1.2. In TLS 1.0 some of these + * parameters are ignored because, for instance, the PRFAlgorithm is a + * builtin-fixed algorithm combining iterations of MD5 and SHA-1 in TLS 1.0. + * + * The Record Protocol requires an algorithm to generate keys required by the + * current connection state. + * + * The master secret is expanded into a sequence of secure bytes, which is then + * split to a client write MAC key, a server write MAC key, a client write + * encryption key, and a server write encryption key. In TLS 1.0 a client write + * IV and server write IV are also generated. Each of these is generated from + * the byte sequence in that order. Unused values are empty. In TLS 1.2, some + * AEAD ciphers may additionally require a client write IV and a server write + * IV (see Section 6.2.3.3). + * + * When keys, MAC keys, and IVs are generated, the master secret is used as an + * entropy source. + * + * To generate the key material, compute: + * + * master_secret = PRF(pre_master_secret, "master secret", + * ClientHello.random + ServerHello.random) + * + * key_block = PRF(SecurityParameters.master_secret, + * "key expansion", + * SecurityParameters.server_random + + * SecurityParameters.client_random); + * + * until enough output has been generated. Then, the key_block is + * partitioned as follows: + * + * client_write_MAC_key[SecurityParameters.mac_key_length] + * server_write_MAC_key[SecurityParameters.mac_key_length] + * client_write_key[SecurityParameters.enc_key_length] + * server_write_key[SecurityParameters.enc_key_length] + * client_write_IV[SecurityParameters.fixed_iv_length] + * server_write_IV[SecurityParameters.fixed_iv_length] + * + * In TLS 1.2, the client_write_IV and server_write_IV are only generated for + * implicit nonce techniques as described in Section 3.2.1 of [AEAD]. This + * implementation uses TLS 1.0 so IVs are generated. + * + * Implementation note: The currently defined cipher suite which requires the + * most material is AES_256_CBC_SHA256. It requires 2 x 32 byte keys and 2 x 32 + * byte MAC keys, for a total 128 bytes of key material. In TLS 1.0 it also + * requires 2 x 16 byte IVs, so it actually takes 160 bytes of key material. + * + * @param c the connection. + * @param sp the security parameters to use. + * + * @return the security keys. + */ +tls.generateKeys = function(c, sp) { + // TLS_RSA_WITH_AES_128_CBC_SHA (required to be compliant with TLS 1.2) & + // TLS_RSA_WITH_AES_256_CBC_SHA are the only cipher suites implemented + // at present + + // TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA is required to be compliant with + // TLS 1.0 but we don't care right now because AES is better and we have + // an implementation for it + + // TODO: TLS 1.2 implementation + /* + // determine the PRF + var prf; + switch(sp.prf_algorithm) { + case tls.PRFAlgorithm.tls_prf_sha256: + prf = prf_sha256; + break; + default: + // should never happen + throw new Error('Invalid PRF'); + } + */ + + // TLS 1.0/1.1 implementation + var prf = prf_TLS1; + + // concatenate server and client random + var random = sp.client_random + sp.server_random; + + // only create master secret if session is new + if(!c.session.resuming) { + // create master secret, clean up pre-master secret + sp.master_secret = prf( + sp.pre_master_secret, 'master secret', random, 48).bytes(); + sp.pre_master_secret = null; + } + + // generate the amount of key material needed + random = sp.server_random + sp.client_random; + var length = 2 * sp.mac_key_length + 2 * sp.enc_key_length; + + // include IV for TLS/1.0 + var tls10 = (c.version.major === tls.Versions.TLS_1_0.major && + c.version.minor === tls.Versions.TLS_1_0.minor); + if(tls10) { + length += 2 * sp.fixed_iv_length; + } + var km = prf(sp.master_secret, 'key expansion', random, length); + + // split the key material into the MAC and encryption keys + var rval = { + client_write_MAC_key: km.getBytes(sp.mac_key_length), + server_write_MAC_key: km.getBytes(sp.mac_key_length), + client_write_key: km.getBytes(sp.enc_key_length), + server_write_key: km.getBytes(sp.enc_key_length) + }; + + // include TLS 1.0 IVs + if(tls10) { + rval.client_write_IV = km.getBytes(sp.fixed_iv_length); + rval.server_write_IV = km.getBytes(sp.fixed_iv_length); + } + + return rval; +}; + +/** + * Creates a new initialized TLS connection state. A connection state has + * a read mode and a write mode. + * + * compression state: + * The current state of the compression algorithm. + * + * cipher state: + * The current state of the encryption algorithm. This will consist of the + * scheduled key for that connection. For stream ciphers, this will also + * contain whatever state information is necessary to allow the stream to + * continue to encrypt or decrypt data. + * + * MAC key: + * The MAC key for the connection. + * + * sequence number: + * Each connection state contains a sequence number, which is maintained + * separately for read and write states. The sequence number MUST be set to + * zero whenever a connection state is made the active state. Sequence + * numbers are of type uint64 and may not exceed 2^64-1. Sequence numbers do + * not wrap. If a TLS implementation would need to wrap a sequence number, + * it must renegotiate instead. A sequence number is incremented after each + * record: specifically, the first record transmitted under a particular + * connection state MUST use sequence number 0. + * + * @param c the connection. + * + * @return the new initialized TLS connection state. + */ +tls.createConnectionState = function(c) { + var client = (c.entity === tls.ConnectionEnd.client); + + var createMode = function() { + var mode = { + // two 32-bit numbers, first is most significant + sequenceNumber: [0, 0], + macKey: null, + macLength: 0, + macFunction: null, + cipherState: null, + cipherFunction: function(record) {return true;}, + compressionState: null, + compressFunction: function(record) {return true;}, + updateSequenceNumber: function() { + if(mode.sequenceNumber[1] === 0xFFFFFFFF) { + mode.sequenceNumber[1] = 0; + ++mode.sequenceNumber[0]; + } else { + ++mode.sequenceNumber[1]; + } + } + }; + return mode; + }; + var state = { + read: createMode(), + write: createMode() + }; + + // update function in read mode will decrypt then decompress a record + state.read.update = function(c, record) { + if(!state.read.cipherFunction(record, state.read)) { + c.error(c, { + message: 'Could not decrypt record or bad MAC.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + // doesn't matter if decryption failed or MAC was + // invalid, return the same error so as not to reveal + // which one occurred + description: tls.Alert.Description.bad_record_mac + } + }); + } else if(!state.read.compressFunction(c, record, state.read)) { + c.error(c, { + message: 'Could not decompress record.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.decompression_failure + } + }); + } + return !c.fail; + }; + + // update function in write mode will compress then encrypt a record + state.write.update = function(c, record) { + if(!state.write.compressFunction(c, record, state.write)) { + // error, but do not send alert since it would require + // compression as well + c.error(c, { + message: 'Could not compress record.', + send: false, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error + } + }); + } else if(!state.write.cipherFunction(record, state.write)) { + // error, but do not send alert since it would require + // encryption as well + c.error(c, { + message: 'Could not encrypt record.', + send: false, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error + } + }); + } + return !c.fail; + }; + + // handle security parameters + if(c.session) { + var sp = c.session.sp; + c.session.cipherSuite.initSecurityParameters(sp); + + // generate keys + sp.keys = tls.generateKeys(c, sp); + state.read.macKey = client ? + sp.keys.server_write_MAC_key : sp.keys.client_write_MAC_key; + state.write.macKey = client ? + sp.keys.client_write_MAC_key : sp.keys.server_write_MAC_key; + + // cipher suite setup + c.session.cipherSuite.initConnectionState(state, c, sp); + + // compression setup + switch(sp.compression_algorithm) { + case tls.CompressionMethod.none: + break; + case tls.CompressionMethod.deflate: + state.read.compressFunction = inflate; + state.write.compressFunction = deflate; + break; + default: + throw new Error('Unsupported compression algorithm.'); + } + } + + return state; +}; + +/** + * Creates a Random structure. + * + * struct { + * uint32 gmt_unix_time; + * opaque random_bytes[28]; + * } Random; + * + * gmt_unix_time: + * The current time and date in standard UNIX 32-bit format (seconds since + * the midnight starting Jan 1, 1970, UTC, ignoring leap seconds) according + * to the sender's internal clock. Clocks are not required to be set + * correctly by the basic TLS protocol; higher-level or application + * protocols may define additional requirements. Note that, for historical + * reasons, the data element is named using GMT, the predecessor of the + * current worldwide time base, UTC. + * random_bytes: + * 28 bytes generated by a secure random number generator. + * + * @return the Random structure as a byte array. + */ +tls.createRandom = function() { + // get UTC milliseconds + var d = new Date(); + var utc = +d + d.getTimezoneOffset() * 60000; + var rval = forge.util.createBuffer(); + rval.putInt32(utc); + rval.putBytes(forge.random.getBytes(28)); + return rval; +}; + +/** + * Creates a TLS record with the given type and data. + * + * @param c the connection. + * @param options: + * type: the record type. + * data: the plain text data in a byte buffer. + * + * @return the created record. + */ +tls.createRecord = function(c, options) { + if(!options.data) { + return null; + } + var record = { + type: options.type, + version: { + major: c.version.major, + minor: c.version.minor + }, + length: options.data.length(), + fragment: options.data + }; + return record; +}; + +/** + * Creates a TLS alert record. + * + * @param c the connection. + * @param alert: + * level: the TLS alert level. + * description: the TLS alert description. + * + * @return the created alert record. + */ +tls.createAlert = function(c, alert) { + var b = forge.util.createBuffer(); + b.putByte(alert.level); + b.putByte(alert.description); + return tls.createRecord(c, { + type: tls.ContentType.alert, + data: b + }); +}; + +/* The structure of a TLS handshake message. + * + * struct { + * HandshakeType msg_type; // handshake type + * uint24 length; // bytes in message + * select(HandshakeType) { + * case hello_request: HelloRequest; + * case client_hello: ClientHello; + * case server_hello: ServerHello; + * case certificate: Certificate; + * case server_key_exchange: ServerKeyExchange; + * case certificate_request: CertificateRequest; + * case server_hello_done: ServerHelloDone; + * case certificate_verify: CertificateVerify; + * case client_key_exchange: ClientKeyExchange; + * case finished: Finished; + * } body; + * } Handshake; + */ + +/** + * Creates a ClientHello message. + * + * opaque SessionID<0..32>; + * enum { null(0), deflate(1), (255) } CompressionMethod; + * uint8 CipherSuite[2]; + * + * struct { + * ProtocolVersion client_version; + * Random random; + * SessionID session_id; + * CipherSuite cipher_suites<2..2^16-2>; + * CompressionMethod compression_methods<1..2^8-1>; + * select(extensions_present) { + * case false: + * struct {}; + * case true: + * Extension extensions<0..2^16-1>; + * }; + * } ClientHello; + * + * The extension format for extended client hellos and server hellos is: + * + * struct { + * ExtensionType extension_type; + * opaque extension_data<0..2^16-1>; + * } Extension; + * + * Here: + * + * - "extension_type" identifies the particular extension type. + * - "extension_data" contains information specific to the particular + * extension type. + * + * The extension types defined in this document are: + * + * enum { + * server_name(0), max_fragment_length(1), + * client_certificate_url(2), trusted_ca_keys(3), + * truncated_hmac(4), status_request(5), (65535) + * } ExtensionType; + * + * @param c the connection. + * + * @return the ClientHello byte buffer. + */ +tls.createClientHello = function(c) { + // save hello version + c.session.clientHelloVersion = { + major: c.version.major, + minor: c.version.minor + }; + + // create supported cipher suites + var cipherSuites = forge.util.createBuffer(); + for(var i = 0; i < c.cipherSuites.length; ++i) { + var cs = c.cipherSuites[i]; + cipherSuites.putByte(cs.id[0]); + cipherSuites.putByte(cs.id[1]); + } + var cSuites = cipherSuites.length(); + + // create supported compression methods, null always supported, but + // also support deflate if connection has inflate and deflate methods + var compressionMethods = forge.util.createBuffer(); + compressionMethods.putByte(tls.CompressionMethod.none); + // FIXME: deflate support disabled until issues with raw deflate data + // without zlib headers are resolved + /* + if(c.inflate !== null && c.deflate !== null) { + compressionMethods.putByte(tls.CompressionMethod.deflate); + } + */ + var cMethods = compressionMethods.length(); + + // create TLS SNI (server name indication) extension if virtual host + // has been specified, see RFC 3546 + var extensions = forge.util.createBuffer(); + if(c.virtualHost) { + // create extension struct + var ext = forge.util.createBuffer(); + ext.putByte(0x00); // type server_name (ExtensionType is 2 bytes) + ext.putByte(0x00); + + /* In order to provide the server name, clients MAY include an + * extension of type "server_name" in the (extended) client hello. + * The "extension_data" field of this extension SHALL contain + * "ServerNameList" where: + * + * struct { + * NameType name_type; + * select(name_type) { + * case host_name: HostName; + * } name; + * } ServerName; + * + * enum { + * host_name(0), (255) + * } NameType; + * + * opaque HostName<1..2^16-1>; + * + * struct { + * ServerName server_name_list<1..2^16-1> + * } ServerNameList; + */ + var serverName = forge.util.createBuffer(); + serverName.putByte(0x00); // type host_name + writeVector(serverName, 2, forge.util.createBuffer(c.virtualHost)); + + // ServerNameList is in extension_data + var snList = forge.util.createBuffer(); + writeVector(snList, 2, serverName); + writeVector(ext, 2, snList); + extensions.putBuffer(ext); + } + var extLength = extensions.length(); + if(extLength > 0) { + // add extension vector length + extLength += 2; + } + + // determine length of the handshake message + // cipher suites and compression methods size will need to be + // updated if more get added to the list + var sessionId = c.session.id; + var length = + sessionId.length + 1 + // session ID vector + 2 + // version (major + minor) + 4 + 28 + // random time and random bytes + 2 + cSuites + // cipher suites vector + 1 + cMethods + // compression methods vector + extLength; // extensions vector + + // build record fragment + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.client_hello); + rval.putInt24(length); // handshake length + rval.putByte(c.version.major); // major version + rval.putByte(c.version.minor); // minor version + rval.putBytes(c.session.sp.client_random); // random time + bytes + writeVector(rval, 1, forge.util.createBuffer(sessionId)); + writeVector(rval, 2, cipherSuites); + writeVector(rval, 1, compressionMethods); + if(extLength > 0) { + writeVector(rval, 2, extensions); + } + return rval; +}; + +/** + * Creates a ServerHello message. + * + * @param c the connection. + * + * @return the ServerHello byte buffer. + */ +tls.createServerHello = function(c) { + // determine length of the handshake message + var sessionId = c.session.id; + var length = + sessionId.length + 1 + // session ID vector + 2 + // version (major + minor) + 4 + 28 + // random time and random bytes + 2 + // chosen cipher suite + 1; // chosen compression method + + // build record fragment + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.server_hello); + rval.putInt24(length); // handshake length + rval.putByte(c.version.major); // major version + rval.putByte(c.version.minor); // minor version + rval.putBytes(c.session.sp.server_random); // random time + bytes + writeVector(rval, 1, forge.util.createBuffer(sessionId)); + rval.putByte(c.session.cipherSuite.id[0]); + rval.putByte(c.session.cipherSuite.id[1]); + rval.putByte(c.session.compressionMethod); + return rval; +}; + +/** + * Creates a Certificate message. + * + * When this message will be sent: + * This is the first message the client can send after receiving a server + * hello done message and the first message the server can send after + * sending a ServerHello. This client message is only sent if the server + * requests a certificate. If no suitable certificate is available, the + * client should send a certificate message containing no certificates. If + * client authentication is required by the server for the handshake to + * continue, it may respond with a fatal handshake failure alert. + * + * opaque ASN.1Cert<1..2^24-1>; + * + * struct { + * ASN.1Cert certificate_list<0..2^24-1>; + * } Certificate; + * + * @param c the connection. + * + * @return the Certificate byte buffer. + */ +tls.createCertificate = function(c) { + // TODO: check certificate request to ensure types are supported + + // get a certificate (a certificate as a PEM string) + var client = (c.entity === tls.ConnectionEnd.client); + var cert = null; + if(c.getCertificate) { + var hint; + if(client) { + hint = c.session.certificateRequest; + } else { + hint = c.session.extensions.server_name.serverNameList; + } + cert = c.getCertificate(c, hint); + } + + // buffer to hold certificate list + var certList = forge.util.createBuffer(); + if(cert !== null) { + try { + // normalize cert to a chain of certificates + if(!forge.util.isArray(cert)) { + cert = [cert]; + } + var asn1 = null; + for(var i = 0; i < cert.length; ++i) { + var msg = forge.pem.decode(cert[i])[0]; + if(msg.type !== 'CERTIFICATE' && + msg.type !== 'X509 CERTIFICATE' && + msg.type !== 'TRUSTED CERTIFICATE') { + var error = new Error('Could not convert certificate from PEM; PEM ' + + 'header type is not "CERTIFICATE", "X509 CERTIFICATE", or ' + + '"TRUSTED CERTIFICATE".'); + error.headerType = msg.type; + throw error; + } + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert certificate from PEM; PEM is encrypted.'); + } + + var der = forge.util.createBuffer(msg.body); + if(asn1 === null) { + asn1 = forge.asn1.fromDer(der.bytes(), false); + } + + // certificate entry is itself a vector with 3 length bytes + var certBuffer = forge.util.createBuffer(); + writeVector(certBuffer, 3, der); + + // add cert vector to cert list vector + certList.putBuffer(certBuffer); + } + + // save certificate + cert = forge.pki.certificateFromAsn1(asn1); + if(client) { + c.session.clientCertificate = cert; + } else { + c.session.serverCertificate = cert; + } + } catch(ex) { + return c.error(c, { + message: 'Could not send certificate list.', + cause: ex, + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.bad_certificate + } + }); + } + } + + // determine length of the handshake message + var length = 3 + certList.length(); // cert list vector + + // build record fragment + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.certificate); + rval.putInt24(length); + writeVector(rval, 3, certList); + return rval; +}; + +/** + * Creates a ClientKeyExchange message. + * + * When this message will be sent: + * This message is always sent by the client. It will immediately follow the + * client certificate message, if it is sent. Otherwise it will be the first + * message sent by the client after it receives the server hello done + * message. + * + * Meaning of this message: + * With this message, the premaster secret is set, either though direct + * transmission of the RSA-encrypted secret, or by the transmission of + * Diffie-Hellman parameters which will allow each side to agree upon the + * same premaster secret. When the key exchange method is DH_RSA or DH_DSS, + * client certification has been requested, and the client was able to + * respond with a certificate which contained a Diffie-Hellman public key + * whose parameters (group and generator) matched those specified by the + * server in its certificate, this message will not contain any data. + * + * Meaning of this message: + * If RSA is being used for key agreement and authentication, the client + * generates a 48-byte premaster secret, encrypts it using the public key + * from the server's certificate or the temporary RSA key provided in a + * server key exchange message, and sends the result in an encrypted + * premaster secret message. This structure is a variant of the client + * key exchange message, not a message in itself. + * + * struct { + * select(KeyExchangeAlgorithm) { + * case rsa: EncryptedPreMasterSecret; + * case diffie_hellman: ClientDiffieHellmanPublic; + * } exchange_keys; + * } ClientKeyExchange; + * + * struct { + * ProtocolVersion client_version; + * opaque random[46]; + * } PreMasterSecret; + * + * struct { + * public-key-encrypted PreMasterSecret pre_master_secret; + * } EncryptedPreMasterSecret; + * + * A public-key-encrypted element is encoded as a vector <0..2^16-1>. + * + * @param c the connection. + * + * @return the ClientKeyExchange byte buffer. + */ +tls.createClientKeyExchange = function(c) { + // create buffer to encrypt + var b = forge.util.createBuffer(); + + // add highest client-supported protocol to help server avoid version + // rollback attacks + b.putByte(c.session.clientHelloVersion.major); + b.putByte(c.session.clientHelloVersion.minor); + + // generate and add 46 random bytes + b.putBytes(forge.random.getBytes(46)); + + // save pre-master secret + var sp = c.session.sp; + sp.pre_master_secret = b.getBytes(); + + // RSA-encrypt the pre-master secret + var key = c.session.serverCertificate.publicKey; + b = key.encrypt(sp.pre_master_secret); + + /* Note: The encrypted pre-master secret will be stored in a + public-key-encrypted opaque vector that has the length prefixed using + 2 bytes, so include those 2 bytes in the handshake message length. This + is done as a minor optimization instead of calling writeVector(). */ + + // determine length of the handshake message + var length = b.length + 2; + + // build record fragment + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.client_key_exchange); + rval.putInt24(length); + // add vector length bytes + rval.putInt16(b.length); + rval.putBytes(b); + return rval; +}; + +/** + * Creates a ServerKeyExchange message. + * + * @param c the connection. + * + * @return the ServerKeyExchange byte buffer. + */ +tls.createServerKeyExchange = function(c) { + // this implementation only supports RSA, no Diffie-Hellman support, + // so this record is empty + + // determine length of the handshake message + var length = 0; + + // build record fragment + var rval = forge.util.createBuffer(); + if(length > 0) { + rval.putByte(tls.HandshakeType.server_key_exchange); + rval.putInt24(length); + } + return rval; +}; + +/** + * Gets the signed data used to verify a client-side certificate. See + * tls.createCertificateVerify() for details. + * + * @param c the connection. + * @param callback the callback to call once the signed data is ready. + */ +tls.getClientSignature = function(c, callback) { + // generate data to RSA encrypt + var b = forge.util.createBuffer(); + b.putBuffer(c.session.md5.digest()); + b.putBuffer(c.session.sha1.digest()); + b = b.getBytes(); + + // create default signing function as necessary + c.getSignature = c.getSignature || function(c, b, callback) { + // do rsa encryption, call callback + var privateKey = null; + if(c.getPrivateKey) { + try { + privateKey = c.getPrivateKey(c, c.session.clientCertificate); + privateKey = forge.pki.privateKeyFromPem(privateKey); + } catch(ex) { + c.error(c, { + message: 'Could not get private key.', + cause: ex, + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error + } + }); + } + } + if(privateKey === null) { + c.error(c, { + message: 'No private key set.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.internal_error + } + }); + } else { + b = privateKey.sign(b, null); + } + callback(c, b); + }; + + // get client signature + c.getSignature(c, b, callback); +}; + +/** + * Creates a CertificateVerify message. + * + * Meaning of this message: + * This structure conveys the client's Diffie-Hellman public value + * (Yc) if it was not already included in the client's certificate. + * The encoding used for Yc is determined by the enumerated + * PublicValueEncoding. This structure is a variant of the client + * key exchange message, not a message in itself. + * + * When this message will be sent: + * This message is used to provide explicit verification of a client + * certificate. This message is only sent following a client + * certificate that has signing capability (i.e. all certificates + * except those containing fixed Diffie-Hellman parameters). When + * sent, it will immediately follow the client key exchange message. + * + * struct { + * Signature signature; + * } CertificateVerify; + * + * CertificateVerify.signature.md5_hash + * MD5(handshake_messages); + * + * Certificate.signature.sha_hash + * SHA(handshake_messages); + * + * Here handshake_messages refers to all handshake messages sent or + * received starting at client hello up to but not including this + * message, including the type and length fields of the handshake + * messages. + * + * select(SignatureAlgorithm) { + * case anonymous: struct { }; + * case rsa: + * digitally-signed struct { + * opaque md5_hash[16]; + * opaque sha_hash[20]; + * }; + * case dsa: + * digitally-signed struct { + * opaque sha_hash[20]; + * }; + * } Signature; + * + * In digital signing, one-way hash functions are used as input for a + * signing algorithm. A digitally-signed element is encoded as an opaque + * vector <0..2^16-1>, where the length is specified by the signing + * algorithm and key. + * + * In RSA signing, a 36-byte structure of two hashes (one SHA and one + * MD5) is signed (encrypted with the private key). It is encoded with + * PKCS #1 block type 0 or type 1 as described in [PKCS1]. + * + * In DSS, the 20 bytes of the SHA hash are run directly through the + * Digital Signing Algorithm with no additional hashing. + * + * @param c the connection. + * @param signature the signature to include in the message. + * + * @return the CertificateVerify byte buffer. + */ +tls.createCertificateVerify = function(c, signature) { + /* Note: The signature will be stored in a "digitally-signed" opaque + vector that has the length prefixed using 2 bytes, so include those + 2 bytes in the handshake message length. This is done as a minor + optimization instead of calling writeVector(). */ + + // determine length of the handshake message + var length = signature.length + 2; + + // build record fragment + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.certificate_verify); + rval.putInt24(length); + // add vector length bytes + rval.putInt16(signature.length); + rval.putBytes(signature); + return rval; +}; + +/** + * Creates a CertificateRequest message. + * + * @param c the connection. + * + * @return the CertificateRequest byte buffer. + */ +tls.createCertificateRequest = function(c) { + // TODO: support other certificate types + var certTypes = forge.util.createBuffer(); + + // common RSA certificate type + certTypes.putByte(0x01); + + // add distinguished names from CA store + var cAs = forge.util.createBuffer(); + for(var key in c.caStore.certs) { + var cert = c.caStore.certs[key]; + var dn = forge.pki.distinguishedNameToAsn1(cert.subject); + var byteBuffer = forge.asn1.toDer(dn); + cAs.putInt16(byteBuffer.length()); + cAs.putBuffer(byteBuffer); + } + + // TODO: TLS 1.2+ has a different format + + // determine length of the handshake message + var length = + 1 + certTypes.length() + + 2 + cAs.length(); + + // build record fragment + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.certificate_request); + rval.putInt24(length); + writeVector(rval, 1, certTypes); + writeVector(rval, 2, cAs); + return rval; +}; + +/** + * Creates a ServerHelloDone message. + * + * @param c the connection. + * + * @return the ServerHelloDone byte buffer. + */ +tls.createServerHelloDone = function(c) { + // build record fragment + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.server_hello_done); + rval.putInt24(0); + return rval; +}; + +/** + * Creates a ChangeCipherSpec message. + * + * The change cipher spec protocol exists to signal transitions in + * ciphering strategies. The protocol consists of a single message, + * which is encrypted and compressed under the current (not the pending) + * connection state. The message consists of a single byte of value 1. + * + * struct { + * enum { change_cipher_spec(1), (255) } type; + * } ChangeCipherSpec; + * + * @return the ChangeCipherSpec byte buffer. + */ +tls.createChangeCipherSpec = function() { + var rval = forge.util.createBuffer(); + rval.putByte(0x01); + return rval; +}; + +/** + * Creates a Finished message. + * + * struct { + * opaque verify_data[12]; + * } Finished; + * + * verify_data + * PRF(master_secret, finished_label, MD5(handshake_messages) + + * SHA-1(handshake_messages)) [0..11]; + * + * finished_label + * For Finished messages sent by the client, the string "client + * finished". For Finished messages sent by the server, the + * string "server finished". + * + * handshake_messages + * All of the data from all handshake messages up to but not + * including this message. This is only data visible at the + * handshake layer and does not include record layer headers. + * This is the concatenation of all the Handshake structures as + * defined in 7.4 exchanged thus far. + * + * @param c the connection. + * + * @return the Finished byte buffer. + */ +tls.createFinished = function(c) { + // generate verify_data + var b = forge.util.createBuffer(); + b.putBuffer(c.session.md5.digest()); + b.putBuffer(c.session.sha1.digest()); + + // TODO: determine prf function and verify length for TLS 1.2 + var client = (c.entity === tls.ConnectionEnd.client); + var sp = c.session.sp; + var vdl = 12; + var prf = prf_TLS1; + var label = client ? 'client finished' : 'server finished'; + b = prf(sp.master_secret, label, b.getBytes(), vdl); + + // build record fragment + var rval = forge.util.createBuffer(); + rval.putByte(tls.HandshakeType.finished); + rval.putInt24(b.length()); + rval.putBuffer(b); + return rval; +}; + +/** + * Creates a HeartbeatMessage (See RFC 6520). + * + * struct { + * HeartbeatMessageType type; + * uint16 payload_length; + * opaque payload[HeartbeatMessage.payload_length]; + * opaque padding[padding_length]; + * } HeartbeatMessage; + * + * The total length of a HeartbeatMessage MUST NOT exceed 2^14 or + * max_fragment_length when negotiated as defined in [RFC6066]. + * + * type: The message type, either heartbeat_request or heartbeat_response. + * + * payload_length: The length of the payload. + * + * payload: The payload consists of arbitrary content. + * + * padding: The padding is random content that MUST be ignored by the + * receiver. The length of a HeartbeatMessage is TLSPlaintext.length + * for TLS and DTLSPlaintext.length for DTLS. Furthermore, the + * length of the type field is 1 byte, and the length of the + * payload_length is 2. Therefore, the padding_length is + * TLSPlaintext.length - payload_length - 3 for TLS and + * DTLSPlaintext.length - payload_length - 3 for DTLS. The + * padding_length MUST be at least 16. + * + * The sender of a HeartbeatMessage MUST use a random padding of at + * least 16 bytes. The padding of a received HeartbeatMessage message + * MUST be ignored. + * + * If the payload_length of a received HeartbeatMessage is too large, + * the received HeartbeatMessage MUST be discarded silently. + * + * @param c the connection. + * @param type the tls.HeartbeatMessageType. + * @param payload the heartbeat data to send as the payload. + * @param [payloadLength] the payload length to use, defaults to the + * actual payload length. + * + * @return the HeartbeatRequest byte buffer. + */ +tls.createHeartbeat = function(type, payload, payloadLength) { + if(typeof payloadLength === 'undefined') { + payloadLength = payload.length; + } + // build record fragment + var rval = forge.util.createBuffer(); + rval.putByte(type); // heartbeat message type + rval.putInt16(payloadLength); // payload length + rval.putBytes(payload); // payload + // padding + var plaintextLength = rval.length(); + var paddingLength = Math.max(16, plaintextLength - payloadLength - 3); + rval.putBytes(forge.random.getBytes(paddingLength)); + return rval; +}; + +/** + * Fragments, compresses, encrypts, and queues a record for delivery. + * + * @param c the connection. + * @param record the record to queue. + */ +tls.queue = function(c, record) { + // error during record creation + if(!record) { + return; + } + + if(record.fragment.length() === 0) { + if(record.type === tls.ContentType.handshake || + record.type === tls.ContentType.alert || + record.type === tls.ContentType.change_cipher_spec) { + // Empty handshake, alert of change cipher spec messages are not allowed per the TLS specification and should not be sent. + return; + } + } + + // if the record is a handshake record, update handshake hashes + if(record.type === tls.ContentType.handshake) { + var bytes = record.fragment.bytes(); + c.session.md5.update(bytes); + c.session.sha1.update(bytes); + bytes = null; + } + + // handle record fragmentation + var records; + if(record.fragment.length() <= tls.MaxFragment) { + records = [record]; + } else { + // fragment data as long as it is too long + records = []; + var data = record.fragment.bytes(); + while(data.length > tls.MaxFragment) { + records.push(tls.createRecord(c, { + type: record.type, + data: forge.util.createBuffer(data.slice(0, tls.MaxFragment)) + })); + data = data.slice(tls.MaxFragment); + } + // add last record + if(data.length > 0) { + records.push(tls.createRecord(c, { + type: record.type, + data: forge.util.createBuffer(data) + })); + } + } + + // compress and encrypt all fragmented records + for(var i = 0; i < records.length && !c.fail; ++i) { + // update the record using current write state + var rec = records[i]; + var s = c.state.current.write; + if(s.update(c, rec)) { + // store record + c.records.push(rec); + } + } +}; + +/** + * Flushes all queued records to the output buffer and calls the + * tlsDataReady() handler on the given connection. + * + * @param c the connection. + * + * @return true on success, false on failure. + */ +tls.flush = function(c) { + for(var i = 0; i < c.records.length; ++i) { + var record = c.records[i]; + + // add record header and fragment + c.tlsData.putByte(record.type); + c.tlsData.putByte(record.version.major); + c.tlsData.putByte(record.version.minor); + c.tlsData.putInt16(record.fragment.length()); + c.tlsData.putBuffer(c.records[i].fragment); + } + c.records = []; + return c.tlsDataReady(c); +}; + +/** + * Maps a pki.certificateError to a tls.Alert.Description. + * + * @param error the error to map. + * + * @return the alert description. + */ +var _certErrorToAlertDesc = function(error) { + switch(error) { + case true: + return true; + case forge.pki.certificateError.bad_certificate: + return tls.Alert.Description.bad_certificate; + case forge.pki.certificateError.unsupported_certificate: + return tls.Alert.Description.unsupported_certificate; + case forge.pki.certificateError.certificate_revoked: + return tls.Alert.Description.certificate_revoked; + case forge.pki.certificateError.certificate_expired: + return tls.Alert.Description.certificate_expired; + case forge.pki.certificateError.certificate_unknown: + return tls.Alert.Description.certificate_unknown; + case forge.pki.certificateError.unknown_ca: + return tls.Alert.Description.unknown_ca; + default: + return tls.Alert.Description.bad_certificate; + } +}; + +/** + * Maps a tls.Alert.Description to a pki.certificateError. + * + * @param desc the alert description. + * + * @return the certificate error. + */ +var _alertDescToCertError = function(desc) { + switch(desc) { + case true: + return true; + case tls.Alert.Description.bad_certificate: + return forge.pki.certificateError.bad_certificate; + case tls.Alert.Description.unsupported_certificate: + return forge.pki.certificateError.unsupported_certificate; + case tls.Alert.Description.certificate_revoked: + return forge.pki.certificateError.certificate_revoked; + case tls.Alert.Description.certificate_expired: + return forge.pki.certificateError.certificate_expired; + case tls.Alert.Description.certificate_unknown: + return forge.pki.certificateError.certificate_unknown; + case tls.Alert.Description.unknown_ca: + return forge.pki.certificateError.unknown_ca; + default: + return forge.pki.certificateError.bad_certificate; + } +}; + +/** + * Verifies a certificate chain against the given connection's + * Certificate Authority store. + * + * @param c the TLS connection. + * @param chain the certificate chain to verify, with the root or highest + * authority at the end. + * + * @return true if successful, false if not. + */ +tls.verifyCertificateChain = function(c, chain) { + try { + // Make a copy of c.verifyOptions so that we can modify options.verify + // without modifying c.verifyOptions. + var options = {}; + for (var key in c.verifyOptions) { + options[key] = c.verifyOptions[key]; + } + + options.verify = function(vfd, depth, chain) { + // convert pki.certificateError to tls alert description + var desc = _certErrorToAlertDesc(vfd); + + // call application callback + var ret = c.verify(c, vfd, depth, chain); + if(ret !== true) { + if(typeof ret === 'object' && !forge.util.isArray(ret)) { + // throw custom error + var error = new Error('The application rejected the certificate.'); + error.send = true; + error.alert = { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.bad_certificate + }; + if(ret.message) { + error.message = ret.message; + } + if(ret.alert) { + error.alert.description = ret.alert; + } + throw error; + } + + // convert tls alert description to pki.certificateError + if(ret !== vfd) { + ret = _alertDescToCertError(ret); + } + } + + return ret; + }; + + // verify chain + forge.pki.verifyCertificateChain(c.caStore, chain, options); + } catch(ex) { + // build tls error if not already customized + var err = ex; + if(typeof err !== 'object' || forge.util.isArray(err)) { + err = { + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: _certErrorToAlertDesc(ex) + } + }; + } + if(!('send' in err)) { + err.send = true; + } + if(!('alert' in err)) { + err.alert = { + level: tls.Alert.Level.fatal, + description: _certErrorToAlertDesc(err.error) + }; + } + + // send error + c.error(c, err); + } + + return !c.fail; +}; + +/** + * Creates a new TLS session cache. + * + * @param cache optional map of session ID to cached session. + * @param capacity the maximum size for the cache (default: 100). + * + * @return the new TLS session cache. + */ +tls.createSessionCache = function(cache, capacity) { + var rval = null; + + // assume input is already a session cache object + if(cache && cache.getSession && cache.setSession && cache.order) { + rval = cache; + } else { + // create cache + rval = {}; + rval.cache = cache || {}; + rval.capacity = Math.max(capacity || 100, 1); + rval.order = []; + + // store order for sessions, delete session overflow + for(var key in cache) { + if(rval.order.length <= capacity) { + rval.order.push(key); + } else { + delete cache[key]; + } + } + + // get a session from a session ID (or get any session) + rval.getSession = function(sessionId) { + var session = null; + var key = null; + + // if session ID provided, use it + if(sessionId) { + key = forge.util.bytesToHex(sessionId); + } else if(rval.order.length > 0) { + // get first session from cache + key = rval.order[0]; + } + + if(key !== null && key in rval.cache) { + // get cached session and remove from cache + session = rval.cache[key]; + delete rval.cache[key]; + for(var i in rval.order) { + if(rval.order[i] === key) { + rval.order.splice(i, 1); + break; + } + } + } + + return session; + }; + + // set a session in the cache + rval.setSession = function(sessionId, session) { + // remove session from cache if at capacity + if(rval.order.length === rval.capacity) { + var key = rval.order.shift(); + delete rval.cache[key]; + } + // add session to cache + var key = forge.util.bytesToHex(sessionId); + rval.order.push(key); + rval.cache[key] = session; + }; + } + + return rval; +}; + +/** + * Creates a new TLS connection. + * + * See public createConnection() docs for more details. + * + * @param options the options for this connection. + * + * @return the new TLS connection. + */ +tls.createConnection = function(options) { + var caStore = null; + if(options.caStore) { + // if CA store is an array, convert it to a CA store object + if(forge.util.isArray(options.caStore)) { + caStore = forge.pki.createCaStore(options.caStore); + } else { + caStore = options.caStore; + } + } else { + // create empty CA store + caStore = forge.pki.createCaStore(); + } + + // setup default cipher suites + var cipherSuites = options.cipherSuites || null; + if(cipherSuites === null) { + cipherSuites = []; + for(var key in tls.CipherSuites) { + cipherSuites.push(tls.CipherSuites[key]); + } + } + + // set default entity + var entity = (options.server || false) ? + tls.ConnectionEnd.server : tls.ConnectionEnd.client; + + // create session cache if requested + var sessionCache = options.sessionCache ? + tls.createSessionCache(options.sessionCache) : null; + + // create TLS connection + var c = { + version: {major: tls.Version.major, minor: tls.Version.minor}, + entity: entity, + sessionId: options.sessionId, + caStore: caStore, + sessionCache: sessionCache, + cipherSuites: cipherSuites, + connected: options.connected, + virtualHost: options.virtualHost || null, + verifyClient: options.verifyClient || false, + verify: options.verify || function(cn, vfd, dpth, cts) {return vfd;}, + verifyOptions: options.verifyOptions || {}, + getCertificate: options.getCertificate || null, + getPrivateKey: options.getPrivateKey || null, + getSignature: options.getSignature || null, + input: forge.util.createBuffer(), + tlsData: forge.util.createBuffer(), + data: forge.util.createBuffer(), + tlsDataReady: options.tlsDataReady, + dataReady: options.dataReady, + heartbeatReceived: options.heartbeatReceived, + closed: options.closed, + error: function(c, ex) { + // set origin if not set + ex.origin = ex.origin || + ((c.entity === tls.ConnectionEnd.client) ? 'client' : 'server'); + + // send TLS alert + if(ex.send) { + tls.queue(c, tls.createAlert(c, ex.alert)); + tls.flush(c); + } + + // error is fatal by default + var fatal = (ex.fatal !== false); + if(fatal) { + // set fail flag + c.fail = true; + } + + // call error handler first + options.error(c, ex); + + if(fatal) { + // fatal error, close connection, do not clear fail + c.close(false); + } + }, + deflate: options.deflate || null, + inflate: options.inflate || null + }; + + /** + * Resets a closed TLS connection for reuse. Called in c.close(). + * + * @param clearFail true to clear the fail flag (default: true). + */ + c.reset = function(clearFail) { + c.version = {major: tls.Version.major, minor: tls.Version.minor}; + c.record = null; + c.session = null; + c.peerCertificate = null; + c.state = { + pending: null, + current: null + }; + c.expect = (c.entity === tls.ConnectionEnd.client) ? SHE : CHE; + c.fragmented = null; + c.records = []; + c.open = false; + c.handshakes = 0; + c.handshaking = false; + c.isConnected = false; + c.fail = !(clearFail || typeof(clearFail) === 'undefined'); + c.input.clear(); + c.tlsData.clear(); + c.data.clear(); + c.state.current = tls.createConnectionState(c); + }; + + // do initial reset of connection + c.reset(); + + /** + * Updates the current TLS engine state based on the given record. + * + * @param c the TLS connection. + * @param record the TLS record to act on. + */ + var _update = function(c, record) { + // get record handler (align type in table by subtracting lowest) + var aligned = record.type - tls.ContentType.change_cipher_spec; + var handlers = ctTable[c.entity][c.expect]; + if(aligned in handlers) { + handlers[aligned](c, record); + } else { + // unexpected record + tls.handleUnexpected(c, record); + } + }; + + /** + * Reads the record header and initializes the next record on the given + * connection. + * + * @param c the TLS connection with the next record. + * + * @return 0 if the input data could be processed, otherwise the + * number of bytes required for data to be processed. + */ + var _readRecordHeader = function(c) { + var rval = 0; + + // get input buffer and its length + var b = c.input; + var len = b.length(); + + // need at least 5 bytes to initialize a record + if(len < 5) { + rval = 5 - len; + } else { + // enough bytes for header + // initialize record + c.record = { + type: b.getByte(), + version: { + major: b.getByte(), + minor: b.getByte() + }, + length: b.getInt16(), + fragment: forge.util.createBuffer(), + ready: false + }; + + // check record version + var compatibleVersion = (c.record.version.major === c.version.major); + if(compatibleVersion && c.session && c.session.version) { + // session version already set, require same minor version + compatibleVersion = (c.record.version.minor === c.version.minor); + } + if(!compatibleVersion) { + c.error(c, { + message: 'Incompatible TLS version.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: tls.Alert.Description.protocol_version + } + }); + } + } + + return rval; + }; + + /** + * Reads the next record's contents and appends its message to any + * previously fragmented message. + * + * @param c the TLS connection with the next record. + * + * @return 0 if the input data could be processed, otherwise the + * number of bytes required for data to be processed. + */ + var _readRecord = function(c) { + var rval = 0; + + // ensure there is enough input data to get the entire record + var b = c.input; + var len = b.length(); + if(len < c.record.length) { + // not enough data yet, return how much is required + rval = c.record.length - len; + } else { + // there is enough data to parse the pending record + // fill record fragment and compact input buffer + c.record.fragment.putBytes(b.getBytes(c.record.length)); + b.compact(); + + // update record using current read state + var s = c.state.current.read; + if(s.update(c, c.record)) { + // see if there is a previously fragmented message that the + // new record's message fragment should be appended to + if(c.fragmented !== null) { + // if the record type matches a previously fragmented + // record, append the record fragment to it + if(c.fragmented.type === c.record.type) { + // concatenate record fragments + c.fragmented.fragment.putBuffer(c.record.fragment); + c.record = c.fragmented; + } else { + // error, invalid fragmented record + c.error(c, { + message: 'Invalid fragmented record.', + send: true, + alert: { + level: tls.Alert.Level.fatal, + description: + tls.Alert.Description.unexpected_message + } + }); + } + } + + // record is now ready + c.record.ready = true; + } + } + + return rval; + }; + + /** + * Performs a handshake using the TLS Handshake Protocol, as a client. + * + * This method should only be called if the connection is in client mode. + * + * @param sessionId the session ID to use, null to start a new one. + */ + c.handshake = function(sessionId) { + // error to call this in non-client mode + if(c.entity !== tls.ConnectionEnd.client) { + // not fatal error + c.error(c, { + message: 'Cannot initiate handshake as a server.', + fatal: false + }); + } else if(c.handshaking) { + // handshake is already in progress, fail but not fatal error + c.error(c, { + message: 'Handshake already in progress.', + fatal: false + }); + } else { + // clear fail flag on reuse + if(c.fail && !c.open && c.handshakes === 0) { + c.fail = false; + } + + // now handshaking + c.handshaking = true; + + // default to blank (new session) + sessionId = sessionId || ''; + + // if a session ID was specified, try to find it in the cache + var session = null; + if(sessionId.length > 0) { + if(c.sessionCache) { + session = c.sessionCache.getSession(sessionId); + } + + // matching session not found in cache, clear session ID + if(session === null) { + sessionId = ''; + } + } + + // no session given, grab a session from the cache, if available + if(sessionId.length === 0 && c.sessionCache) { + session = c.sessionCache.getSession(); + if(session !== null) { + sessionId = session.id; + } + } + + // set up session + c.session = { + id: sessionId, + version: null, + cipherSuite: null, + compressionMethod: null, + serverCertificate: null, + certificateRequest: null, + clientCertificate: null, + sp: {}, + md5: forge.md.md5.create(), + sha1: forge.md.sha1.create() + }; + + // use existing session information + if(session) { + // only update version on connection, session version not yet set + c.version = session.version; + c.session.sp = session.sp; + } + + // generate new client random + c.session.sp.client_random = tls.createRandom().getBytes(); + + // connection now open + c.open = true; + + // send hello + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.handshake, + data: tls.createClientHello(c) + })); + tls.flush(c); + } + }; + + /** + * Called when TLS protocol data has been received from somewhere and should + * be processed by the TLS engine. + * + * @param data the TLS protocol data, as a string, to process. + * + * @return 0 if the data could be processed, otherwise the number of bytes + * required for data to be processed. + */ + c.process = function(data) { + var rval = 0; + + // buffer input data + if(data) { + c.input.putBytes(data); + } + + // process next record if no failure, process will be called after + // each record is handled (since handling can be asynchronous) + if(!c.fail) { + // reset record if ready and now empty + if(c.record !== null && + c.record.ready && c.record.fragment.isEmpty()) { + c.record = null; + } + + // if there is no pending record, try to read record header + if(c.record === null) { + rval = _readRecordHeader(c); + } + + // read the next record (if record not yet ready) + if(!c.fail && c.record !== null && !c.record.ready) { + rval = _readRecord(c); + } + + // record ready to be handled, update engine state + if(!c.fail && c.record !== null && c.record.ready) { + _update(c, c.record); + } + } + + return rval; + }; + + /** + * Requests that application data be packaged into a TLS record. The + * tlsDataReady handler will be called when the TLS record(s) have been + * prepared. + * + * @param data the application data, as a raw 'binary' encoded string, to + * be sent; to send utf-16/utf-8 string data, use the return value + * of util.encodeUtf8(str). + * + * @return true on success, false on failure. + */ + c.prepare = function(data) { + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.application_data, + data: forge.util.createBuffer(data) + })); + return tls.flush(c); + }; + + /** + * Requests that a heartbeat request be packaged into a TLS record for + * transmission. The tlsDataReady handler will be called when TLS record(s) + * have been prepared. + * + * When a heartbeat response has been received, the heartbeatReceived + * handler will be called with the matching payload. This handler can + * be used to clear a retransmission timer, etc. + * + * @param payload the heartbeat data to send as the payload in the message. + * @param [payloadLength] the payload length to use, defaults to the + * actual payload length. + * + * @return true on success, false on failure. + */ + c.prepareHeartbeatRequest = function(payload, payloadLength) { + if(payload instanceof forge.util.ByteBuffer) { + payload = payload.bytes(); + } + if(typeof payloadLength === 'undefined') { + payloadLength = payload.length; + } + c.expectedHeartbeatPayload = payload; + tls.queue(c, tls.createRecord(c, { + type: tls.ContentType.heartbeat, + data: tls.createHeartbeat( + tls.HeartbeatMessageType.heartbeat_request, payload, payloadLength) + })); + return tls.flush(c); + }; + + /** + * Closes the connection (sends a close_notify alert). + * + * @param clearFail true to clear the fail flag (default: true). + */ + c.close = function(clearFail) { + // save session if connection didn't fail + if(!c.fail && c.sessionCache && c.session) { + // only need to preserve session ID, version, and security params + var session = { + id: c.session.id, + version: c.session.version, + sp: c.session.sp + }; + session.sp.keys = null; + c.sessionCache.setSession(session.id, session); + } + + if(c.open) { + // connection no longer open, clear input + c.open = false; + c.input.clear(); + + // if connected or handshaking, send an alert + if(c.isConnected || c.handshaking) { + c.isConnected = c.handshaking = false; + + // send close_notify alert + tls.queue(c, tls.createAlert(c, { + level: tls.Alert.Level.warning, + description: tls.Alert.Description.close_notify + })); + tls.flush(c); + } + + // call handler + c.closed(c); + } + + // reset TLS connection, do not clear fail flag + c.reset(clearFail); + }; + + return c; +}; + +/* TLS API */ +module.exports = forge.tls = forge.tls || {}; + +// expose non-functions +for(var key in tls) { + if(typeof tls[key] !== 'function') { + forge.tls[key] = tls[key]; + } +} + +// expose prf_tls1 for testing +forge.tls.prf_tls1 = prf_TLS1; + +// expose sha1 hmac method +forge.tls.hmac_sha1 = hmac_sha1; + +// expose session cache creation +forge.tls.createSessionCache = tls.createSessionCache; + +/** + * Creates a new TLS connection. This does not make any assumptions about the + * transport layer that TLS is working on top of, ie: it does not assume there + * is a TCP/IP connection or establish one. A TLS connection is totally + * abstracted away from the layer is runs on top of, it merely establishes a + * secure channel between a client" and a "server". + * + * A TLS connection contains 4 connection states: pending read and write, and + * current read and write. + * + * At initialization, the current read and write states will be null. Only once + * the security parameters have been set and the keys have been generated can + * the pending states be converted into current states. Current states will be + * updated for each record processed. + * + * A custom certificate verify callback may be provided to check information + * like the common name on the server's certificate. It will be called for + * every certificate in the chain. It has the following signature: + * + * variable func(c, certs, index, preVerify) + * Where: + * c The TLS connection + * verified Set to true if certificate was verified, otherwise the alert + * tls.Alert.Description for why the certificate failed. + * depth The current index in the chain, where 0 is the server's cert. + * certs The certificate chain, *NOTE* if the server was anonymous then + * the chain will be empty. + * + * The function returns true on success and on failure either the appropriate + * tls.Alert.Description or an object with 'alert' set to the appropriate + * tls.Alert.Description and 'message' set to a custom error message. If true + * is not returned then the connection will abort using, in order of + * availability, first the returned alert description, second the preVerify + * alert description, and lastly the default 'bad_certificate'. + * + * There are three callbacks that can be used to make use of client-side + * certificates where each takes the TLS connection as the first parameter: + * + * getCertificate(conn, hint) + * The second parameter is a hint as to which certificate should be + * returned. If the connection entity is a client, then the hint will be + * the CertificateRequest message from the server that is part of the + * TLS protocol. If the connection entity is a server, then it will be + * the servername list provided via an SNI extension the ClientHello, if + * one was provided (empty array if not). The hint can be examined to + * determine which certificate to use (advanced). Most implementations + * will just return a certificate. The return value must be a + * PEM-formatted certificate or an array of PEM-formatted certificates + * that constitute a certificate chain, with the first in the array/chain + * being the client's certificate. + * getPrivateKey(conn, certificate) + * The second parameter is an forge.pki X.509 certificate object that + * is associated with the requested private key. The return value must + * be a PEM-formatted private key. + * getSignature(conn, bytes, callback) + * This callback can be used instead of getPrivateKey if the private key + * is not directly accessible in javascript or should not be. For + * instance, a secure external web service could provide the signature + * in exchange for appropriate credentials. The second parameter is a + * string of bytes to be signed that are part of the TLS protocol. These + * bytes are used to verify that the private key for the previously + * provided client-side certificate is accessible to the client. The + * callback is a function that takes 2 parameters, the TLS connection + * and the RSA encrypted (signed) bytes as a string. This callback must + * be called once the signature is ready. + * + * @param options the options for this connection: + * server: true if the connection is server-side, false for client. + * sessionId: a session ID to reuse, null for a new connection. + * caStore: an array of certificates to trust. + * sessionCache: a session cache to use. + * cipherSuites: an optional array of cipher suites to use, + * see tls.CipherSuites. + * connected: function(conn) called when the first handshake completes. + * virtualHost: the virtual server name to use in a TLS SNI extension. + * verifyClient: true to require a client certificate in server mode, + * 'optional' to request one, false not to (default: false). + * verify: a handler used to custom verify certificates in the chain. + * verifyOptions: an object with options for the certificate chain validation. + * See documentation of pki.verifyCertificateChain for possible options. + * verifyOptions.verify is ignored. If you wish to specify a verify handler + * use the verify key. + * getCertificate: an optional callback used to get a certificate or + * a chain of certificates (as an array). + * getPrivateKey: an optional callback used to get a private key. + * getSignature: an optional callback used to get a signature. + * tlsDataReady: function(conn) called when TLS protocol data has been + * prepared and is ready to be used (typically sent over a socket + * connection to its destination), read from conn.tlsData buffer. + * dataReady: function(conn) called when application data has + * been parsed from a TLS record and should be consumed by the + * application, read from conn.data buffer. + * closed: function(conn) called when the connection has been closed. + * error: function(conn, error) called when there was an error. + * deflate: function(inBytes) if provided, will deflate TLS records using + * the deflate algorithm if the server supports it. + * inflate: function(inBytes) if provided, will inflate TLS records using + * the deflate algorithm if the server supports it. + * + * @return the new TLS connection. + */ +forge.tls.createConnection = tls.createConnection; diff --git a/node_modules/node-forge/lib/tlssocket.js b/node_modules/node-forge/lib/tlssocket.js new file mode 100644 index 0000000..d09b650 --- /dev/null +++ b/node_modules/node-forge/lib/tlssocket.js @@ -0,0 +1,249 @@ +/** + * Socket wrapping functions for TLS. + * + * @author Dave Longley + * + * Copyright (c) 2009-2012 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./tls'); + +/** + * Wraps a forge.net socket with a TLS layer. + * + * @param options: + * sessionId: a session ID to reuse, null for a new connection if no session + * cache is provided or it is empty. + * caStore: an array of certificates to trust. + * sessionCache: a session cache to use. + * cipherSuites: an optional array of cipher suites to use, see + * tls.CipherSuites. + * socket: the socket to wrap. + * virtualHost: the virtual server name to use in a TLS SNI extension. + * verify: a handler used to custom verify certificates in the chain. + * getCertificate: an optional callback used to get a certificate. + * getPrivateKey: an optional callback used to get a private key. + * getSignature: an optional callback used to get a signature. + * deflate: function(inBytes) if provided, will deflate TLS records using + * the deflate algorithm if the server supports it. + * inflate: function(inBytes) if provided, will inflate TLS records using + * the deflate algorithm if the server supports it. + * + * @return the TLS-wrapped socket. + */ +forge.tls.wrapSocket = function(options) { + // get raw socket + var socket = options.socket; + + // create TLS socket + var tlsSocket = { + id: socket.id, + // set handlers + connected: socket.connected || function(e) {}, + closed: socket.closed || function(e) {}, + data: socket.data || function(e) {}, + error: socket.error || function(e) {} + }; + + // create TLS connection + var c = forge.tls.createConnection({ + server: false, + sessionId: options.sessionId || null, + caStore: options.caStore || [], + sessionCache: options.sessionCache || null, + cipherSuites: options.cipherSuites || null, + virtualHost: options.virtualHost, + verify: options.verify, + getCertificate: options.getCertificate, + getPrivateKey: options.getPrivateKey, + getSignature: options.getSignature, + deflate: options.deflate, + inflate: options.inflate, + connected: function(c) { + // first handshake complete, call handler + if(c.handshakes === 1) { + tlsSocket.connected({ + id: socket.id, + type: 'connect', + bytesAvailable: c.data.length() + }); + } + }, + tlsDataReady: function(c) { + // send TLS data over socket + return socket.send(c.tlsData.getBytes()); + }, + dataReady: function(c) { + // indicate application data is ready + tlsSocket.data({ + id: socket.id, + type: 'socketData', + bytesAvailable: c.data.length() + }); + }, + closed: function(c) { + // close socket + socket.close(); + }, + error: function(c, e) { + // send error, close socket + tlsSocket.error({ + id: socket.id, + type: 'tlsError', + message: e.message, + bytesAvailable: 0, + error: e + }); + socket.close(); + } + }); + + // handle doing handshake after connecting + socket.connected = function(e) { + c.handshake(options.sessionId); + }; + + // handle closing TLS connection + socket.closed = function(e) { + if(c.open && c.handshaking) { + // error + tlsSocket.error({ + id: socket.id, + type: 'ioError', + message: 'Connection closed during handshake.', + bytesAvailable: 0 + }); + } + c.close(); + + // call socket handler + tlsSocket.closed({ + id: socket.id, + type: 'close', + bytesAvailable: 0 + }); + }; + + // handle error on socket + socket.error = function(e) { + // error + tlsSocket.error({ + id: socket.id, + type: e.type, + message: e.message, + bytesAvailable: 0 + }); + c.close(); + }; + + // handle receiving raw TLS data from socket + var _requiredBytes = 0; + socket.data = function(e) { + // drop data if connection not open + if(!c.open) { + socket.receive(e.bytesAvailable); + } else { + // only receive if there are enough bytes available to + // process a record + if(e.bytesAvailable >= _requiredBytes) { + var count = Math.max(e.bytesAvailable, _requiredBytes); + var data = socket.receive(count); + if(data !== null) { + _requiredBytes = c.process(data); + } + } + } + }; + + /** + * Destroys this socket. + */ + tlsSocket.destroy = function() { + socket.destroy(); + }; + + /** + * Sets this socket's TLS session cache. This should be called before + * the socket is connected or after it is closed. + * + * The cache is an object mapping session IDs to internal opaque state. + * An application might need to change the cache used by a particular + * tlsSocket between connections if it accesses multiple TLS hosts. + * + * @param cache the session cache to use. + */ + tlsSocket.setSessionCache = function(cache) { + c.sessionCache = tls.createSessionCache(cache); + }; + + /** + * Connects this socket. + * + * @param options: + * host: the host to connect to. + * port: the port to connect to. + * policyPort: the policy port to use (if non-default), 0 to + * use the flash default. + * policyUrl: the policy file URL to use (instead of port). + */ + tlsSocket.connect = function(options) { + socket.connect(options); + }; + + /** + * Closes this socket. + */ + tlsSocket.close = function() { + c.close(); + }; + + /** + * Determines if the socket is connected or not. + * + * @return true if connected, false if not. + */ + tlsSocket.isConnected = function() { + return c.isConnected && socket.isConnected(); + }; + + /** + * Writes bytes to this socket. + * + * @param bytes the bytes (as a string) to write. + * + * @return true on success, false on failure. + */ + tlsSocket.send = function(bytes) { + return c.prepare(bytes); + }; + + /** + * Reads bytes from this socket (non-blocking). Fewer than the number of + * bytes requested may be read if enough bytes are not available. + * + * This method should be called from the data handler if there are enough + * bytes available. To see how many bytes are available, check the + * 'bytesAvailable' property on the event in the data handler or call the + * bytesAvailable() function on the socket. If the browser is msie, then the + * bytesAvailable() function should be used to avoid race conditions. + * Otherwise, using the property on the data handler's event may be quicker. + * + * @param count the maximum number of bytes to read. + * + * @return the bytes read (as a string) or null on error. + */ + tlsSocket.receive = function(count) { + return c.data.getBytes(count); + }; + + /** + * Gets the number of bytes available for receiving on the socket. + * + * @return the number of bytes available for receiving. + */ + tlsSocket.bytesAvailable = function() { + return c.data.length(); + }; + + return tlsSocket; +}; diff --git a/node_modules/node-forge/lib/util.js b/node_modules/node-forge/lib/util.js new file mode 100644 index 0000000..a866092 --- /dev/null +++ b/node_modules/node-forge/lib/util.js @@ -0,0 +1,3000 @@ +/** + * Utility functions for web applications. + * + * @author Dave Longley + * + * Copyright (c) 2010-2018 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +var baseN = require('./baseN'); + +/* Utilities API */ +var util = module.exports = forge.util = forge.util || {}; + +// define setImmediate and nextTick +(function() { + // use native nextTick (unless we're in webpack) + // webpack (or better node-libs-browser polyfill) sets process.browser. + // this way we can detect webpack properly + if(typeof process !== 'undefined' && process.nextTick && !process.browser) { + util.nextTick = process.nextTick; + if(typeof setImmediate === 'function') { + util.setImmediate = setImmediate; + } else { + // polyfill setImmediate with nextTick, older versions of node + // (those w/o setImmediate) won't totally starve IO + util.setImmediate = util.nextTick; + } + return; + } + + // polyfill nextTick with native setImmediate + if(typeof setImmediate === 'function') { + util.setImmediate = function() { return setImmediate.apply(undefined, arguments); }; + util.nextTick = function(callback) { + return setImmediate(callback); + }; + return; + } + + /* Note: A polyfill upgrade pattern is used here to allow combining + polyfills. For example, MutationObserver is fast, but blocks UI updates, + so it needs to allow UI updates periodically, so it falls back on + postMessage or setTimeout. */ + + // polyfill with setTimeout + util.setImmediate = function(callback) { + setTimeout(callback, 0); + }; + + // upgrade polyfill to use postMessage + if(typeof window !== 'undefined' && + typeof window.postMessage === 'function') { + var msg = 'forge.setImmediate'; + var callbacks = []; + util.setImmediate = function(callback) { + callbacks.push(callback); + // only send message when one hasn't been sent in + // the current turn of the event loop + if(callbacks.length === 1) { + window.postMessage(msg, '*'); + } + }; + function handler(event) { + if(event.source === window && event.data === msg) { + event.stopPropagation(); + var copy = callbacks.slice(); + callbacks.length = 0; + copy.forEach(function(callback) { + callback(); + }); + } + } + window.addEventListener('message', handler, true); + } + + // upgrade polyfill to use MutationObserver + if(typeof MutationObserver !== 'undefined') { + // polyfill with MutationObserver + var now = Date.now(); + var attr = true; + var div = document.createElement('div'); + var callbacks = []; + new MutationObserver(function() { + var copy = callbacks.slice(); + callbacks.length = 0; + copy.forEach(function(callback) { + callback(); + }); + }).observe(div, {attributes: true}); + var oldSetImmediate = util.setImmediate; + util.setImmediate = function(callback) { + if(Date.now() - now > 15) { + now = Date.now(); + oldSetImmediate(callback); + } else { + callbacks.push(callback); + // only trigger observer when it hasn't been triggered in + // the current turn of the event loop + if(callbacks.length === 1) { + div.setAttribute('a', attr = !attr); + } + } + }; + } + + util.nextTick = util.setImmediate; +})(); + +// check if running under Node.js +util.isNodejs = + typeof process !== 'undefined' && process.versions && process.versions.node; + + +// 'self' will also work in Web Workers (instance of WorkerGlobalScope) while +// it will point to `window` in the main thread. +// To remain compatible with older browsers, we fall back to 'window' if 'self' +// is not available. +util.globalScope = (function() { + if(util.isNodejs) { + return global; + } + + return typeof self === 'undefined' ? window : self; +})(); + +// define isArray +util.isArray = Array.isArray || function(x) { + return Object.prototype.toString.call(x) === '[object Array]'; +}; + +// define isArrayBuffer +util.isArrayBuffer = function(x) { + return typeof ArrayBuffer !== 'undefined' && x instanceof ArrayBuffer; +}; + +// define isArrayBufferView +util.isArrayBufferView = function(x) { + return x && util.isArrayBuffer(x.buffer) && x.byteLength !== undefined; +}; + +/** + * Ensure a bits param is 8, 16, 24, or 32. Used to validate input for + * algorithms where bit manipulation, JavaScript limitations, and/or algorithm + * design only allow for byte operations of a limited size. + * + * @param n number of bits. + * + * Throw Error if n invalid. + */ +function _checkBitsParam(n) { + if(!(n === 8 || n === 16 || n === 24 || n === 32)) { + throw new Error('Only 8, 16, 24, or 32 bits supported: ' + n); + } +} + +// TODO: set ByteBuffer to best available backing +util.ByteBuffer = ByteStringBuffer; + +/** Buffer w/BinaryString backing */ + +/** + * Constructor for a binary string backed byte buffer. + * + * @param [b] the bytes to wrap (either encoded as string, one byte per + * character, or as an ArrayBuffer or Typed Array). + */ +function ByteStringBuffer(b) { + // TODO: update to match DataBuffer API + + // the data in this buffer + this.data = ''; + // the pointer for reading from this buffer + this.read = 0; + + if(typeof b === 'string') { + this.data = b; + } else if(util.isArrayBuffer(b) || util.isArrayBufferView(b)) { + if(typeof Buffer !== 'undefined' && b instanceof Buffer) { + this.data = b.toString('binary'); + } else { + // convert native buffer to forge buffer + // FIXME: support native buffers internally instead + var arr = new Uint8Array(b); + try { + this.data = String.fromCharCode.apply(null, arr); + } catch(e) { + for(var i = 0; i < arr.length; ++i) { + this.putByte(arr[i]); + } + } + } + } else if(b instanceof ByteStringBuffer || + (typeof b === 'object' && typeof b.data === 'string' && + typeof b.read === 'number')) { + // copy existing buffer + this.data = b.data; + this.read = b.read; + } + + // used for v8 optimization + this._constructedStringLength = 0; +} +util.ByteStringBuffer = ByteStringBuffer; + +/* Note: This is an optimization for V8-based browsers. When V8 concatenates + a string, the strings are only joined logically using a "cons string" or + "constructed/concatenated string". These containers keep references to one + another and can result in very large memory usage. For example, if a 2MB + string is constructed by concatenating 4 bytes together at a time, the + memory usage will be ~44MB; so ~22x increase. The strings are only joined + together when an operation requiring their joining takes place, such as + substr(). This function is called when adding data to this buffer to ensure + these types of strings are periodically joined to reduce the memory + footprint. */ +var _MAX_CONSTRUCTED_STRING_LENGTH = 4096; +util.ByteStringBuffer.prototype._optimizeConstructedString = function(x) { + this._constructedStringLength += x; + if(this._constructedStringLength > _MAX_CONSTRUCTED_STRING_LENGTH) { + // this substr() should cause the constructed string to join + this.data.substr(0, 1); + this._constructedStringLength = 0; + } +}; + +/** + * Gets the number of bytes in this buffer. + * + * @return the number of bytes in this buffer. + */ +util.ByteStringBuffer.prototype.length = function() { + return this.data.length - this.read; +}; + +/** + * Gets whether or not this buffer is empty. + * + * @return true if this buffer is empty, false if not. + */ +util.ByteStringBuffer.prototype.isEmpty = function() { + return this.length() <= 0; +}; + +/** + * Puts a byte in this buffer. + * + * @param b the byte to put. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putByte = function(b) { + return this.putBytes(String.fromCharCode(b)); +}; + +/** + * Puts a byte in this buffer N times. + * + * @param b the byte to put. + * @param n the number of bytes of value b to put. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.fillWithByte = function(b, n) { + b = String.fromCharCode(b); + var d = this.data; + while(n > 0) { + if(n & 1) { + d += b; + } + n >>>= 1; + if(n > 0) { + b += b; + } + } + this.data = d; + this._optimizeConstructedString(n); + return this; +}; + +/** + * Puts bytes in this buffer. + * + * @param bytes the bytes (as a binary encoded string) to put. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putBytes = function(bytes) { + this.data += bytes; + this._optimizeConstructedString(bytes.length); + return this; +}; + +/** + * Puts a UTF-16 encoded string into this buffer. + * + * @param str the string to put. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putString = function(str) { + return this.putBytes(util.encodeUtf8(str)); +}; + +/** + * Puts a 16-bit integer in this buffer in big-endian order. + * + * @param i the 16-bit integer. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putInt16 = function(i) { + return this.putBytes( + String.fromCharCode(i >> 8 & 0xFF) + + String.fromCharCode(i & 0xFF)); +}; + +/** + * Puts a 24-bit integer in this buffer in big-endian order. + * + * @param i the 24-bit integer. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putInt24 = function(i) { + return this.putBytes( + String.fromCharCode(i >> 16 & 0xFF) + + String.fromCharCode(i >> 8 & 0xFF) + + String.fromCharCode(i & 0xFF)); +}; + +/** + * Puts a 32-bit integer in this buffer in big-endian order. + * + * @param i the 32-bit integer. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putInt32 = function(i) { + return this.putBytes( + String.fromCharCode(i >> 24 & 0xFF) + + String.fromCharCode(i >> 16 & 0xFF) + + String.fromCharCode(i >> 8 & 0xFF) + + String.fromCharCode(i & 0xFF)); +}; + +/** + * Puts a 16-bit integer in this buffer in little-endian order. + * + * @param i the 16-bit integer. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putInt16Le = function(i) { + return this.putBytes( + String.fromCharCode(i & 0xFF) + + String.fromCharCode(i >> 8 & 0xFF)); +}; + +/** + * Puts a 24-bit integer in this buffer in little-endian order. + * + * @param i the 24-bit integer. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putInt24Le = function(i) { + return this.putBytes( + String.fromCharCode(i & 0xFF) + + String.fromCharCode(i >> 8 & 0xFF) + + String.fromCharCode(i >> 16 & 0xFF)); +}; + +/** + * Puts a 32-bit integer in this buffer in little-endian order. + * + * @param i the 32-bit integer. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putInt32Le = function(i) { + return this.putBytes( + String.fromCharCode(i & 0xFF) + + String.fromCharCode(i >> 8 & 0xFF) + + String.fromCharCode(i >> 16 & 0xFF) + + String.fromCharCode(i >> 24 & 0xFF)); +}; + +/** + * Puts an n-bit integer in this buffer in big-endian order. + * + * @param i the n-bit integer. + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putInt = function(i, n) { + _checkBitsParam(n); + var bytes = ''; + do { + n -= 8; + bytes += String.fromCharCode((i >> n) & 0xFF); + } while(n > 0); + return this.putBytes(bytes); +}; + +/** + * Puts a signed n-bit integer in this buffer in big-endian order. Two's + * complement representation is used. + * + * @param i the n-bit integer. + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putSignedInt = function(i, n) { + // putInt checks n + if(i < 0) { + i += 2 << (n - 1); + } + return this.putInt(i, n); +}; + +/** + * Puts the given buffer into this buffer. + * + * @param buffer the buffer to put into this one. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.putBuffer = function(buffer) { + return this.putBytes(buffer.getBytes()); +}; + +/** + * Gets a byte from this buffer and advances the read pointer by 1. + * + * @return the byte. + */ +util.ByteStringBuffer.prototype.getByte = function() { + return this.data.charCodeAt(this.read++); +}; + +/** + * Gets a uint16 from this buffer in big-endian order and advances the read + * pointer by 2. + * + * @return the uint16. + */ +util.ByteStringBuffer.prototype.getInt16 = function() { + var rval = ( + this.data.charCodeAt(this.read) << 8 ^ + this.data.charCodeAt(this.read + 1)); + this.read += 2; + return rval; +}; + +/** + * Gets a uint24 from this buffer in big-endian order and advances the read + * pointer by 3. + * + * @return the uint24. + */ +util.ByteStringBuffer.prototype.getInt24 = function() { + var rval = ( + this.data.charCodeAt(this.read) << 16 ^ + this.data.charCodeAt(this.read + 1) << 8 ^ + this.data.charCodeAt(this.read + 2)); + this.read += 3; + return rval; +}; + +/** + * Gets a uint32 from this buffer in big-endian order and advances the read + * pointer by 4. + * + * @return the word. + */ +util.ByteStringBuffer.prototype.getInt32 = function() { + var rval = ( + this.data.charCodeAt(this.read) << 24 ^ + this.data.charCodeAt(this.read + 1) << 16 ^ + this.data.charCodeAt(this.read + 2) << 8 ^ + this.data.charCodeAt(this.read + 3)); + this.read += 4; + return rval; +}; + +/** + * Gets a uint16 from this buffer in little-endian order and advances the read + * pointer by 2. + * + * @return the uint16. + */ +util.ByteStringBuffer.prototype.getInt16Le = function() { + var rval = ( + this.data.charCodeAt(this.read) ^ + this.data.charCodeAt(this.read + 1) << 8); + this.read += 2; + return rval; +}; + +/** + * Gets a uint24 from this buffer in little-endian order and advances the read + * pointer by 3. + * + * @return the uint24. + */ +util.ByteStringBuffer.prototype.getInt24Le = function() { + var rval = ( + this.data.charCodeAt(this.read) ^ + this.data.charCodeAt(this.read + 1) << 8 ^ + this.data.charCodeAt(this.read + 2) << 16); + this.read += 3; + return rval; +}; + +/** + * Gets a uint32 from this buffer in little-endian order and advances the read + * pointer by 4. + * + * @return the word. + */ +util.ByteStringBuffer.prototype.getInt32Le = function() { + var rval = ( + this.data.charCodeAt(this.read) ^ + this.data.charCodeAt(this.read + 1) << 8 ^ + this.data.charCodeAt(this.read + 2) << 16 ^ + this.data.charCodeAt(this.read + 3) << 24); + this.read += 4; + return rval; +}; + +/** + * Gets an n-bit integer from this buffer in big-endian order and advances the + * read pointer by ceil(n/8). + * + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return the integer. + */ +util.ByteStringBuffer.prototype.getInt = function(n) { + _checkBitsParam(n); + var rval = 0; + do { + // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits. + rval = (rval << 8) + this.data.charCodeAt(this.read++); + n -= 8; + } while(n > 0); + return rval; +}; + +/** + * Gets a signed n-bit integer from this buffer in big-endian order, using + * two's complement, and advances the read pointer by n/8. + * + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return the integer. + */ +util.ByteStringBuffer.prototype.getSignedInt = function(n) { + // getInt checks n + var x = this.getInt(n); + var max = 2 << (n - 2); + if(x >= max) { + x -= max << 1; + } + return x; +}; + +/** + * Reads bytes out as a binary encoded string and clears them from the + * buffer. Note that the resulting string is binary encoded (in node.js this + * encoding is referred to as `binary`, it is *not* `utf8`). + * + * @param count the number of bytes to read, undefined or null for all. + * + * @return a binary encoded string of bytes. + */ +util.ByteStringBuffer.prototype.getBytes = function(count) { + var rval; + if(count) { + // read count bytes + count = Math.min(this.length(), count); + rval = this.data.slice(this.read, this.read + count); + this.read += count; + } else if(count === 0) { + rval = ''; + } else { + // read all bytes, optimize to only copy when needed + rval = (this.read === 0) ? this.data : this.data.slice(this.read); + this.clear(); + } + return rval; +}; + +/** + * Gets a binary encoded string of the bytes from this buffer without + * modifying the read pointer. + * + * @param count the number of bytes to get, omit to get all. + * + * @return a string full of binary encoded characters. + */ +util.ByteStringBuffer.prototype.bytes = function(count) { + return (typeof(count) === 'undefined' ? + this.data.slice(this.read) : + this.data.slice(this.read, this.read + count)); +}; + +/** + * Gets a byte at the given index without modifying the read pointer. + * + * @param i the byte index. + * + * @return the byte. + */ +util.ByteStringBuffer.prototype.at = function(i) { + return this.data.charCodeAt(this.read + i); +}; + +/** + * Puts a byte at the given index without modifying the read pointer. + * + * @param i the byte index. + * @param b the byte to put. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.setAt = function(i, b) { + this.data = this.data.substr(0, this.read + i) + + String.fromCharCode(b) + + this.data.substr(this.read + i + 1); + return this; +}; + +/** + * Gets the last byte without modifying the read pointer. + * + * @return the last byte. + */ +util.ByteStringBuffer.prototype.last = function() { + return this.data.charCodeAt(this.data.length - 1); +}; + +/** + * Creates a copy of this buffer. + * + * @return the copy. + */ +util.ByteStringBuffer.prototype.copy = function() { + var c = util.createBuffer(this.data); + c.read = this.read; + return c; +}; + +/** + * Compacts this buffer. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.compact = function() { + if(this.read > 0) { + this.data = this.data.slice(this.read); + this.read = 0; + } + return this; +}; + +/** + * Clears this buffer. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.clear = function() { + this.data = ''; + this.read = 0; + return this; +}; + +/** + * Shortens this buffer by triming bytes off of the end of this buffer. + * + * @param count the number of bytes to trim off. + * + * @return this buffer. + */ +util.ByteStringBuffer.prototype.truncate = function(count) { + var len = Math.max(0, this.length() - count); + this.data = this.data.substr(this.read, len); + this.read = 0; + return this; +}; + +/** + * Converts this buffer to a hexadecimal string. + * + * @return a hexadecimal string. + */ +util.ByteStringBuffer.prototype.toHex = function() { + var rval = ''; + for(var i = this.read; i < this.data.length; ++i) { + var b = this.data.charCodeAt(i); + if(b < 16) { + rval += '0'; + } + rval += b.toString(16); + } + return rval; +}; + +/** + * Converts this buffer to a UTF-16 string (standard JavaScript string). + * + * @return a UTF-16 string. + */ +util.ByteStringBuffer.prototype.toString = function() { + return util.decodeUtf8(this.bytes()); +}; + +/** End Buffer w/BinaryString backing */ + +/** Buffer w/UInt8Array backing */ + +/** + * FIXME: Experimental. Do not use yet. + * + * Constructor for an ArrayBuffer-backed byte buffer. + * + * The buffer may be constructed from a string, an ArrayBuffer, DataView, or a + * TypedArray. + * + * If a string is given, its encoding should be provided as an option, + * otherwise it will default to 'binary'. A 'binary' string is encoded such + * that each character is one byte in length and size. + * + * If an ArrayBuffer, DataView, or TypedArray is given, it will be used + * *directly* without any copying. Note that, if a write to the buffer requires + * more space, the buffer will allocate a new backing ArrayBuffer to + * accommodate. The starting read and write offsets for the buffer may be + * given as options. + * + * @param [b] the initial bytes for this buffer. + * @param options the options to use: + * [readOffset] the starting read offset to use (default: 0). + * [writeOffset] the starting write offset to use (default: the + * length of the first parameter). + * [growSize] the minimum amount, in bytes, to grow the buffer by to + * accommodate writes (default: 1024). + * [encoding] the encoding ('binary', 'utf8', 'utf16', 'hex') for the + * first parameter, if it is a string (default: 'binary'). + */ +function DataBuffer(b, options) { + // default options + options = options || {}; + + // pointers for read from/write to buffer + this.read = options.readOffset || 0; + this.growSize = options.growSize || 1024; + + var isArrayBuffer = util.isArrayBuffer(b); + var isArrayBufferView = util.isArrayBufferView(b); + if(isArrayBuffer || isArrayBufferView) { + // use ArrayBuffer directly + if(isArrayBuffer) { + this.data = new DataView(b); + } else { + // TODO: adjust read/write offset based on the type of view + // or specify that this must be done in the options ... that the + // offsets are byte-based + this.data = new DataView(b.buffer, b.byteOffset, b.byteLength); + } + this.write = ('writeOffset' in options ? + options.writeOffset : this.data.byteLength); + return; + } + + // initialize to empty array buffer and add any given bytes using putBytes + this.data = new DataView(new ArrayBuffer(0)); + this.write = 0; + + if(b !== null && b !== undefined) { + this.putBytes(b); + } + + if('writeOffset' in options) { + this.write = options.writeOffset; + } +} +util.DataBuffer = DataBuffer; + +/** + * Gets the number of bytes in this buffer. + * + * @return the number of bytes in this buffer. + */ +util.DataBuffer.prototype.length = function() { + return this.write - this.read; +}; + +/** + * Gets whether or not this buffer is empty. + * + * @return true if this buffer is empty, false if not. + */ +util.DataBuffer.prototype.isEmpty = function() { + return this.length() <= 0; +}; + +/** + * Ensures this buffer has enough empty space to accommodate the given number + * of bytes. An optional parameter may be given that indicates a minimum + * amount to grow the buffer if necessary. If the parameter is not given, + * the buffer will be grown by some previously-specified default amount + * or heuristic. + * + * @param amount the number of bytes to accommodate. + * @param [growSize] the minimum amount, in bytes, to grow the buffer by if + * necessary. + */ +util.DataBuffer.prototype.accommodate = function(amount, growSize) { + if(this.length() >= amount) { + return this; + } + growSize = Math.max(growSize || this.growSize, amount); + + // grow buffer + var src = new Uint8Array( + this.data.buffer, this.data.byteOffset, this.data.byteLength); + var dst = new Uint8Array(this.length() + growSize); + dst.set(src); + this.data = new DataView(dst.buffer); + + return this; +}; + +/** + * Puts a byte in this buffer. + * + * @param b the byte to put. + * + * @return this buffer. + */ +util.DataBuffer.prototype.putByte = function(b) { + this.accommodate(1); + this.data.setUint8(this.write++, b); + return this; +}; + +/** + * Puts a byte in this buffer N times. + * + * @param b the byte to put. + * @param n the number of bytes of value b to put. + * + * @return this buffer. + */ +util.DataBuffer.prototype.fillWithByte = function(b, n) { + this.accommodate(n); + for(var i = 0; i < n; ++i) { + this.data.setUint8(b); + } + return this; +}; + +/** + * Puts bytes in this buffer. The bytes may be given as a string, an + * ArrayBuffer, a DataView, or a TypedArray. + * + * @param bytes the bytes to put. + * @param [encoding] the encoding for the first parameter ('binary', 'utf8', + * 'utf16', 'hex'), if it is a string (default: 'binary'). + * + * @return this buffer. + */ +util.DataBuffer.prototype.putBytes = function(bytes, encoding) { + if(util.isArrayBufferView(bytes)) { + var src = new Uint8Array(bytes.buffer, bytes.byteOffset, bytes.byteLength); + var len = src.byteLength - src.byteOffset; + this.accommodate(len); + var dst = new Uint8Array(this.data.buffer, this.write); + dst.set(src); + this.write += len; + return this; + } + + if(util.isArrayBuffer(bytes)) { + var src = new Uint8Array(bytes); + this.accommodate(src.byteLength); + var dst = new Uint8Array(this.data.buffer); + dst.set(src, this.write); + this.write += src.byteLength; + return this; + } + + // bytes is a util.DataBuffer or equivalent + if(bytes instanceof util.DataBuffer || + (typeof bytes === 'object' && + typeof bytes.read === 'number' && typeof bytes.write === 'number' && + util.isArrayBufferView(bytes.data))) { + var src = new Uint8Array(bytes.data.byteLength, bytes.read, bytes.length()); + this.accommodate(src.byteLength); + var dst = new Uint8Array(bytes.data.byteLength, this.write); + dst.set(src); + this.write += src.byteLength; + return this; + } + + if(bytes instanceof util.ByteStringBuffer) { + // copy binary string and process as the same as a string parameter below + bytes = bytes.data; + encoding = 'binary'; + } + + // string conversion + encoding = encoding || 'binary'; + if(typeof bytes === 'string') { + var view; + + // decode from string + if(encoding === 'hex') { + this.accommodate(Math.ceil(bytes.length / 2)); + view = new Uint8Array(this.data.buffer, this.write); + this.write += util.binary.hex.decode(bytes, view, this.write); + return this; + } + if(encoding === 'base64') { + this.accommodate(Math.ceil(bytes.length / 4) * 3); + view = new Uint8Array(this.data.buffer, this.write); + this.write += util.binary.base64.decode(bytes, view, this.write); + return this; + } + + // encode text as UTF-8 bytes + if(encoding === 'utf8') { + // encode as UTF-8 then decode string as raw binary + bytes = util.encodeUtf8(bytes); + encoding = 'binary'; + } + + // decode string as raw binary + if(encoding === 'binary' || encoding === 'raw') { + // one byte per character + this.accommodate(bytes.length); + view = new Uint8Array(this.data.buffer, this.write); + this.write += util.binary.raw.decode(view); + return this; + } + + // encode text as UTF-16 bytes + if(encoding === 'utf16') { + // two bytes per character + this.accommodate(bytes.length * 2); + view = new Uint16Array(this.data.buffer, this.write); + this.write += util.text.utf16.encode(view); + return this; + } + + throw new Error('Invalid encoding: ' + encoding); + } + + throw Error('Invalid parameter: ' + bytes); +}; + +/** + * Puts the given buffer into this buffer. + * + * @param buffer the buffer to put into this one. + * + * @return this buffer. + */ +util.DataBuffer.prototype.putBuffer = function(buffer) { + this.putBytes(buffer); + buffer.clear(); + return this; +}; + +/** + * Puts a string into this buffer. + * + * @param str the string to put. + * @param [encoding] the encoding for the string (default: 'utf16'). + * + * @return this buffer. + */ +util.DataBuffer.prototype.putString = function(str) { + return this.putBytes(str, 'utf16'); +}; + +/** + * Puts a 16-bit integer in this buffer in big-endian order. + * + * @param i the 16-bit integer. + * + * @return this buffer. + */ +util.DataBuffer.prototype.putInt16 = function(i) { + this.accommodate(2); + this.data.setInt16(this.write, i); + this.write += 2; + return this; +}; + +/** + * Puts a 24-bit integer in this buffer in big-endian order. + * + * @param i the 24-bit integer. + * + * @return this buffer. + */ +util.DataBuffer.prototype.putInt24 = function(i) { + this.accommodate(3); + this.data.setInt16(this.write, i >> 8 & 0xFFFF); + this.data.setInt8(this.write, i >> 16 & 0xFF); + this.write += 3; + return this; +}; + +/** + * Puts a 32-bit integer in this buffer in big-endian order. + * + * @param i the 32-bit integer. + * + * @return this buffer. + */ +util.DataBuffer.prototype.putInt32 = function(i) { + this.accommodate(4); + this.data.setInt32(this.write, i); + this.write += 4; + return this; +}; + +/** + * Puts a 16-bit integer in this buffer in little-endian order. + * + * @param i the 16-bit integer. + * + * @return this buffer. + */ +util.DataBuffer.prototype.putInt16Le = function(i) { + this.accommodate(2); + this.data.setInt16(this.write, i, true); + this.write += 2; + return this; +}; + +/** + * Puts a 24-bit integer in this buffer in little-endian order. + * + * @param i the 24-bit integer. + * + * @return this buffer. + */ +util.DataBuffer.prototype.putInt24Le = function(i) { + this.accommodate(3); + this.data.setInt8(this.write, i >> 16 & 0xFF); + this.data.setInt16(this.write, i >> 8 & 0xFFFF, true); + this.write += 3; + return this; +}; + +/** + * Puts a 32-bit integer in this buffer in little-endian order. + * + * @param i the 32-bit integer. + * + * @return this buffer. + */ +util.DataBuffer.prototype.putInt32Le = function(i) { + this.accommodate(4); + this.data.setInt32(this.write, i, true); + this.write += 4; + return this; +}; + +/** + * Puts an n-bit integer in this buffer in big-endian order. + * + * @param i the n-bit integer. + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return this buffer. + */ +util.DataBuffer.prototype.putInt = function(i, n) { + _checkBitsParam(n); + this.accommodate(n / 8); + do { + n -= 8; + this.data.setInt8(this.write++, (i >> n) & 0xFF); + } while(n > 0); + return this; +}; + +/** + * Puts a signed n-bit integer in this buffer in big-endian order. Two's + * complement representation is used. + * + * @param i the n-bit integer. + * @param n the number of bits in the integer. + * + * @return this buffer. + */ +util.DataBuffer.prototype.putSignedInt = function(i, n) { + _checkBitsParam(n); + this.accommodate(n / 8); + if(i < 0) { + i += 2 << (n - 1); + } + return this.putInt(i, n); +}; + +/** + * Gets a byte from this buffer and advances the read pointer by 1. + * + * @return the byte. + */ +util.DataBuffer.prototype.getByte = function() { + return this.data.getInt8(this.read++); +}; + +/** + * Gets a uint16 from this buffer in big-endian order and advances the read + * pointer by 2. + * + * @return the uint16. + */ +util.DataBuffer.prototype.getInt16 = function() { + var rval = this.data.getInt16(this.read); + this.read += 2; + return rval; +}; + +/** + * Gets a uint24 from this buffer in big-endian order and advances the read + * pointer by 3. + * + * @return the uint24. + */ +util.DataBuffer.prototype.getInt24 = function() { + var rval = ( + this.data.getInt16(this.read) << 8 ^ + this.data.getInt8(this.read + 2)); + this.read += 3; + return rval; +}; + +/** + * Gets a uint32 from this buffer in big-endian order and advances the read + * pointer by 4. + * + * @return the word. + */ +util.DataBuffer.prototype.getInt32 = function() { + var rval = this.data.getInt32(this.read); + this.read += 4; + return rval; +}; + +/** + * Gets a uint16 from this buffer in little-endian order and advances the read + * pointer by 2. + * + * @return the uint16. + */ +util.DataBuffer.prototype.getInt16Le = function() { + var rval = this.data.getInt16(this.read, true); + this.read += 2; + return rval; +}; + +/** + * Gets a uint24 from this buffer in little-endian order and advances the read + * pointer by 3. + * + * @return the uint24. + */ +util.DataBuffer.prototype.getInt24Le = function() { + var rval = ( + this.data.getInt8(this.read) ^ + this.data.getInt16(this.read + 1, true) << 8); + this.read += 3; + return rval; +}; + +/** + * Gets a uint32 from this buffer in little-endian order and advances the read + * pointer by 4. + * + * @return the word. + */ +util.DataBuffer.prototype.getInt32Le = function() { + var rval = this.data.getInt32(this.read, true); + this.read += 4; + return rval; +}; + +/** + * Gets an n-bit integer from this buffer in big-endian order and advances the + * read pointer by n/8. + * + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return the integer. + */ +util.DataBuffer.prototype.getInt = function(n) { + _checkBitsParam(n); + var rval = 0; + do { + // TODO: Use (rval * 0x100) if adding support for 33 to 53 bits. + rval = (rval << 8) + this.data.getInt8(this.read++); + n -= 8; + } while(n > 0); + return rval; +}; + +/** + * Gets a signed n-bit integer from this buffer in big-endian order, using + * two's complement, and advances the read pointer by n/8. + * + * @param n the number of bits in the integer (8, 16, 24, or 32). + * + * @return the integer. + */ +util.DataBuffer.prototype.getSignedInt = function(n) { + // getInt checks n + var x = this.getInt(n); + var max = 2 << (n - 2); + if(x >= max) { + x -= max << 1; + } + return x; +}; + +/** + * Reads bytes out as a binary encoded string and clears them from the + * buffer. + * + * @param count the number of bytes to read, undefined or null for all. + * + * @return a binary encoded string of bytes. + */ +util.DataBuffer.prototype.getBytes = function(count) { + // TODO: deprecate this method, it is poorly named and + // this.toString('binary') replaces it + // add a toTypedArray()/toArrayBuffer() function + var rval; + if(count) { + // read count bytes + count = Math.min(this.length(), count); + rval = this.data.slice(this.read, this.read + count); + this.read += count; + } else if(count === 0) { + rval = ''; + } else { + // read all bytes, optimize to only copy when needed + rval = (this.read === 0) ? this.data : this.data.slice(this.read); + this.clear(); + } + return rval; +}; + +/** + * Gets a binary encoded string of the bytes from this buffer without + * modifying the read pointer. + * + * @param count the number of bytes to get, omit to get all. + * + * @return a string full of binary encoded characters. + */ +util.DataBuffer.prototype.bytes = function(count) { + // TODO: deprecate this method, it is poorly named, add "getString()" + return (typeof(count) === 'undefined' ? + this.data.slice(this.read) : + this.data.slice(this.read, this.read + count)); +}; + +/** + * Gets a byte at the given index without modifying the read pointer. + * + * @param i the byte index. + * + * @return the byte. + */ +util.DataBuffer.prototype.at = function(i) { + return this.data.getUint8(this.read + i); +}; + +/** + * Puts a byte at the given index without modifying the read pointer. + * + * @param i the byte index. + * @param b the byte to put. + * + * @return this buffer. + */ +util.DataBuffer.prototype.setAt = function(i, b) { + this.data.setUint8(i, b); + return this; +}; + +/** + * Gets the last byte without modifying the read pointer. + * + * @return the last byte. + */ +util.DataBuffer.prototype.last = function() { + return this.data.getUint8(this.write - 1); +}; + +/** + * Creates a copy of this buffer. + * + * @return the copy. + */ +util.DataBuffer.prototype.copy = function() { + return new util.DataBuffer(this); +}; + +/** + * Compacts this buffer. + * + * @return this buffer. + */ +util.DataBuffer.prototype.compact = function() { + if(this.read > 0) { + var src = new Uint8Array(this.data.buffer, this.read); + var dst = new Uint8Array(src.byteLength); + dst.set(src); + this.data = new DataView(dst); + this.write -= this.read; + this.read = 0; + } + return this; +}; + +/** + * Clears this buffer. + * + * @return this buffer. + */ +util.DataBuffer.prototype.clear = function() { + this.data = new DataView(new ArrayBuffer(0)); + this.read = this.write = 0; + return this; +}; + +/** + * Shortens this buffer by triming bytes off of the end of this buffer. + * + * @param count the number of bytes to trim off. + * + * @return this buffer. + */ +util.DataBuffer.prototype.truncate = function(count) { + this.write = Math.max(0, this.length() - count); + this.read = Math.min(this.read, this.write); + return this; +}; + +/** + * Converts this buffer to a hexadecimal string. + * + * @return a hexadecimal string. + */ +util.DataBuffer.prototype.toHex = function() { + var rval = ''; + for(var i = this.read; i < this.data.byteLength; ++i) { + var b = this.data.getUint8(i); + if(b < 16) { + rval += '0'; + } + rval += b.toString(16); + } + return rval; +}; + +/** + * Converts this buffer to a string, using the given encoding. If no + * encoding is given, 'utf8' (UTF-8) is used. + * + * @param [encoding] the encoding to use: 'binary', 'utf8', 'utf16', 'hex', + * 'base64' (default: 'utf8'). + * + * @return a string representation of the bytes in this buffer. + */ +util.DataBuffer.prototype.toString = function(encoding) { + var view = new Uint8Array(this.data, this.read, this.length()); + encoding = encoding || 'utf8'; + + // encode to string + if(encoding === 'binary' || encoding === 'raw') { + return util.binary.raw.encode(view); + } + if(encoding === 'hex') { + return util.binary.hex.encode(view); + } + if(encoding === 'base64') { + return util.binary.base64.encode(view); + } + + // decode to text + if(encoding === 'utf8') { + return util.text.utf8.decode(view); + } + if(encoding === 'utf16') { + return util.text.utf16.decode(view); + } + + throw new Error('Invalid encoding: ' + encoding); +}; + +/** End Buffer w/UInt8Array backing */ + +/** + * Creates a buffer that stores bytes. A value may be given to populate the + * buffer with data. This value can either be string of encoded bytes or a + * regular string of characters. When passing a string of binary encoded + * bytes, the encoding `raw` should be given. This is also the default. When + * passing a string of characters, the encoding `utf8` should be given. + * + * @param [input] a string with encoded bytes to store in the buffer. + * @param [encoding] (default: 'raw', other: 'utf8'). + */ +util.createBuffer = function(input, encoding) { + // TODO: deprecate, use new ByteBuffer() instead + encoding = encoding || 'raw'; + if(input !== undefined && encoding === 'utf8') { + input = util.encodeUtf8(input); + } + return new util.ByteBuffer(input); +}; + +/** + * Fills a string with a particular value. If you want the string to be a byte + * string, pass in String.fromCharCode(theByte). + * + * @param c the character to fill the string with, use String.fromCharCode + * to fill the string with a byte value. + * @param n the number of characters of value c to fill with. + * + * @return the filled string. + */ +util.fillString = function(c, n) { + var s = ''; + while(n > 0) { + if(n & 1) { + s += c; + } + n >>>= 1; + if(n > 0) { + c += c; + } + } + return s; +}; + +/** + * Performs a per byte XOR between two byte strings and returns the result as a + * string of bytes. + * + * @param s1 first string of bytes. + * @param s2 second string of bytes. + * @param n the number of bytes to XOR. + * + * @return the XOR'd result. + */ +util.xorBytes = function(s1, s2, n) { + var s3 = ''; + var b = ''; + var t = ''; + var i = 0; + var c = 0; + for(; n > 0; --n, ++i) { + b = s1.charCodeAt(i) ^ s2.charCodeAt(i); + if(c >= 10) { + s3 += t; + t = ''; + c = 0; + } + t += String.fromCharCode(b); + ++c; + } + s3 += t; + return s3; +}; + +/** + * Converts a hex string into a 'binary' encoded string of bytes. + * + * @param hex the hexadecimal string to convert. + * + * @return the binary-encoded string of bytes. + */ +util.hexToBytes = function(hex) { + // TODO: deprecate: "Deprecated. Use util.binary.hex.decode instead." + var rval = ''; + var i = 0; + if(hex.length & 1 == 1) { + // odd number of characters, convert first character alone + i = 1; + rval += String.fromCharCode(parseInt(hex[0], 16)); + } + // convert 2 characters (1 byte) at a time + for(; i < hex.length; i += 2) { + rval += String.fromCharCode(parseInt(hex.substr(i, 2), 16)); + } + return rval; +}; + +/** + * Converts a 'binary' encoded string of bytes to hex. + * + * @param bytes the byte string to convert. + * + * @return the string of hexadecimal characters. + */ +util.bytesToHex = function(bytes) { + // TODO: deprecate: "Deprecated. Use util.binary.hex.encode instead." + return util.createBuffer(bytes).toHex(); +}; + +/** + * Converts an 32-bit integer to 4-big-endian byte string. + * + * @param i the integer. + * + * @return the byte string. + */ +util.int32ToBytes = function(i) { + return ( + String.fromCharCode(i >> 24 & 0xFF) + + String.fromCharCode(i >> 16 & 0xFF) + + String.fromCharCode(i >> 8 & 0xFF) + + String.fromCharCode(i & 0xFF)); +}; + +// base64 characters, reverse mapping +var _base64 = + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; +var _base64Idx = [ +/*43 -43 = 0*/ +/*'+', 1, 2, 3,'/' */ + 62, -1, -1, -1, 63, + +/*'0','1','2','3','4','5','6','7','8','9' */ + 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, + +/*15, 16, 17,'=', 19, 20, 21 */ + -1, -1, -1, 64, -1, -1, -1, + +/*65 - 43 = 22*/ +/*'A','B','C','D','E','F','G','H','I','J','K','L','M', */ + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, + +/*'N','O','P','Q','R','S','T','U','V','W','X','Y','Z' */ + 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, + +/*91 - 43 = 48 */ +/*48, 49, 50, 51, 52, 53 */ + -1, -1, -1, -1, -1, -1, + +/*97 - 43 = 54*/ +/*'a','b','c','d','e','f','g','h','i','j','k','l','m' */ + 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, + +/*'n','o','p','q','r','s','t','u','v','w','x','y','z' */ + 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51 +]; + +// base58 characters (Bitcoin alphabet) +var _base58 = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'; + +/** + * Base64 encodes a 'binary' encoded string of bytes. + * + * @param input the binary encoded string of bytes to base64-encode. + * @param maxline the maximum number of encoded characters per line to use, + * defaults to none. + * + * @return the base64-encoded output. + */ +util.encode64 = function(input, maxline) { + // TODO: deprecate: "Deprecated. Use util.binary.base64.encode instead." + var line = ''; + var output = ''; + var chr1, chr2, chr3; + var i = 0; + while(i < input.length) { + chr1 = input.charCodeAt(i++); + chr2 = input.charCodeAt(i++); + chr3 = input.charCodeAt(i++); + + // encode 4 character group + line += _base64.charAt(chr1 >> 2); + line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4)); + if(isNaN(chr2)) { + line += '=='; + } else { + line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6)); + line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63); + } + + if(maxline && line.length > maxline) { + output += line.substr(0, maxline) + '\r\n'; + line = line.substr(maxline); + } + } + output += line; + return output; +}; + +/** + * Base64 decodes a string into a 'binary' encoded string of bytes. + * + * @param input the base64-encoded input. + * + * @return the binary encoded string. + */ +util.decode64 = function(input) { + // TODO: deprecate: "Deprecated. Use util.binary.base64.decode instead." + + // remove all non-base64 characters + input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ''); + + var output = ''; + var enc1, enc2, enc3, enc4; + var i = 0; + + while(i < input.length) { + enc1 = _base64Idx[input.charCodeAt(i++) - 43]; + enc2 = _base64Idx[input.charCodeAt(i++) - 43]; + enc3 = _base64Idx[input.charCodeAt(i++) - 43]; + enc4 = _base64Idx[input.charCodeAt(i++) - 43]; + + output += String.fromCharCode((enc1 << 2) | (enc2 >> 4)); + if(enc3 !== 64) { + // decoded at least 2 bytes + output += String.fromCharCode(((enc2 & 15) << 4) | (enc3 >> 2)); + if(enc4 !== 64) { + // decoded 3 bytes + output += String.fromCharCode(((enc3 & 3) << 6) | enc4); + } + } + } + + return output; +}; + +/** + * Encodes the given string of characters (a standard JavaScript + * string) as a binary encoded string where the bytes represent + * a UTF-8 encoded string of characters. Non-ASCII characters will be + * encoded as multiple bytes according to UTF-8. + * + * @param str a standard string of characters to encode. + * + * @return the binary encoded string. + */ +util.encodeUtf8 = function(str) { + return unescape(encodeURIComponent(str)); +}; + +/** + * Decodes a binary encoded string that contains bytes that + * represent a UTF-8 encoded string of characters -- into a + * string of characters (a standard JavaScript string). + * + * @param str the binary encoded string to decode. + * + * @return the resulting standard string of characters. + */ +util.decodeUtf8 = function(str) { + return decodeURIComponent(escape(str)); +}; + +// binary encoding/decoding tools +// FIXME: Experimental. Do not use yet. +util.binary = { + raw: {}, + hex: {}, + base64: {}, + base58: {}, + baseN : { + encode: baseN.encode, + decode: baseN.decode + } +}; + +/** + * Encodes a Uint8Array as a binary-encoded string. This encoding uses + * a value between 0 and 255 for each character. + * + * @param bytes the Uint8Array to encode. + * + * @return the binary-encoded string. + */ +util.binary.raw.encode = function(bytes) { + return String.fromCharCode.apply(null, bytes); +}; + +/** + * Decodes a binary-encoded string to a Uint8Array. This encoding uses + * a value between 0 and 255 for each character. + * + * @param str the binary-encoded string to decode. + * @param [output] an optional Uint8Array to write the output to; if it + * is too small, an exception will be thrown. + * @param [offset] the start offset for writing to the output (default: 0). + * + * @return the Uint8Array or the number of bytes written if output was given. + */ +util.binary.raw.decode = function(str, output, offset) { + var out = output; + if(!out) { + out = new Uint8Array(str.length); + } + offset = offset || 0; + var j = offset; + for(var i = 0; i < str.length; ++i) { + out[j++] = str.charCodeAt(i); + } + return output ? (j - offset) : out; +}; + +/** + * Encodes a 'binary' string, ArrayBuffer, DataView, TypedArray, or + * ByteBuffer as a string of hexadecimal characters. + * + * @param bytes the bytes to convert. + * + * @return the string of hexadecimal characters. + */ +util.binary.hex.encode = util.bytesToHex; + +/** + * Decodes a hex-encoded string to a Uint8Array. + * + * @param hex the hexadecimal string to convert. + * @param [output] an optional Uint8Array to write the output to; if it + * is too small, an exception will be thrown. + * @param [offset] the start offset for writing to the output (default: 0). + * + * @return the Uint8Array or the number of bytes written if output was given. + */ +util.binary.hex.decode = function(hex, output, offset) { + var out = output; + if(!out) { + out = new Uint8Array(Math.ceil(hex.length / 2)); + } + offset = offset || 0; + var i = 0, j = offset; + if(hex.length & 1) { + // odd number of characters, convert first character alone + i = 1; + out[j++] = parseInt(hex[0], 16); + } + // convert 2 characters (1 byte) at a time + for(; i < hex.length; i += 2) { + out[j++] = parseInt(hex.substr(i, 2), 16); + } + return output ? (j - offset) : out; +}; + +/** + * Base64-encodes a Uint8Array. + * + * @param input the Uint8Array to encode. + * @param maxline the maximum number of encoded characters per line to use, + * defaults to none. + * + * @return the base64-encoded output string. + */ +util.binary.base64.encode = function(input, maxline) { + var line = ''; + var output = ''; + var chr1, chr2, chr3; + var i = 0; + while(i < input.byteLength) { + chr1 = input[i++]; + chr2 = input[i++]; + chr3 = input[i++]; + + // encode 4 character group + line += _base64.charAt(chr1 >> 2); + line += _base64.charAt(((chr1 & 3) << 4) | (chr2 >> 4)); + if(isNaN(chr2)) { + line += '=='; + } else { + line += _base64.charAt(((chr2 & 15) << 2) | (chr3 >> 6)); + line += isNaN(chr3) ? '=' : _base64.charAt(chr3 & 63); + } + + if(maxline && line.length > maxline) { + output += line.substr(0, maxline) + '\r\n'; + line = line.substr(maxline); + } + } + output += line; + return output; +}; + +/** + * Decodes a base64-encoded string to a Uint8Array. + * + * @param input the base64-encoded input string. + * @param [output] an optional Uint8Array to write the output to; if it + * is too small, an exception will be thrown. + * @param [offset] the start offset for writing to the output (default: 0). + * + * @return the Uint8Array or the number of bytes written if output was given. + */ +util.binary.base64.decode = function(input, output, offset) { + var out = output; + if(!out) { + out = new Uint8Array(Math.ceil(input.length / 4) * 3); + } + + // remove all non-base64 characters + input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ''); + + offset = offset || 0; + var enc1, enc2, enc3, enc4; + var i = 0, j = offset; + + while(i < input.length) { + enc1 = _base64Idx[input.charCodeAt(i++) - 43]; + enc2 = _base64Idx[input.charCodeAt(i++) - 43]; + enc3 = _base64Idx[input.charCodeAt(i++) - 43]; + enc4 = _base64Idx[input.charCodeAt(i++) - 43]; + + out[j++] = (enc1 << 2) | (enc2 >> 4); + if(enc3 !== 64) { + // decoded at least 2 bytes + out[j++] = ((enc2 & 15) << 4) | (enc3 >> 2); + if(enc4 !== 64) { + // decoded 3 bytes + out[j++] = ((enc3 & 3) << 6) | enc4; + } + } + } + + // make sure result is the exact decoded length + return output ? (j - offset) : out.subarray(0, j); +}; + +// add support for base58 encoding/decoding with Bitcoin alphabet +util.binary.base58.encode = function(input, maxline) { + return util.binary.baseN.encode(input, _base58, maxline); +}; +util.binary.base58.decode = function(input, maxline) { + return util.binary.baseN.decode(input, _base58, maxline); +}; + +// text encoding/decoding tools +// FIXME: Experimental. Do not use yet. +util.text = { + utf8: {}, + utf16: {} +}; + +/** + * Encodes the given string as UTF-8 in a Uint8Array. + * + * @param str the string to encode. + * @param [output] an optional Uint8Array to write the output to; if it + * is too small, an exception will be thrown. + * @param [offset] the start offset for writing to the output (default: 0). + * + * @return the Uint8Array or the number of bytes written if output was given. + */ +util.text.utf8.encode = function(str, output, offset) { + str = util.encodeUtf8(str); + var out = output; + if(!out) { + out = new Uint8Array(str.length); + } + offset = offset || 0; + var j = offset; + for(var i = 0; i < str.length; ++i) { + out[j++] = str.charCodeAt(i); + } + return output ? (j - offset) : out; +}; + +/** + * Decodes the UTF-8 contents from a Uint8Array. + * + * @param bytes the Uint8Array to decode. + * + * @return the resulting string. + */ +util.text.utf8.decode = function(bytes) { + return util.decodeUtf8(String.fromCharCode.apply(null, bytes)); +}; + +/** + * Encodes the given string as UTF-16 in a Uint8Array. + * + * @param str the string to encode. + * @param [output] an optional Uint8Array to write the output to; if it + * is too small, an exception will be thrown. + * @param [offset] the start offset for writing to the output (default: 0). + * + * @return the Uint8Array or the number of bytes written if output was given. + */ +util.text.utf16.encode = function(str, output, offset) { + var out = output; + if(!out) { + out = new Uint8Array(str.length * 2); + } + var view = new Uint16Array(out.buffer); + offset = offset || 0; + var j = offset; + var k = offset; + for(var i = 0; i < str.length; ++i) { + view[k++] = str.charCodeAt(i); + j += 2; + } + return output ? (j - offset) : out; +}; + +/** + * Decodes the UTF-16 contents from a Uint8Array. + * + * @param bytes the Uint8Array to decode. + * + * @return the resulting string. + */ +util.text.utf16.decode = function(bytes) { + return String.fromCharCode.apply(null, new Uint16Array(bytes.buffer)); +}; + +/** + * Deflates the given data using a flash interface. + * + * @param api the flash interface. + * @param bytes the data. + * @param raw true to return only raw deflate data, false to include zlib + * header and trailer. + * + * @return the deflated data as a string. + */ +util.deflate = function(api, bytes, raw) { + bytes = util.decode64(api.deflate(util.encode64(bytes)).rval); + + // strip zlib header and trailer if necessary + if(raw) { + // zlib header is 2 bytes (CMF,FLG) where FLG indicates that + // there is a 4-byte DICT (alder-32) block before the data if + // its 5th bit is set + var start = 2; + var flg = bytes.charCodeAt(1); + if(flg & 0x20) { + start = 6; + } + // zlib trailer is 4 bytes of adler-32 + bytes = bytes.substring(start, bytes.length - 4); + } + + return bytes; +}; + +/** + * Inflates the given data using a flash interface. + * + * @param api the flash interface. + * @param bytes the data. + * @param raw true if the incoming data has no zlib header or trailer and is + * raw DEFLATE data. + * + * @return the inflated data as a string, null on error. + */ +util.inflate = function(api, bytes, raw) { + // TODO: add zlib header and trailer if necessary/possible + var rval = api.inflate(util.encode64(bytes)).rval; + return (rval === null) ? null : util.decode64(rval); +}; + +/** + * Sets a storage object. + * + * @param api the storage interface. + * @param id the storage ID to use. + * @param obj the storage object, null to remove. + */ +var _setStorageObject = function(api, id, obj) { + if(!api) { + throw new Error('WebStorage not available.'); + } + + var rval; + if(obj === null) { + rval = api.removeItem(id); + } else { + // json-encode and base64-encode object + obj = util.encode64(JSON.stringify(obj)); + rval = api.setItem(id, obj); + } + + // handle potential flash error + if(typeof(rval) !== 'undefined' && rval.rval !== true) { + var error = new Error(rval.error.message); + error.id = rval.error.id; + error.name = rval.error.name; + throw error; + } +}; + +/** + * Gets a storage object. + * + * @param api the storage interface. + * @param id the storage ID to use. + * + * @return the storage object entry or null if none exists. + */ +var _getStorageObject = function(api, id) { + if(!api) { + throw new Error('WebStorage not available.'); + } + + // get the existing entry + var rval = api.getItem(id); + + /* Note: We check api.init because we can't do (api == localStorage) + on IE because of "Class doesn't support Automation" exception. Only + the flash api has an init method so this works too, but we need a + better solution in the future. */ + + // flash returns item wrapped in an object, handle special case + if(api.init) { + if(rval.rval === null) { + if(rval.error) { + var error = new Error(rval.error.message); + error.id = rval.error.id; + error.name = rval.error.name; + throw error; + } + // no error, but also no item + rval = null; + } else { + rval = rval.rval; + } + } + + // handle decoding + if(rval !== null) { + // base64-decode and json-decode data + rval = JSON.parse(util.decode64(rval)); + } + + return rval; +}; + +/** + * Stores an item in local storage. + * + * @param api the storage interface. + * @param id the storage ID to use. + * @param key the key for the item. + * @param data the data for the item (any javascript object/primitive). + */ +var _setItem = function(api, id, key, data) { + // get storage object + var obj = _getStorageObject(api, id); + if(obj === null) { + // create a new storage object + obj = {}; + } + // update key + obj[key] = data; + + // set storage object + _setStorageObject(api, id, obj); +}; + +/** + * Gets an item from local storage. + * + * @param api the storage interface. + * @param id the storage ID to use. + * @param key the key for the item. + * + * @return the item. + */ +var _getItem = function(api, id, key) { + // get storage object + var rval = _getStorageObject(api, id); + if(rval !== null) { + // return data at key + rval = (key in rval) ? rval[key] : null; + } + + return rval; +}; + +/** + * Removes an item from local storage. + * + * @param api the storage interface. + * @param id the storage ID to use. + * @param key the key for the item. + */ +var _removeItem = function(api, id, key) { + // get storage object + var obj = _getStorageObject(api, id); + if(obj !== null && key in obj) { + // remove key + delete obj[key]; + + // see if entry has no keys remaining + var empty = true; + for(var prop in obj) { + empty = false; + break; + } + if(empty) { + // remove entry entirely if no keys are left + obj = null; + } + + // set storage object + _setStorageObject(api, id, obj); + } +}; + +/** + * Clears the local disk storage identified by the given ID. + * + * @param api the storage interface. + * @param id the storage ID to use. + */ +var _clearItems = function(api, id) { + _setStorageObject(api, id, null); +}; + +/** + * Calls a storage function. + * + * @param func the function to call. + * @param args the arguments for the function. + * @param location the location argument. + * + * @return the return value from the function. + */ +var _callStorageFunction = function(func, args, location) { + var rval = null; + + // default storage types + if(typeof(location) === 'undefined') { + location = ['web', 'flash']; + } + + // apply storage types in order of preference + var type; + var done = false; + var exception = null; + for(var idx in location) { + type = location[idx]; + try { + if(type === 'flash' || type === 'both') { + if(args[0] === null) { + throw new Error('Flash local storage not available.'); + } + rval = func.apply(this, args); + done = (type === 'flash'); + } + if(type === 'web' || type === 'both') { + args[0] = localStorage; + rval = func.apply(this, args); + done = true; + } + } catch(ex) { + exception = ex; + } + if(done) { + break; + } + } + + if(!done) { + throw exception; + } + + return rval; +}; + +/** + * Stores an item on local disk. + * + * The available types of local storage include 'flash', 'web', and 'both'. + * + * The type 'flash' refers to flash local storage (SharedObject). In order + * to use flash local storage, the 'api' parameter must be valid. The type + * 'web' refers to WebStorage, if supported by the browser. The type 'both' + * refers to storing using both 'flash' and 'web', not just one or the + * other. + * + * The location array should list the storage types to use in order of + * preference: + * + * ['flash']: flash only storage + * ['web']: web only storage + * ['both']: try to store in both + * ['flash','web']: store in flash first, but if not available, 'web' + * ['web','flash']: store in web first, but if not available, 'flash' + * + * The location array defaults to: ['web', 'flash'] + * + * @param api the flash interface, null to use only WebStorage. + * @param id the storage ID to use. + * @param key the key for the item. + * @param data the data for the item (any javascript object/primitive). + * @param location an array with the preferred types of storage to use. + */ +util.setItem = function(api, id, key, data, location) { + _callStorageFunction(_setItem, arguments, location); +}; + +/** + * Gets an item on local disk. + * + * Set setItem() for details on storage types. + * + * @param api the flash interface, null to use only WebStorage. + * @param id the storage ID to use. + * @param key the key for the item. + * @param location an array with the preferred types of storage to use. + * + * @return the item. + */ +util.getItem = function(api, id, key, location) { + return _callStorageFunction(_getItem, arguments, location); +}; + +/** + * Removes an item on local disk. + * + * Set setItem() for details on storage types. + * + * @param api the flash interface. + * @param id the storage ID to use. + * @param key the key for the item. + * @param location an array with the preferred types of storage to use. + */ +util.removeItem = function(api, id, key, location) { + _callStorageFunction(_removeItem, arguments, location); +}; + +/** + * Clears the local disk storage identified by the given ID. + * + * Set setItem() for details on storage types. + * + * @param api the flash interface if flash is available. + * @param id the storage ID to use. + * @param location an array with the preferred types of storage to use. + */ +util.clearItems = function(api, id, location) { + _callStorageFunction(_clearItems, arguments, location); +}; + +/** + * Parses the scheme, host, and port from an http(s) url. + * + * @param str the url string. + * + * @return the parsed url object or null if the url is invalid. + */ +util.parseUrl = function(str) { + // FIXME: this regex looks a bit broken + var regex = /^(https?):\/\/([^:&^\/]*):?(\d*)(.*)$/g; + regex.lastIndex = 0; + var m = regex.exec(str); + var url = (m === null) ? null : { + full: str, + scheme: m[1], + host: m[2], + port: m[3], + path: m[4] + }; + if(url) { + url.fullHost = url.host; + if(url.port) { + if(url.port !== 80 && url.scheme === 'http') { + url.fullHost += ':' + url.port; + } else if(url.port !== 443 && url.scheme === 'https') { + url.fullHost += ':' + url.port; + } + } else if(url.scheme === 'http') { + url.port = 80; + } else if(url.scheme === 'https') { + url.port = 443; + } + url.full = url.scheme + '://' + url.fullHost; + } + return url; +}; + +/* Storage for query variables */ +var _queryVariables = null; + +/** + * Returns the window location query variables. Query is parsed on the first + * call and the same object is returned on subsequent calls. The mapping + * is from keys to an array of values. Parameters without values will have + * an object key set but no value added to the value array. Values are + * unescaped. + * + * ...?k1=v1&k2=v2: + * { + * "k1": ["v1"], + * "k2": ["v2"] + * } + * + * ...?k1=v1&k1=v2: + * { + * "k1": ["v1", "v2"] + * } + * + * ...?k1=v1&k2: + * { + * "k1": ["v1"], + * "k2": [] + * } + * + * ...?k1=v1&k1: + * { + * "k1": ["v1"] + * } + * + * ...?k1&k1: + * { + * "k1": [] + * } + * + * @param query the query string to parse (optional, default to cached + * results from parsing window location search query). + * + * @return object mapping keys to variables. + */ +util.getQueryVariables = function(query) { + var parse = function(q) { + var rval = {}; + var kvpairs = q.split('&'); + for(var i = 0; i < kvpairs.length; i++) { + var pos = kvpairs[i].indexOf('='); + var key; + var val; + if(pos > 0) { + key = kvpairs[i].substring(0, pos); + val = kvpairs[i].substring(pos + 1); + } else { + key = kvpairs[i]; + val = null; + } + if(!(key in rval)) { + rval[key] = []; + } + // disallow overriding object prototype keys + if(!(key in Object.prototype) && val !== null) { + rval[key].push(unescape(val)); + } + } + return rval; + }; + + var rval; + if(typeof(query) === 'undefined') { + // set cached variables if needed + if(_queryVariables === null) { + if(typeof(window) !== 'undefined' && window.location && window.location.search) { + // parse window search query + _queryVariables = parse(window.location.search.substring(1)); + } else { + // no query variables available + _queryVariables = {}; + } + } + rval = _queryVariables; + } else { + // parse given query + rval = parse(query); + } + return rval; +}; + +/** + * Parses a fragment into a path and query. This method will take a URI + * fragment and break it up as if it were the main URI. For example: + * /bar/baz?a=1&b=2 + * results in: + * { + * path: ["bar", "baz"], + * query: {"k1": ["v1"], "k2": ["v2"]} + * } + * + * @return object with a path array and query object. + */ +util.parseFragment = function(fragment) { + // default to whole fragment + var fp = fragment; + var fq = ''; + // split into path and query if possible at the first '?' + var pos = fragment.indexOf('?'); + if(pos > 0) { + fp = fragment.substring(0, pos); + fq = fragment.substring(pos + 1); + } + // split path based on '/' and ignore first element if empty + var path = fp.split('/'); + if(path.length > 0 && path[0] === '') { + path.shift(); + } + // convert query into object + var query = (fq === '') ? {} : util.getQueryVariables(fq); + + return { + pathString: fp, + queryString: fq, + path: path, + query: query + }; +}; + +/** + * Makes a request out of a URI-like request string. This is intended to + * be used where a fragment id (after a URI '#') is parsed as a URI with + * path and query parts. The string should have a path beginning and + * delimited by '/' and optional query parameters following a '?'. The + * query should be a standard URL set of key value pairs delimited by + * '&'. For backwards compatibility the initial '/' on the path is not + * required. The request object has the following API, (fully described + * in the method code): + * { + * path: . + * query: , + * getPath(i): get part or all of the split path array, + * getQuery(k, i): get part or all of a query key array, + * getQueryLast(k, _default): get last element of a query key array. + * } + * + * @return object with request parameters. + */ +util.makeRequest = function(reqString) { + var frag = util.parseFragment(reqString); + var req = { + // full path string + path: frag.pathString, + // full query string + query: frag.queryString, + /** + * Get path or element in path. + * + * @param i optional path index. + * + * @return path or part of path if i provided. + */ + getPath: function(i) { + return (typeof(i) === 'undefined') ? frag.path : frag.path[i]; + }, + /** + * Get query, values for a key, or value for a key index. + * + * @param k optional query key. + * @param i optional query key index. + * + * @return query, values for a key, or value for a key index. + */ + getQuery: function(k, i) { + var rval; + if(typeof(k) === 'undefined') { + rval = frag.query; + } else { + rval = frag.query[k]; + if(rval && typeof(i) !== 'undefined') { + rval = rval[i]; + } + } + return rval; + }, + getQueryLast: function(k, _default) { + var rval; + var vals = req.getQuery(k); + if(vals) { + rval = vals[vals.length - 1]; + } else { + rval = _default; + } + return rval; + } + }; + return req; +}; + +/** + * Makes a URI out of a path, an object with query parameters, and a + * fragment. Uses jQuery.param() internally for query string creation. + * If the path is an array, it will be joined with '/'. + * + * @param path string path or array of strings. + * @param query object with query parameters. (optional) + * @param fragment fragment string. (optional) + * + * @return string object with request parameters. + */ +util.makeLink = function(path, query, fragment) { + // join path parts if needed + path = jQuery.isArray(path) ? path.join('/') : path; + + var qstr = jQuery.param(query || {}); + fragment = fragment || ''; + return path + + ((qstr.length > 0) ? ('?' + qstr) : '') + + ((fragment.length > 0) ? ('#' + fragment) : ''); +}; + +/** + * Follows a path of keys deep into an object hierarchy and set a value. + * If a key does not exist or it's value is not an object, create an + * object in it's place. This can be destructive to a object tree if + * leaf nodes are given as non-final path keys. + * Used to avoid exceptions from missing parts of the path. + * + * @param object the starting object. + * @param keys an array of string keys. + * @param value the value to set. + */ +util.setPath = function(object, keys, value) { + // need to start at an object + if(typeof(object) === 'object' && object !== null) { + var i = 0; + var len = keys.length; + while(i < len) { + var next = keys[i++]; + if(i == len) { + // last + object[next] = value; + } else { + // more + var hasNext = (next in object); + if(!hasNext || + (hasNext && typeof(object[next]) !== 'object') || + (hasNext && object[next] === null)) { + object[next] = {}; + } + object = object[next]; + } + } + } +}; + +/** + * Follows a path of keys deep into an object hierarchy and return a value. + * If a key does not exist, create an object in it's place. + * Used to avoid exceptions from missing parts of the path. + * + * @param object the starting object. + * @param keys an array of string keys. + * @param _default value to return if path not found. + * + * @return the value at the path if found, else default if given, else + * undefined. + */ +util.getPath = function(object, keys, _default) { + var i = 0; + var len = keys.length; + var hasNext = true; + while(hasNext && i < len && + typeof(object) === 'object' && object !== null) { + var next = keys[i++]; + hasNext = next in object; + if(hasNext) { + object = object[next]; + } + } + return (hasNext ? object : _default); +}; + +/** + * Follow a path of keys deep into an object hierarchy and delete the + * last one. If a key does not exist, do nothing. + * Used to avoid exceptions from missing parts of the path. + * + * @param object the starting object. + * @param keys an array of string keys. + */ +util.deletePath = function(object, keys) { + // need to start at an object + if(typeof(object) === 'object' && object !== null) { + var i = 0; + var len = keys.length; + while(i < len) { + var next = keys[i++]; + if(i == len) { + // last + delete object[next]; + } else { + // more + if(!(next in object) || + (typeof(object[next]) !== 'object') || + (object[next] === null)) { + break; + } + object = object[next]; + } + } + } +}; + +/** + * Check if an object is empty. + * + * Taken from: + * http://stackoverflow.com/questions/679915/how-do-i-test-for-an-empty-javascript-object-from-json/679937#679937 + * + * @param object the object to check. + */ +util.isEmpty = function(obj) { + for(var prop in obj) { + if(obj.hasOwnProperty(prop)) { + return false; + } + } + return true; +}; + +/** + * Format with simple printf-style interpolation. + * + * %%: literal '%' + * %s,%o: convert next argument into a string. + * + * @param format the string to format. + * @param ... arguments to interpolate into the format string. + */ +util.format = function(format) { + var re = /%./g; + // current match + var match; + // current part + var part; + // current arg index + var argi = 0; + // collected parts to recombine later + var parts = []; + // last index found + var last = 0; + // loop while matches remain + while((match = re.exec(format))) { + part = format.substring(last, re.lastIndex - 2); + // don't add empty strings (ie, parts between %s%s) + if(part.length > 0) { + parts.push(part); + } + last = re.lastIndex; + // switch on % code + var code = match[0][1]; + switch(code) { + case 's': + case 'o': + // check if enough arguments were given + if(argi < arguments.length) { + parts.push(arguments[argi++ + 1]); + } else { + parts.push(''); + } + break; + // FIXME: do proper formating for numbers, etc + //case 'f': + //case 'd': + case '%': + parts.push('%'); + break; + default: + parts.push('<%' + code + '?>'); + } + } + // add trailing part of format string + parts.push(format.substring(last)); + return parts.join(''); +}; + +/** + * Formats a number. + * + * http://snipplr.com/view/5945/javascript-numberformat--ported-from-php/ + */ +util.formatNumber = function(number, decimals, dec_point, thousands_sep) { + // http://kevin.vanzonneveld.net + // + original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) + // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) + // + bugfix by: Michael White (http://crestidg.com) + // + bugfix by: Benjamin Lupton + // + bugfix by: Allan Jensen (http://www.winternet.no) + // + revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com) + // * example 1: number_format(1234.5678, 2, '.', ''); + // * returns 1: 1234.57 + + var n = number, c = isNaN(decimals = Math.abs(decimals)) ? 2 : decimals; + var d = dec_point === undefined ? ',' : dec_point; + var t = thousands_sep === undefined ? + '.' : thousands_sep, s = n < 0 ? '-' : ''; + var i = parseInt((n = Math.abs(+n || 0).toFixed(c)), 10) + ''; + var j = (i.length > 3) ? i.length % 3 : 0; + return s + (j ? i.substr(0, j) + t : '') + + i.substr(j).replace(/(\d{3})(?=\d)/g, '$1' + t) + + (c ? d + Math.abs(n - i).toFixed(c).slice(2) : ''); +}; + +/** + * Formats a byte size. + * + * http://snipplr.com/view/5949/format-humanize-file-byte-size-presentation-in-javascript/ + */ +util.formatSize = function(size) { + if(size >= 1073741824) { + size = util.formatNumber(size / 1073741824, 2, '.', '') + ' GiB'; + } else if(size >= 1048576) { + size = util.formatNumber(size / 1048576, 2, '.', '') + ' MiB'; + } else if(size >= 1024) { + size = util.formatNumber(size / 1024, 0) + ' KiB'; + } else { + size = util.formatNumber(size, 0) + ' bytes'; + } + return size; +}; + +/** + * Converts an IPv4 or IPv6 string representation into bytes (in network order). + * + * @param ip the IPv4 or IPv6 address to convert. + * + * @return the 4-byte IPv6 or 16-byte IPv6 address or null if the address can't + * be parsed. + */ +util.bytesFromIP = function(ip) { + if(ip.indexOf('.') !== -1) { + return util.bytesFromIPv4(ip); + } + if(ip.indexOf(':') !== -1) { + return util.bytesFromIPv6(ip); + } + return null; +}; + +/** + * Converts an IPv4 string representation into bytes (in network order). + * + * @param ip the IPv4 address to convert. + * + * @return the 4-byte address or null if the address can't be parsed. + */ +util.bytesFromIPv4 = function(ip) { + ip = ip.split('.'); + if(ip.length !== 4) { + return null; + } + var b = util.createBuffer(); + for(var i = 0; i < ip.length; ++i) { + var num = parseInt(ip[i], 10); + if(isNaN(num)) { + return null; + } + b.putByte(num); + } + return b.getBytes(); +}; + +/** + * Converts an IPv6 string representation into bytes (in network order). + * + * @param ip the IPv6 address to convert. + * + * @return the 16-byte address or null if the address can't be parsed. + */ +util.bytesFromIPv6 = function(ip) { + var blanks = 0; + ip = ip.split(':').filter(function(e) { + if(e.length === 0) ++blanks; + return true; + }); + var zeros = (8 - ip.length + blanks) * 2; + var b = util.createBuffer(); + for(var i = 0; i < 8; ++i) { + if(!ip[i] || ip[i].length === 0) { + b.fillWithByte(0, zeros); + zeros = 0; + continue; + } + var bytes = util.hexToBytes(ip[i]); + if(bytes.length < 2) { + b.putByte(0); + } + b.putBytes(bytes); + } + return b.getBytes(); +}; + +/** + * Converts 4-bytes into an IPv4 string representation or 16-bytes into + * an IPv6 string representation. The bytes must be in network order. + * + * @param bytes the bytes to convert. + * + * @return the IPv4 or IPv6 string representation if 4 or 16 bytes, + * respectively, are given, otherwise null. + */ +util.bytesToIP = function(bytes) { + if(bytes.length === 4) { + return util.bytesToIPv4(bytes); + } + if(bytes.length === 16) { + return util.bytesToIPv6(bytes); + } + return null; +}; + +/** + * Converts 4-bytes into an IPv4 string representation. The bytes must be + * in network order. + * + * @param bytes the bytes to convert. + * + * @return the IPv4 string representation or null for an invalid # of bytes. + */ +util.bytesToIPv4 = function(bytes) { + if(bytes.length !== 4) { + return null; + } + var ip = []; + for(var i = 0; i < bytes.length; ++i) { + ip.push(bytes.charCodeAt(i)); + } + return ip.join('.'); +}; + +/** + * Converts 16-bytes into an IPv16 string representation. The bytes must be + * in network order. + * + * @param bytes the bytes to convert. + * + * @return the IPv16 string representation or null for an invalid # of bytes. + */ +util.bytesToIPv6 = function(bytes) { + if(bytes.length !== 16) { + return null; + } + var ip = []; + var zeroGroups = []; + var zeroMaxGroup = 0; + for(var i = 0; i < bytes.length; i += 2) { + var hex = util.bytesToHex(bytes[i] + bytes[i + 1]); + // canonicalize zero representation + while(hex[0] === '0' && hex !== '0') { + hex = hex.substr(1); + } + if(hex === '0') { + var last = zeroGroups[zeroGroups.length - 1]; + var idx = ip.length; + if(!last || idx !== last.end + 1) { + zeroGroups.push({start: idx, end: idx}); + } else { + last.end = idx; + if((last.end - last.start) > + (zeroGroups[zeroMaxGroup].end - zeroGroups[zeroMaxGroup].start)) { + zeroMaxGroup = zeroGroups.length - 1; + } + } + } + ip.push(hex); + } + if(zeroGroups.length > 0) { + var group = zeroGroups[zeroMaxGroup]; + // only shorten group of length > 0 + if(group.end - group.start > 0) { + ip.splice(group.start, group.end - group.start + 1, ''); + if(group.start === 0) { + ip.unshift(''); + } + if(group.end === 7) { + ip.push(''); + } + } + } + return ip.join(':'); +}; + +/** + * Estimates the number of processes that can be run concurrently. If + * creating Web Workers, keep in mind that the main JavaScript process needs + * its own core. + * + * @param options the options to use: + * update true to force an update (not use the cached value). + * @param callback(err, max) called once the operation completes. + */ +util.estimateCores = function(options, callback) { + if(typeof options === 'function') { + callback = options; + options = {}; + } + options = options || {}; + if('cores' in util && !options.update) { + return callback(null, util.cores); + } + if(typeof navigator !== 'undefined' && + 'hardwareConcurrency' in navigator && + navigator.hardwareConcurrency > 0) { + util.cores = navigator.hardwareConcurrency; + return callback(null, util.cores); + } + if(typeof Worker === 'undefined') { + // workers not available + util.cores = 1; + return callback(null, util.cores); + } + if(typeof Blob === 'undefined') { + // can't estimate, default to 2 + util.cores = 2; + return callback(null, util.cores); + } + + // create worker concurrency estimation code as blob + var blobUrl = URL.createObjectURL(new Blob(['(', + function() { + self.addEventListener('message', function(e) { + // run worker for 4 ms + var st = Date.now(); + var et = st + 4; + while(Date.now() < et); + self.postMessage({st: st, et: et}); + }); + }.toString(), + ')()'], {type: 'application/javascript'})); + + // take 5 samples using 16 workers + sample([], 5, 16); + + function sample(max, samples, numWorkers) { + if(samples === 0) { + // get overlap average + var avg = Math.floor(max.reduce(function(avg, x) { + return avg + x; + }, 0) / max.length); + util.cores = Math.max(1, avg); + URL.revokeObjectURL(blobUrl); + return callback(null, util.cores); + } + map(numWorkers, function(err, results) { + max.push(reduce(numWorkers, results)); + sample(max, samples - 1, numWorkers); + }); + } + + function map(numWorkers, callback) { + var workers = []; + var results = []; + for(var i = 0; i < numWorkers; ++i) { + var worker = new Worker(blobUrl); + worker.addEventListener('message', function(e) { + results.push(e.data); + if(results.length === numWorkers) { + for(var i = 0; i < numWorkers; ++i) { + workers[i].terminate(); + } + callback(null, results); + } + }); + workers.push(worker); + } + for(var i = 0; i < numWorkers; ++i) { + workers[i].postMessage(i); + } + } + + function reduce(numWorkers, results) { + // find overlapping time windows + var overlaps = []; + for(var n = 0; n < numWorkers; ++n) { + var r1 = results[n]; + var overlap = overlaps[n] = []; + for(var i = 0; i < numWorkers; ++i) { + if(n === i) { + continue; + } + var r2 = results[i]; + if((r1.st > r2.st && r1.st < r2.et) || + (r2.st > r1.st && r2.st < r1.et)) { + overlap.push(i); + } + } + } + // get maximum overlaps ... don't include overlapping worker itself + // as the main JS process was also being scheduled during the work and + // would have to be subtracted from the estimate anyway + return overlaps.reduce(function(max, overlap) { + return Math.max(max, overlap.length); + }, 0); + } +}; diff --git a/node_modules/node-forge/lib/x509.js b/node_modules/node-forge/lib/x509.js new file mode 100644 index 0000000..95dbc29 --- /dev/null +++ b/node_modules/node-forge/lib/x509.js @@ -0,0 +1,3333 @@ +/** + * Javascript implementation of X.509 and related components (such as + * Certification Signing Requests) of a Public Key Infrastructure. + * + * @author Dave Longley + * + * Copyright (c) 2010-2014 Digital Bazaar, Inc. + * + * The ASN.1 representation of an X.509v3 certificate is as follows + * (see RFC 2459): + * + * Certificate ::= SEQUENCE { + * tbsCertificate TBSCertificate, + * signatureAlgorithm AlgorithmIdentifier, + * signatureValue BIT STRING + * } + * + * TBSCertificate ::= SEQUENCE { + * version [0] EXPLICIT Version DEFAULT v1, + * serialNumber CertificateSerialNumber, + * signature AlgorithmIdentifier, + * issuer Name, + * validity Validity, + * subject Name, + * subjectPublicKeyInfo SubjectPublicKeyInfo, + * issuerUniqueID [1] IMPLICIT UniqueIdentifier OPTIONAL, + * -- If present, version shall be v2 or v3 + * subjectUniqueID [2] IMPLICIT UniqueIdentifier OPTIONAL, + * -- If present, version shall be v2 or v3 + * extensions [3] EXPLICIT Extensions OPTIONAL + * -- If present, version shall be v3 + * } + * + * Version ::= INTEGER { v1(0), v2(1), v3(2) } + * + * CertificateSerialNumber ::= INTEGER + * + * Name ::= CHOICE { + * // only one possible choice for now + * RDNSequence + * } + * + * RDNSequence ::= SEQUENCE OF RelativeDistinguishedName + * + * RelativeDistinguishedName ::= SET OF AttributeTypeAndValue + * + * AttributeTypeAndValue ::= SEQUENCE { + * type AttributeType, + * value AttributeValue + * } + * AttributeType ::= OBJECT IDENTIFIER + * AttributeValue ::= ANY DEFINED BY AttributeType + * + * Validity ::= SEQUENCE { + * notBefore Time, + * notAfter Time + * } + * + * Time ::= CHOICE { + * utcTime UTCTime, + * generalTime GeneralizedTime + * } + * + * UniqueIdentifier ::= BIT STRING + * + * SubjectPublicKeyInfo ::= SEQUENCE { + * algorithm AlgorithmIdentifier, + * subjectPublicKey BIT STRING + * } + * + * Extensions ::= SEQUENCE SIZE (1..MAX) OF Extension + * + * Extension ::= SEQUENCE { + * extnID OBJECT IDENTIFIER, + * critical BOOLEAN DEFAULT FALSE, + * extnValue OCTET STRING + * } + * + * The only key algorithm currently supported for PKI is RSA. + * + * RSASSA-PSS signatures are described in RFC 3447 and RFC 4055. + * + * PKCS#10 v1.7 describes certificate signing requests: + * + * CertificationRequestInfo: + * + * CertificationRequestInfo ::= SEQUENCE { + * version INTEGER { v1(0) } (v1,...), + * subject Name, + * subjectPKInfo SubjectPublicKeyInfo{{ PKInfoAlgorithms }}, + * attributes [0] Attributes{{ CRIAttributes }} + * } + * + * Attributes { ATTRIBUTE:IOSet } ::= SET OF Attribute{{ IOSet }} + * + * CRIAttributes ATTRIBUTE ::= { + * ... -- add any locally defined attributes here -- } + * + * Attribute { ATTRIBUTE:IOSet } ::= SEQUENCE { + * type ATTRIBUTE.&id({IOSet}), + * values SET SIZE(1..MAX) OF ATTRIBUTE.&Type({IOSet}{@type}) + * } + * + * CertificationRequest ::= SEQUENCE { + * certificationRequestInfo CertificationRequestInfo, + * signatureAlgorithm AlgorithmIdentifier{{ SignatureAlgorithms }}, + * signature BIT STRING + * } + */ +var forge = require('./forge'); +require('./aes'); +require('./asn1'); +require('./des'); +require('./md'); +require('./mgf'); +require('./oids'); +require('./pem'); +require('./pss'); +require('./rsa'); +require('./util'); + +// shortcut for asn.1 API +var asn1 = forge.asn1; + +/* Public Key Infrastructure (PKI) implementation. */ +var pki = module.exports = forge.pki = forge.pki || {}; +var oids = pki.oids; + +// short name OID mappings +var _shortNames = {}; +_shortNames['CN'] = oids['commonName']; +_shortNames['commonName'] = 'CN'; +_shortNames['C'] = oids['countryName']; +_shortNames['countryName'] = 'C'; +_shortNames['L'] = oids['localityName']; +_shortNames['localityName'] = 'L'; +_shortNames['ST'] = oids['stateOrProvinceName']; +_shortNames['stateOrProvinceName'] = 'ST'; +_shortNames['O'] = oids['organizationName']; +_shortNames['organizationName'] = 'O'; +_shortNames['OU'] = oids['organizationalUnitName']; +_shortNames['organizationalUnitName'] = 'OU'; +_shortNames['E'] = oids['emailAddress']; +_shortNames['emailAddress'] = 'E'; + +// validator for an SubjectPublicKeyInfo structure +// Note: Currently only works with an RSA public key +var publicKeyValidator = forge.pki.rsa.publicKeyValidator; + +// validator for an X.509v3 certificate +var x509CertificateValidator = { + name: 'Certificate', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'Certificate.TBSCertificate', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'tbsCertificate', + value: [{ + name: 'Certificate.TBSCertificate.version', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + optional: true, + value: [{ + name: 'Certificate.TBSCertificate.version.integer', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'certVersion' + }] + }, { + name: 'Certificate.TBSCertificate.serialNumber', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'certSerialNumber' + }, { + name: 'Certificate.TBSCertificate.signature', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'Certificate.TBSCertificate.signature.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'certinfoSignatureOid' + }, { + name: 'Certificate.TBSCertificate.signature.parameters', + tagClass: asn1.Class.UNIVERSAL, + optional: true, + captureAsn1: 'certinfoSignatureParams' + }] + }, { + name: 'Certificate.TBSCertificate.issuer', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'certIssuer' + }, { + name: 'Certificate.TBSCertificate.validity', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + // Note: UTC and generalized times may both appear so the capture + // names are based on their detected order, the names used below + // are only for the common case, which validity time really means + // "notBefore" and which means "notAfter" will be determined by order + value: [{ + // notBefore (Time) (UTC time case) + name: 'Certificate.TBSCertificate.validity.notBefore (utc)', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.UTCTIME, + constructed: false, + optional: true, + capture: 'certValidity1UTCTime' + }, { + // notBefore (Time) (generalized time case) + name: 'Certificate.TBSCertificate.validity.notBefore (generalized)', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.GENERALIZEDTIME, + constructed: false, + optional: true, + capture: 'certValidity2GeneralizedTime' + }, { + // notAfter (Time) (only UTC time is supported) + name: 'Certificate.TBSCertificate.validity.notAfter (utc)', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.UTCTIME, + constructed: false, + optional: true, + capture: 'certValidity3UTCTime' + }, { + // notAfter (Time) (only UTC time is supported) + name: 'Certificate.TBSCertificate.validity.notAfter (generalized)', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.GENERALIZEDTIME, + constructed: false, + optional: true, + capture: 'certValidity4GeneralizedTime' + }] + }, { + // Name (subject) (RDNSequence) + name: 'Certificate.TBSCertificate.subject', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'certSubject' + }, + // SubjectPublicKeyInfo + publicKeyValidator, + { + // issuerUniqueID (optional) + name: 'Certificate.TBSCertificate.issuerUniqueID', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 1, + constructed: true, + optional: true, + value: [{ + name: 'Certificate.TBSCertificate.issuerUniqueID.id', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + // TODO: support arbitrary bit length ids + captureBitStringValue: 'certIssuerUniqueId' + }] + }, { + // subjectUniqueID (optional) + name: 'Certificate.TBSCertificate.subjectUniqueID', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 2, + constructed: true, + optional: true, + value: [{ + name: 'Certificate.TBSCertificate.subjectUniqueID.id', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + // TODO: support arbitrary bit length ids + captureBitStringValue: 'certSubjectUniqueId' + }] + }, { + // Extensions (optional) + name: 'Certificate.TBSCertificate.extensions', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 3, + constructed: true, + captureAsn1: 'certExtensions', + optional: true + }] + }, { + // AlgorithmIdentifier (signature algorithm) + name: 'Certificate.signatureAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + // algorithm + name: 'Certificate.signatureAlgorithm.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'certSignatureOid' + }, { + name: 'Certificate.TBSCertificate.signature.parameters', + tagClass: asn1.Class.UNIVERSAL, + optional: true, + captureAsn1: 'certSignatureParams' + }] + }, { + // SignatureValue + name: 'Certificate.signatureValue', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + captureBitStringValue: 'certSignature' + }] +}; + +var rsassaPssParameterValidator = { + name: 'rsapss', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'rsapss.hashAlgorithm', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + value: [{ + name: 'rsapss.hashAlgorithm.AlgorithmIdentifier', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Class.SEQUENCE, + constructed: true, + optional: true, + value: [{ + name: 'rsapss.hashAlgorithm.AlgorithmIdentifier.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'hashOid' + /* parameter block omitted, for SHA1 NULL anyhow. */ + }] + }] + }, { + name: 'rsapss.maskGenAlgorithm', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 1, + constructed: true, + value: [{ + name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Class.SEQUENCE, + constructed: true, + optional: true, + value: [{ + name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'maskGenOid' + }, { + name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'rsapss.maskGenAlgorithm.AlgorithmIdentifier.params.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'maskGenHashOid' + /* parameter block omitted, for SHA1 NULL anyhow. */ + }] + }] + }] + }, { + name: 'rsapss.saltLength', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 2, + optional: true, + value: [{ + name: 'rsapss.saltLength.saltLength', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Class.INTEGER, + constructed: false, + capture: 'saltLength' + }] + }, { + name: 'rsapss.trailerField', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 3, + optional: true, + value: [{ + name: 'rsapss.trailer.trailer', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Class.INTEGER, + constructed: false, + capture: 'trailer' + }] + }] +}; + +// validator for a CertificationRequestInfo structure +var certificationRequestInfoValidator = { + name: 'CertificationRequestInfo', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'certificationRequestInfo', + value: [{ + name: 'CertificationRequestInfo.integer', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.INTEGER, + constructed: false, + capture: 'certificationRequestInfoVersion' + }, { + // Name (subject) (RDNSequence) + name: 'CertificationRequestInfo.subject', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'certificationRequestInfoSubject' + }, + // SubjectPublicKeyInfo + publicKeyValidator, + { + name: 'CertificationRequestInfo.attributes', + tagClass: asn1.Class.CONTEXT_SPECIFIC, + type: 0, + constructed: true, + optional: true, + capture: 'certificationRequestInfoAttributes', + value: [{ + name: 'CertificationRequestInfo.attributes', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + name: 'CertificationRequestInfo.attributes.type', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false + }, { + name: 'CertificationRequestInfo.attributes.value', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SET, + constructed: true + }] + }] + }] +}; + +// validator for a CertificationRequest structure +var certificationRequestValidator = { + name: 'CertificationRequest', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + captureAsn1: 'csr', + value: [ + certificationRequestInfoValidator, { + // AlgorithmIdentifier (signature algorithm) + name: 'CertificationRequest.signatureAlgorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.SEQUENCE, + constructed: true, + value: [{ + // algorithm + name: 'CertificationRequest.signatureAlgorithm.algorithm', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.OID, + constructed: false, + capture: 'csrSignatureOid' + }, { + name: 'CertificationRequest.signatureAlgorithm.parameters', + tagClass: asn1.Class.UNIVERSAL, + optional: true, + captureAsn1: 'csrSignatureParams' + }] + }, { + // signature + name: 'CertificationRequest.signature', + tagClass: asn1.Class.UNIVERSAL, + type: asn1.Type.BITSTRING, + constructed: false, + captureBitStringValue: 'csrSignature' + } + ] +}; + +/** + * Converts an RDNSequence of ASN.1 DER-encoded RelativeDistinguishedName + * sets into an array with objects that have type and value properties. + * + * @param rdn the RDNSequence to convert. + * @param md a message digest to append type and value to if provided. + */ +pki.RDNAttributesAsArray = function(rdn, md) { + var rval = []; + + // each value in 'rdn' in is a SET of RelativeDistinguishedName + var set, attr, obj; + for(var si = 0; si < rdn.value.length; ++si) { + // get the RelativeDistinguishedName set + set = rdn.value[si]; + + // each value in the SET is an AttributeTypeAndValue sequence + // containing first a type (an OID) and second a value (defined by + // the OID) + for(var i = 0; i < set.value.length; ++i) { + obj = {}; + attr = set.value[i]; + obj.type = asn1.derToOid(attr.value[0].value); + obj.value = attr.value[1].value; + obj.valueTagClass = attr.value[1].type; + // if the OID is known, get its name and short name + if(obj.type in oids) { + obj.name = oids[obj.type]; + if(obj.name in _shortNames) { + obj.shortName = _shortNames[obj.name]; + } + } + if(md) { + md.update(obj.type); + md.update(obj.value); + } + rval.push(obj); + } + } + + return rval; +}; + +/** + * Converts ASN.1 CRIAttributes into an array with objects that have type and + * value properties. + * + * @param attributes the CRIAttributes to convert. + */ +pki.CRIAttributesAsArray = function(attributes) { + var rval = []; + + // each value in 'attributes' in is a SEQUENCE with an OID and a SET + for(var si = 0; si < attributes.length; ++si) { + // get the attribute sequence + var seq = attributes[si]; + + // each value in the SEQUENCE containing first a type (an OID) and + // second a set of values (defined by the OID) + var type = asn1.derToOid(seq.value[0].value); + var values = seq.value[1].value; + for(var vi = 0; vi < values.length; ++vi) { + var obj = {}; + obj.type = type; + obj.value = values[vi].value; + obj.valueTagClass = values[vi].type; + // if the OID is known, get its name and short name + if(obj.type in oids) { + obj.name = oids[obj.type]; + if(obj.name in _shortNames) { + obj.shortName = _shortNames[obj.name]; + } + } + // parse extensions + if(obj.type === oids.extensionRequest) { + obj.extensions = []; + for(var ei = 0; ei < obj.value.length; ++ei) { + obj.extensions.push(pki.certificateExtensionFromAsn1(obj.value[ei])); + } + } + rval.push(obj); + } + } + + return rval; +}; + +/** + * Gets an issuer or subject attribute from its name, type, or short name. + * + * @param obj the issuer or subject object. + * @param options a short name string or an object with: + * shortName the short name for the attribute. + * name the name for the attribute. + * type the type for the attribute. + * + * @return the attribute. + */ +function _getAttribute(obj, options) { + if(typeof options === 'string') { + options = {shortName: options}; + } + + var rval = null; + var attr; + for(var i = 0; rval === null && i < obj.attributes.length; ++i) { + attr = obj.attributes[i]; + if(options.type && options.type === attr.type) { + rval = attr; + } else if(options.name && options.name === attr.name) { + rval = attr; + } else if(options.shortName && options.shortName === attr.shortName) { + rval = attr; + } + } + return rval; +} + +/** + * Converts signature parameters from ASN.1 structure. + * + * Currently only RSASSA-PSS supported. The PKCS#1 v1.5 signature scheme had + * no parameters. + * + * RSASSA-PSS-params ::= SEQUENCE { + * hashAlgorithm [0] HashAlgorithm DEFAULT + * sha1Identifier, + * maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT + * mgf1SHA1Identifier, + * saltLength [2] INTEGER DEFAULT 20, + * trailerField [3] INTEGER DEFAULT 1 + * } + * + * HashAlgorithm ::= AlgorithmIdentifier + * + * MaskGenAlgorithm ::= AlgorithmIdentifier + * + * AlgorithmIdentifer ::= SEQUENCE { + * algorithm OBJECT IDENTIFIER, + * parameters ANY DEFINED BY algorithm OPTIONAL + * } + * + * @param oid The OID specifying the signature algorithm + * @param obj The ASN.1 structure holding the parameters + * @param fillDefaults Whether to use return default values where omitted + * @return signature parameter object + */ +var _readSignatureParameters = function(oid, obj, fillDefaults) { + var params = {}; + + if(oid !== oids['RSASSA-PSS']) { + return params; + } + + if(fillDefaults) { + params = { + hash: { + algorithmOid: oids['sha1'] + }, + mgf: { + algorithmOid: oids['mgf1'], + hash: { + algorithmOid: oids['sha1'] + } + }, + saltLength: 20 + }; + } + + var capture = {}; + var errors = []; + if(!asn1.validate(obj, rsassaPssParameterValidator, capture, errors)) { + var error = new Error('Cannot read RSASSA-PSS parameter block.'); + error.errors = errors; + throw error; + } + + if(capture.hashOid !== undefined) { + params.hash = params.hash || {}; + params.hash.algorithmOid = asn1.derToOid(capture.hashOid); + } + + if(capture.maskGenOid !== undefined) { + params.mgf = params.mgf || {}; + params.mgf.algorithmOid = asn1.derToOid(capture.maskGenOid); + params.mgf.hash = params.mgf.hash || {}; + params.mgf.hash.algorithmOid = asn1.derToOid(capture.maskGenHashOid); + } + + if(capture.saltLength !== undefined) { + params.saltLength = capture.saltLength.charCodeAt(0); + } + + return params; +}; + +/** + * Converts an X.509 certificate from PEM format. + * + * Note: If the certificate is to be verified then compute hash should + * be set to true. This will scan the TBSCertificate part of the ASN.1 + * object while it is converted so it doesn't need to be converted back + * to ASN.1-DER-encoding later. + * + * @param pem the PEM-formatted certificate. + * @param computeHash true to compute the hash for verification. + * @param strict true to be strict when checking ASN.1 value lengths, false to + * allow truncated values (default: true). + * + * @return the certificate. + */ +pki.certificateFromPem = function(pem, computeHash, strict) { + var msg = forge.pem.decode(pem)[0]; + + if(msg.type !== 'CERTIFICATE' && + msg.type !== 'X509 CERTIFICATE' && + msg.type !== 'TRUSTED CERTIFICATE') { + var error = new Error( + 'Could not convert certificate from PEM; PEM header type ' + + 'is not "CERTIFICATE", "X509 CERTIFICATE", or "TRUSTED CERTIFICATE".'); + error.headerType = msg.type; + throw error; + } + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error( + 'Could not convert certificate from PEM; PEM is encrypted.'); + } + + // convert DER to ASN.1 object + var obj = asn1.fromDer(msg.body, strict); + + return pki.certificateFromAsn1(obj, computeHash); +}; + +/** + * Converts an X.509 certificate to PEM format. + * + * @param cert the certificate. + * @param maxline the maximum characters per line, defaults to 64. + * + * @return the PEM-formatted certificate. + */ +pki.certificateToPem = function(cert, maxline) { + // convert to ASN.1, then DER, then PEM-encode + var msg = { + type: 'CERTIFICATE', + body: asn1.toDer(pki.certificateToAsn1(cert)).getBytes() + }; + return forge.pem.encode(msg, {maxline: maxline}); +}; + +/** + * Converts an RSA public key from PEM format. + * + * @param pem the PEM-formatted public key. + * + * @return the public key. + */ +pki.publicKeyFromPem = function(pem) { + var msg = forge.pem.decode(pem)[0]; + + if(msg.type !== 'PUBLIC KEY' && msg.type !== 'RSA PUBLIC KEY') { + var error = new Error('Could not convert public key from PEM; PEM header ' + + 'type is not "PUBLIC KEY" or "RSA PUBLIC KEY".'); + error.headerType = msg.type; + throw error; + } + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert public key from PEM; PEM is encrypted.'); + } + + // convert DER to ASN.1 object + var obj = asn1.fromDer(msg.body); + + return pki.publicKeyFromAsn1(obj); +}; + +/** + * Converts an RSA public key to PEM format (using a SubjectPublicKeyInfo). + * + * @param key the public key. + * @param maxline the maximum characters per line, defaults to 64. + * + * @return the PEM-formatted public key. + */ +pki.publicKeyToPem = function(key, maxline) { + // convert to ASN.1, then DER, then PEM-encode + var msg = { + type: 'PUBLIC KEY', + body: asn1.toDer(pki.publicKeyToAsn1(key)).getBytes() + }; + return forge.pem.encode(msg, {maxline: maxline}); +}; + +/** + * Converts an RSA public key to PEM format (using an RSAPublicKey). + * + * @param key the public key. + * @param maxline the maximum characters per line, defaults to 64. + * + * @return the PEM-formatted public key. + */ +pki.publicKeyToRSAPublicKeyPem = function(key, maxline) { + // convert to ASN.1, then DER, then PEM-encode + var msg = { + type: 'RSA PUBLIC KEY', + body: asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes() + }; + return forge.pem.encode(msg, {maxline: maxline}); +}; + +/** + * Gets a fingerprint for the given public key. + * + * @param options the options to use. + * [md] the message digest object to use (defaults to forge.md.sha1). + * [type] the type of fingerprint, such as 'RSAPublicKey', + * 'SubjectPublicKeyInfo' (defaults to 'RSAPublicKey'). + * [encoding] an alternative output encoding, such as 'hex' + * (defaults to none, outputs a byte buffer). + * [delimiter] the delimiter to use between bytes for 'hex' encoded + * output, eg: ':' (defaults to none). + * + * @return the fingerprint as a byte buffer or other encoding based on options. + */ +pki.getPublicKeyFingerprint = function(key, options) { + options = options || {}; + var md = options.md || forge.md.sha1.create(); + var type = options.type || 'RSAPublicKey'; + + var bytes; + switch(type) { + case 'RSAPublicKey': + bytes = asn1.toDer(pki.publicKeyToRSAPublicKey(key)).getBytes(); + break; + case 'SubjectPublicKeyInfo': + bytes = asn1.toDer(pki.publicKeyToAsn1(key)).getBytes(); + break; + default: + throw new Error('Unknown fingerprint type "' + options.type + '".'); + } + + // hash public key bytes + md.start(); + md.update(bytes); + var digest = md.digest(); + if(options.encoding === 'hex') { + var hex = digest.toHex(); + if(options.delimiter) { + return hex.match(/.{2}/g).join(options.delimiter); + } + return hex; + } else if(options.encoding === 'binary') { + return digest.getBytes(); + } else if(options.encoding) { + throw new Error('Unknown encoding "' + options.encoding + '".'); + } + return digest; +}; + +/** + * Converts a PKCS#10 certification request (CSR) from PEM format. + * + * Note: If the certification request is to be verified then compute hash + * should be set to true. This will scan the CertificationRequestInfo part of + * the ASN.1 object while it is converted so it doesn't need to be converted + * back to ASN.1-DER-encoding later. + * + * @param pem the PEM-formatted certificate. + * @param computeHash true to compute the hash for verification. + * @param strict true to be strict when checking ASN.1 value lengths, false to + * allow truncated values (default: true). + * + * @return the certification request (CSR). + */ +pki.certificationRequestFromPem = function(pem, computeHash, strict) { + var msg = forge.pem.decode(pem)[0]; + + if(msg.type !== 'CERTIFICATE REQUEST') { + var error = new Error('Could not convert certification request from PEM; ' + + 'PEM header type is not "CERTIFICATE REQUEST".'); + error.headerType = msg.type; + throw error; + } + if(msg.procType && msg.procType.type === 'ENCRYPTED') { + throw new Error('Could not convert certification request from PEM; ' + + 'PEM is encrypted.'); + } + + // convert DER to ASN.1 object + var obj = asn1.fromDer(msg.body, strict); + + return pki.certificationRequestFromAsn1(obj, computeHash); +}; + +/** + * Converts a PKCS#10 certification request (CSR) to PEM format. + * + * @param csr the certification request. + * @param maxline the maximum characters per line, defaults to 64. + * + * @return the PEM-formatted certification request. + */ +pki.certificationRequestToPem = function(csr, maxline) { + // convert to ASN.1, then DER, then PEM-encode + var msg = { + type: 'CERTIFICATE REQUEST', + body: asn1.toDer(pki.certificationRequestToAsn1(csr)).getBytes() + }; + return forge.pem.encode(msg, {maxline: maxline}); +}; + +/** + * Creates an empty X.509v3 RSA certificate. + * + * @return the certificate. + */ +pki.createCertificate = function() { + var cert = {}; + cert.version = 0x02; + cert.serialNumber = '00'; + cert.signatureOid = null; + cert.signature = null; + cert.siginfo = {}; + cert.siginfo.algorithmOid = null; + cert.validity = {}; + cert.validity.notBefore = new Date(); + cert.validity.notAfter = new Date(); + + cert.issuer = {}; + cert.issuer.getField = function(sn) { + return _getAttribute(cert.issuer, sn); + }; + cert.issuer.addField = function(attr) { + _fillMissingFields([attr]); + cert.issuer.attributes.push(attr); + }; + cert.issuer.attributes = []; + cert.issuer.hash = null; + + cert.subject = {}; + cert.subject.getField = function(sn) { + return _getAttribute(cert.subject, sn); + }; + cert.subject.addField = function(attr) { + _fillMissingFields([attr]); + cert.subject.attributes.push(attr); + }; + cert.subject.attributes = []; + cert.subject.hash = null; + + cert.extensions = []; + cert.publicKey = null; + cert.md = null; + + /** + * Sets the subject of this certificate. + * + * @param attrs the array of subject attributes to use. + * @param uniqueId an optional a unique ID to use. + */ + cert.setSubject = function(attrs, uniqueId) { + // set new attributes, clear hash + _fillMissingFields(attrs); + cert.subject.attributes = attrs; + delete cert.subject.uniqueId; + if(uniqueId) { + // TODO: support arbitrary bit length ids + cert.subject.uniqueId = uniqueId; + } + cert.subject.hash = null; + }; + + /** + * Sets the issuer of this certificate. + * + * @param attrs the array of issuer attributes to use. + * @param uniqueId an optional a unique ID to use. + */ + cert.setIssuer = function(attrs, uniqueId) { + // set new attributes, clear hash + _fillMissingFields(attrs); + cert.issuer.attributes = attrs; + delete cert.issuer.uniqueId; + if(uniqueId) { + // TODO: support arbitrary bit length ids + cert.issuer.uniqueId = uniqueId; + } + cert.issuer.hash = null; + }; + + /** + * Sets the extensions of this certificate. + * + * @param exts the array of extensions to use. + */ + cert.setExtensions = function(exts) { + for(var i = 0; i < exts.length; ++i) { + _fillMissingExtensionFields(exts[i], {cert: cert}); + } + // set new extensions + cert.extensions = exts; + }; + + /** + * Gets an extension by its name or id. + * + * @param options the name to use or an object with: + * name the name to use. + * id the id to use. + * + * @return the extension or null if not found. + */ + cert.getExtension = function(options) { + if(typeof options === 'string') { + options = {name: options}; + } + + var rval = null; + var ext; + for(var i = 0; rval === null && i < cert.extensions.length; ++i) { + ext = cert.extensions[i]; + if(options.id && ext.id === options.id) { + rval = ext; + } else if(options.name && ext.name === options.name) { + rval = ext; + } + } + return rval; + }; + + /** + * Signs this certificate using the given private key. + * + * @param key the private key to sign with. + * @param md the message digest object to use (defaults to forge.md.sha1). + */ + cert.sign = function(key, md) { + // TODO: get signature OID from private key + cert.md = md || forge.md.sha1.create(); + var algorithmOid = oids[cert.md.algorithm + 'WithRSAEncryption']; + if(!algorithmOid) { + var error = new Error('Could not compute certificate digest. ' + + 'Unknown message digest algorithm OID.'); + error.algorithm = cert.md.algorithm; + throw error; + } + cert.signatureOid = cert.siginfo.algorithmOid = algorithmOid; + + // get TBSCertificate, convert to DER + cert.tbsCertificate = pki.getTBSCertificate(cert); + var bytes = asn1.toDer(cert.tbsCertificate); + + // digest and sign + cert.md.update(bytes.getBytes()); + cert.signature = key.sign(cert.md); + }; + + /** + * Attempts verify the signature on the passed certificate using this + * certificate's public key. + * + * @param child the certificate to verify. + * + * @return true if verified, false if not. + */ + cert.verify = function(child) { + var rval = false; + + if(!cert.issued(child)) { + var issuer = child.issuer; + var subject = cert.subject; + var error = new Error( + 'The parent certificate did not issue the given child ' + + 'certificate; the child certificate\'s issuer does not match the ' + + 'parent\'s subject.'); + error.expectedIssuer = issuer.attributes; + error.actualIssuer = subject.attributes; + throw error; + } + + var md = child.md; + if(md === null) { + // check signature OID for supported signature types + if(child.signatureOid in oids) { + var oid = oids[child.signatureOid]; + switch(oid) { + case 'sha1WithRSAEncryption': + md = forge.md.sha1.create(); + break; + case 'md5WithRSAEncryption': + md = forge.md.md5.create(); + break; + case 'sha256WithRSAEncryption': + md = forge.md.sha256.create(); + break; + case 'sha384WithRSAEncryption': + md = forge.md.sha384.create(); + break; + case 'sha512WithRSAEncryption': + md = forge.md.sha512.create(); + break; + case 'RSASSA-PSS': + md = forge.md.sha256.create(); + break; + } + } + if(md === null) { + var error = new Error('Could not compute certificate digest. ' + + 'Unknown signature OID.'); + error.signatureOid = child.signatureOid; + throw error; + } + + // produce DER formatted TBSCertificate and digest it + var tbsCertificate = child.tbsCertificate || pki.getTBSCertificate(child); + var bytes = asn1.toDer(tbsCertificate); + md.update(bytes.getBytes()); + } + + if(md !== null) { + var scheme; + + switch(child.signatureOid) { + case oids.sha1WithRSAEncryption: + scheme = undefined; /* use PKCS#1 v1.5 padding scheme */ + break; + case oids['RSASSA-PSS']: + var hash, mgf; + + /* initialize mgf */ + hash = oids[child.signatureParameters.mgf.hash.algorithmOid]; + if(hash === undefined || forge.md[hash] === undefined) { + var error = new Error('Unsupported MGF hash function.'); + error.oid = child.signatureParameters.mgf.hash.algorithmOid; + error.name = hash; + throw error; + } + + mgf = oids[child.signatureParameters.mgf.algorithmOid]; + if(mgf === undefined || forge.mgf[mgf] === undefined) { + var error = new Error('Unsupported MGF function.'); + error.oid = child.signatureParameters.mgf.algorithmOid; + error.name = mgf; + throw error; + } + + mgf = forge.mgf[mgf].create(forge.md[hash].create()); + + /* initialize hash function */ + hash = oids[child.signatureParameters.hash.algorithmOid]; + if(hash === undefined || forge.md[hash] === undefined) { + throw { + message: 'Unsupported RSASSA-PSS hash function.', + oid: child.signatureParameters.hash.algorithmOid, + name: hash + }; + } + + scheme = forge.pss.create(forge.md[hash].create(), mgf, + child.signatureParameters.saltLength); + break; + } + + // verify signature on cert using public key + rval = cert.publicKey.verify( + md.digest().getBytes(), child.signature, scheme); + } + + return rval; + }; + + /** + * Returns true if this certificate's issuer matches the passed + * certificate's subject. Note that no signature check is performed. + * + * @param parent the certificate to check. + * + * @return true if this certificate's issuer matches the passed certificate's + * subject. + */ + cert.isIssuer = function(parent) { + var rval = false; + + var i = cert.issuer; + var s = parent.subject; + + // compare hashes if present + if(i.hash && s.hash) { + rval = (i.hash === s.hash); + } else if(i.attributes.length === s.attributes.length) { + // all attributes are the same so issuer matches subject + rval = true; + var iattr, sattr; + for(var n = 0; rval && n < i.attributes.length; ++n) { + iattr = i.attributes[n]; + sattr = s.attributes[n]; + if(iattr.type !== sattr.type || iattr.value !== sattr.value) { + // attribute mismatch + rval = false; + } + } + } + + return rval; + }; + + /** + * Returns true if this certificate's subject matches the issuer of the + * given certificate). Note that not signature check is performed. + * + * @param child the certificate to check. + * + * @return true if this certificate's subject matches the passed + * certificate's issuer. + */ + cert.issued = function(child) { + return child.isIssuer(cert); + }; + + /** + * Generates the subjectKeyIdentifier for this certificate as byte buffer. + * + * @return the subjectKeyIdentifier for this certificate as byte buffer. + */ + cert.generateSubjectKeyIdentifier = function() { + /* See: 4.2.1.2 section of the the RFC3280, keyIdentifier is either: + + (1) The keyIdentifier is composed of the 160-bit SHA-1 hash of the + value of the BIT STRING subjectPublicKey (excluding the tag, + length, and number of unused bits). + + (2) The keyIdentifier is composed of a four bit type field with + the value 0100 followed by the least significant 60 bits of the + SHA-1 hash of the value of the BIT STRING subjectPublicKey + (excluding the tag, length, and number of unused bit string bits). + */ + + // skipping the tag, length, and number of unused bits is the same + // as just using the RSAPublicKey (for RSA keys, which are the + // only ones supported) + return pki.getPublicKeyFingerprint(cert.publicKey, {type: 'RSAPublicKey'}); + }; + + /** + * Verifies the subjectKeyIdentifier extension value for this certificate + * against its public key. If no extension is found, false will be + * returned. + * + * @return true if verified, false if not. + */ + cert.verifySubjectKeyIdentifier = function() { + var oid = oids['subjectKeyIdentifier']; + for(var i = 0; i < cert.extensions.length; ++i) { + var ext = cert.extensions[i]; + if(ext.id === oid) { + var ski = cert.generateSubjectKeyIdentifier().getBytes(); + return (forge.util.hexToBytes(ext.subjectKeyIdentifier) === ski); + } + } + return false; + }; + + return cert; +}; + +/** + * Converts an X.509v3 RSA certificate from an ASN.1 object. + * + * Note: If the certificate is to be verified then compute hash should + * be set to true. There is currently no implementation for converting + * a certificate back to ASN.1 so the TBSCertificate part of the ASN.1 + * object needs to be scanned before the cert object is created. + * + * @param obj the asn1 representation of an X.509v3 RSA certificate. + * @param computeHash true to compute the hash for verification. + * + * @return the certificate. + */ +pki.certificateFromAsn1 = function(obj, computeHash) { + // validate certificate and capture data + var capture = {}; + var errors = []; + if(!asn1.validate(obj, x509CertificateValidator, capture, errors)) { + var error = new Error('Cannot read X.509 certificate. ' + + 'ASN.1 object is not an X509v3 Certificate.'); + error.errors = errors; + throw error; + } + + // get oid + var oid = asn1.derToOid(capture.publicKeyOid); + if(oid !== pki.oids.rsaEncryption) { + throw new Error('Cannot read public key. OID is not RSA.'); + } + + // create certificate + var cert = pki.createCertificate(); + cert.version = capture.certVersion ? + capture.certVersion.charCodeAt(0) : 0; + var serial = forge.util.createBuffer(capture.certSerialNumber); + cert.serialNumber = serial.toHex(); + cert.signatureOid = forge.asn1.derToOid(capture.certSignatureOid); + cert.signatureParameters = _readSignatureParameters( + cert.signatureOid, capture.certSignatureParams, true); + cert.siginfo.algorithmOid = forge.asn1.derToOid(capture.certinfoSignatureOid); + cert.siginfo.parameters = _readSignatureParameters(cert.siginfo.algorithmOid, + capture.certinfoSignatureParams, false); + cert.signature = capture.certSignature; + + var validity = []; + if(capture.certValidity1UTCTime !== undefined) { + validity.push(asn1.utcTimeToDate(capture.certValidity1UTCTime)); + } + if(capture.certValidity2GeneralizedTime !== undefined) { + validity.push(asn1.generalizedTimeToDate( + capture.certValidity2GeneralizedTime)); + } + if(capture.certValidity3UTCTime !== undefined) { + validity.push(asn1.utcTimeToDate(capture.certValidity3UTCTime)); + } + if(capture.certValidity4GeneralizedTime !== undefined) { + validity.push(asn1.generalizedTimeToDate( + capture.certValidity4GeneralizedTime)); + } + if(validity.length > 2) { + throw new Error('Cannot read notBefore/notAfter validity times; more ' + + 'than two times were provided in the certificate.'); + } + if(validity.length < 2) { + throw new Error('Cannot read notBefore/notAfter validity times; they ' + + 'were not provided as either UTCTime or GeneralizedTime.'); + } + cert.validity.notBefore = validity[0]; + cert.validity.notAfter = validity[1]; + + // keep TBSCertificate to preserve signature when exporting + cert.tbsCertificate = capture.tbsCertificate; + + if(computeHash) { + // check signature OID for supported signature types + cert.md = null; + if(cert.signatureOid in oids) { + var oid = oids[cert.signatureOid]; + switch(oid) { + case 'sha1WithRSAEncryption': + cert.md = forge.md.sha1.create(); + break; + case 'md5WithRSAEncryption': + cert.md = forge.md.md5.create(); + break; + case 'sha256WithRSAEncryption': + cert.md = forge.md.sha256.create(); + break; + case 'sha384WithRSAEncryption': + cert.md = forge.md.sha384.create(); + break; + case 'sha512WithRSAEncryption': + cert.md = forge.md.sha512.create(); + break; + case 'RSASSA-PSS': + cert.md = forge.md.sha256.create(); + break; + } + } + if(cert.md === null) { + var error = new Error('Could not compute certificate digest. ' + + 'Unknown signature OID.'); + error.signatureOid = cert.signatureOid; + throw error; + } + + // produce DER formatted TBSCertificate and digest it + var bytes = asn1.toDer(cert.tbsCertificate); + cert.md.update(bytes.getBytes()); + } + + // handle issuer, build issuer message digest + var imd = forge.md.sha1.create(); + cert.issuer.getField = function(sn) { + return _getAttribute(cert.issuer, sn); + }; + cert.issuer.addField = function(attr) { + _fillMissingFields([attr]); + cert.issuer.attributes.push(attr); + }; + cert.issuer.attributes = pki.RDNAttributesAsArray(capture.certIssuer, imd); + if(capture.certIssuerUniqueId) { + cert.issuer.uniqueId = capture.certIssuerUniqueId; + } + cert.issuer.hash = imd.digest().toHex(); + + // handle subject, build subject message digest + var smd = forge.md.sha1.create(); + cert.subject.getField = function(sn) { + return _getAttribute(cert.subject, sn); + }; + cert.subject.addField = function(attr) { + _fillMissingFields([attr]); + cert.subject.attributes.push(attr); + }; + cert.subject.attributes = pki.RDNAttributesAsArray(capture.certSubject, smd); + if(capture.certSubjectUniqueId) { + cert.subject.uniqueId = capture.certSubjectUniqueId; + } + cert.subject.hash = smd.digest().toHex(); + + // handle extensions + if(capture.certExtensions) { + cert.extensions = pki.certificateExtensionsFromAsn1(capture.certExtensions); + } else { + cert.extensions = []; + } + + // convert RSA public key from ASN.1 + cert.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo); + + return cert; +}; + +/** + * Converts an ASN.1 extensions object (with extension sequences as its + * values) into an array of extension objects with types and values. + * + * Supported extensions: + * + * id-ce-keyUsage OBJECT IDENTIFIER ::= { id-ce 15 } + * KeyUsage ::= BIT STRING { + * digitalSignature (0), + * nonRepudiation (1), + * keyEncipherment (2), + * dataEncipherment (3), + * keyAgreement (4), + * keyCertSign (5), + * cRLSign (6), + * encipherOnly (7), + * decipherOnly (8) + * } + * + * id-ce-basicConstraints OBJECT IDENTIFIER ::= { id-ce 19 } + * BasicConstraints ::= SEQUENCE { + * cA BOOLEAN DEFAULT FALSE, + * pathLenConstraint INTEGER (0..MAX) OPTIONAL + * } + * + * subjectAltName EXTENSION ::= { + * SYNTAX GeneralNames + * IDENTIFIED BY id-ce-subjectAltName + * } + * + * GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName + * + * GeneralName ::= CHOICE { + * otherName [0] INSTANCE OF OTHER-NAME, + * rfc822Name [1] IA5String, + * dNSName [2] IA5String, + * x400Address [3] ORAddress, + * directoryName [4] Name, + * ediPartyName [5] EDIPartyName, + * uniformResourceIdentifier [6] IA5String, + * IPAddress [7] OCTET STRING, + * registeredID [8] OBJECT IDENTIFIER + * } + * + * OTHER-NAME ::= TYPE-IDENTIFIER + * + * EDIPartyName ::= SEQUENCE { + * nameAssigner [0] DirectoryString {ub-name} OPTIONAL, + * partyName [1] DirectoryString {ub-name} + * } + * + * @param exts the extensions ASN.1 with extension sequences to parse. + * + * @return the array. + */ +pki.certificateExtensionsFromAsn1 = function(exts) { + var rval = []; + for(var i = 0; i < exts.value.length; ++i) { + // get extension sequence + var extseq = exts.value[i]; + for(var ei = 0; ei < extseq.value.length; ++ei) { + rval.push(pki.certificateExtensionFromAsn1(extseq.value[ei])); + } + } + + return rval; +}; + +/** + * Parses a single certificate extension from ASN.1. + * + * @param ext the extension in ASN.1 format. + * + * @return the parsed extension as an object. + */ +pki.certificateExtensionFromAsn1 = function(ext) { + // an extension has: + // [0] extnID OBJECT IDENTIFIER + // [1] critical BOOLEAN DEFAULT FALSE + // [2] extnValue OCTET STRING + var e = {}; + e.id = asn1.derToOid(ext.value[0].value); + e.critical = false; + if(ext.value[1].type === asn1.Type.BOOLEAN) { + e.critical = (ext.value[1].value.charCodeAt(0) !== 0x00); + e.value = ext.value[2].value; + } else { + e.value = ext.value[1].value; + } + // if the oid is known, get its name + if(e.id in oids) { + e.name = oids[e.id]; + + // handle key usage + if(e.name === 'keyUsage') { + // get value as BIT STRING + var ev = asn1.fromDer(e.value); + var b2 = 0x00; + var b3 = 0x00; + if(ev.value.length > 1) { + // skip first byte, just indicates unused bits which + // will be padded with 0s anyway + // get bytes with flag bits + b2 = ev.value.charCodeAt(1); + b3 = ev.value.length > 2 ? ev.value.charCodeAt(2) : 0; + } + // set flags + e.digitalSignature = (b2 & 0x80) === 0x80; + e.nonRepudiation = (b2 & 0x40) === 0x40; + e.keyEncipherment = (b2 & 0x20) === 0x20; + e.dataEncipherment = (b2 & 0x10) === 0x10; + e.keyAgreement = (b2 & 0x08) === 0x08; + e.keyCertSign = (b2 & 0x04) === 0x04; + e.cRLSign = (b2 & 0x02) === 0x02; + e.encipherOnly = (b2 & 0x01) === 0x01; + e.decipherOnly = (b3 & 0x80) === 0x80; + } else if(e.name === 'basicConstraints') { + // handle basic constraints + // get value as SEQUENCE + var ev = asn1.fromDer(e.value); + // get cA BOOLEAN flag (defaults to false) + if(ev.value.length > 0 && ev.value[0].type === asn1.Type.BOOLEAN) { + e.cA = (ev.value[0].value.charCodeAt(0) !== 0x00); + } else { + e.cA = false; + } + // get path length constraint + var value = null; + if(ev.value.length > 0 && ev.value[0].type === asn1.Type.INTEGER) { + value = ev.value[0].value; + } else if(ev.value.length > 1) { + value = ev.value[1].value; + } + if(value !== null) { + e.pathLenConstraint = asn1.derToInteger(value); + } + } else if(e.name === 'extKeyUsage') { + // handle extKeyUsage + // value is a SEQUENCE of OIDs + var ev = asn1.fromDer(e.value); + for(var vi = 0; vi < ev.value.length; ++vi) { + var oid = asn1.derToOid(ev.value[vi].value); + if(oid in oids) { + e[oids[oid]] = true; + } else { + e[oid] = true; + } + } + } else if(e.name === 'nsCertType') { + // handle nsCertType + // get value as BIT STRING + var ev = asn1.fromDer(e.value); + var b2 = 0x00; + if(ev.value.length > 1) { + // skip first byte, just indicates unused bits which + // will be padded with 0s anyway + // get bytes with flag bits + b2 = ev.value.charCodeAt(1); + } + // set flags + e.client = (b2 & 0x80) === 0x80; + e.server = (b2 & 0x40) === 0x40; + e.email = (b2 & 0x20) === 0x20; + e.objsign = (b2 & 0x10) === 0x10; + e.reserved = (b2 & 0x08) === 0x08; + e.sslCA = (b2 & 0x04) === 0x04; + e.emailCA = (b2 & 0x02) === 0x02; + e.objCA = (b2 & 0x01) === 0x01; + } else if( + e.name === 'subjectAltName' || + e.name === 'issuerAltName') { + // handle subjectAltName/issuerAltName + e.altNames = []; + + // ev is a SYNTAX SEQUENCE + var gn; + var ev = asn1.fromDer(e.value); + for(var n = 0; n < ev.value.length; ++n) { + // get GeneralName + gn = ev.value[n]; + + var altName = { + type: gn.type, + value: gn.value + }; + e.altNames.push(altName); + + // Note: Support for types 1,2,6,7,8 + switch(gn.type) { + // rfc822Name + case 1: + // dNSName + case 2: + // uniformResourceIdentifier (URI) + case 6: + break; + // IPAddress + case 7: + // convert to IPv4/IPv6 string representation + altName.ip = forge.util.bytesToIP(gn.value); + break; + // registeredID + case 8: + altName.oid = asn1.derToOid(gn.value); + break; + default: + // unsupported + } + } + } else if(e.name === 'subjectKeyIdentifier') { + // value is an OCTETSTRING w/the hash of the key-type specific + // public key structure (eg: RSAPublicKey) + var ev = asn1.fromDer(e.value); + e.subjectKeyIdentifier = forge.util.bytesToHex(ev.value); + } + } + return e; +}; + +/** + * Converts a PKCS#10 certification request (CSR) from an ASN.1 object. + * + * Note: If the certification request is to be verified then compute hash + * should be set to true. There is currently no implementation for converting + * a certificate back to ASN.1 so the CertificationRequestInfo part of the + * ASN.1 object needs to be scanned before the csr object is created. + * + * @param obj the asn1 representation of a PKCS#10 certification request (CSR). + * @param computeHash true to compute the hash for verification. + * + * @return the certification request (CSR). + */ +pki.certificationRequestFromAsn1 = function(obj, computeHash) { + // validate certification request and capture data + var capture = {}; + var errors = []; + if(!asn1.validate(obj, certificationRequestValidator, capture, errors)) { + var error = new Error('Cannot read PKCS#10 certificate request. ' + + 'ASN.1 object is not a PKCS#10 CertificationRequest.'); + error.errors = errors; + throw error; + } + + // get oid + var oid = asn1.derToOid(capture.publicKeyOid); + if(oid !== pki.oids.rsaEncryption) { + throw new Error('Cannot read public key. OID is not RSA.'); + } + + // create certification request + var csr = pki.createCertificationRequest(); + csr.version = capture.csrVersion ? capture.csrVersion.charCodeAt(0) : 0; + csr.signatureOid = forge.asn1.derToOid(capture.csrSignatureOid); + csr.signatureParameters = _readSignatureParameters( + csr.signatureOid, capture.csrSignatureParams, true); + csr.siginfo.algorithmOid = forge.asn1.derToOid(capture.csrSignatureOid); + csr.siginfo.parameters = _readSignatureParameters( + csr.siginfo.algorithmOid, capture.csrSignatureParams, false); + csr.signature = capture.csrSignature; + + // keep CertificationRequestInfo to preserve signature when exporting + csr.certificationRequestInfo = capture.certificationRequestInfo; + + if(computeHash) { + // check signature OID for supported signature types + csr.md = null; + if(csr.signatureOid in oids) { + var oid = oids[csr.signatureOid]; + switch(oid) { + case 'sha1WithRSAEncryption': + csr.md = forge.md.sha1.create(); + break; + case 'md5WithRSAEncryption': + csr.md = forge.md.md5.create(); + break; + case 'sha256WithRSAEncryption': + csr.md = forge.md.sha256.create(); + break; + case 'sha384WithRSAEncryption': + csr.md = forge.md.sha384.create(); + break; + case 'sha512WithRSAEncryption': + csr.md = forge.md.sha512.create(); + break; + case 'RSASSA-PSS': + csr.md = forge.md.sha256.create(); + break; + } + } + if(csr.md === null) { + var error = new Error('Could not compute certification request digest. ' + + 'Unknown signature OID.'); + error.signatureOid = csr.signatureOid; + throw error; + } + + // produce DER formatted CertificationRequestInfo and digest it + var bytes = asn1.toDer(csr.certificationRequestInfo); + csr.md.update(bytes.getBytes()); + } + + // handle subject, build subject message digest + var smd = forge.md.sha1.create(); + csr.subject.getField = function(sn) { + return _getAttribute(csr.subject, sn); + }; + csr.subject.addField = function(attr) { + _fillMissingFields([attr]); + csr.subject.attributes.push(attr); + }; + csr.subject.attributes = pki.RDNAttributesAsArray( + capture.certificationRequestInfoSubject, smd); + csr.subject.hash = smd.digest().toHex(); + + // convert RSA public key from ASN.1 + csr.publicKey = pki.publicKeyFromAsn1(capture.subjectPublicKeyInfo); + + // convert attributes from ASN.1 + csr.getAttribute = function(sn) { + return _getAttribute(csr, sn); + }; + csr.addAttribute = function(attr) { + _fillMissingFields([attr]); + csr.attributes.push(attr); + }; + csr.attributes = pki.CRIAttributesAsArray( + capture.certificationRequestInfoAttributes || []); + + return csr; +}; + +/** + * Creates an empty certification request (a CSR or certificate signing + * request). Once created, its public key and attributes can be set and then + * it can be signed. + * + * @return the empty certification request. + */ +pki.createCertificationRequest = function() { + var csr = {}; + csr.version = 0x00; + csr.signatureOid = null; + csr.signature = null; + csr.siginfo = {}; + csr.siginfo.algorithmOid = null; + + csr.subject = {}; + csr.subject.getField = function(sn) { + return _getAttribute(csr.subject, sn); + }; + csr.subject.addField = function(attr) { + _fillMissingFields([attr]); + csr.subject.attributes.push(attr); + }; + csr.subject.attributes = []; + csr.subject.hash = null; + + csr.publicKey = null; + csr.attributes = []; + csr.getAttribute = function(sn) { + return _getAttribute(csr, sn); + }; + csr.addAttribute = function(attr) { + _fillMissingFields([attr]); + csr.attributes.push(attr); + }; + csr.md = null; + + /** + * Sets the subject of this certification request. + * + * @param attrs the array of subject attributes to use. + */ + csr.setSubject = function(attrs) { + // set new attributes + _fillMissingFields(attrs); + csr.subject.attributes = attrs; + csr.subject.hash = null; + }; + + /** + * Sets the attributes of this certification request. + * + * @param attrs the array of attributes to use. + */ + csr.setAttributes = function(attrs) { + // set new attributes + _fillMissingFields(attrs); + csr.attributes = attrs; + }; + + /** + * Signs this certification request using the given private key. + * + * @param key the private key to sign with. + * @param md the message digest object to use (defaults to forge.md.sha1). + */ + csr.sign = function(key, md) { + // TODO: get signature OID from private key + csr.md = md || forge.md.sha1.create(); + var algorithmOid = oids[csr.md.algorithm + 'WithRSAEncryption']; + if(!algorithmOid) { + var error = new Error('Could not compute certification request digest. ' + + 'Unknown message digest algorithm OID.'); + error.algorithm = csr.md.algorithm; + throw error; + } + csr.signatureOid = csr.siginfo.algorithmOid = algorithmOid; + + // get CertificationRequestInfo, convert to DER + csr.certificationRequestInfo = pki.getCertificationRequestInfo(csr); + var bytes = asn1.toDer(csr.certificationRequestInfo); + + // digest and sign + csr.md.update(bytes.getBytes()); + csr.signature = key.sign(csr.md); + }; + + /** + * Attempts verify the signature on the passed certification request using + * its public key. + * + * A CSR that has been exported to a file in PEM format can be verified using + * OpenSSL using this command: + * + * openssl req -in -verify -noout -text + * + * @return true if verified, false if not. + */ + csr.verify = function() { + var rval = false; + + var md = csr.md; + if(md === null) { + // check signature OID for supported signature types + if(csr.signatureOid in oids) { + // TODO: create DRY `OID to md` function + var oid = oids[csr.signatureOid]; + switch(oid) { + case 'sha1WithRSAEncryption': + md = forge.md.sha1.create(); + break; + case 'md5WithRSAEncryption': + md = forge.md.md5.create(); + break; + case 'sha256WithRSAEncryption': + md = forge.md.sha256.create(); + break; + case 'sha384WithRSAEncryption': + md = forge.md.sha384.create(); + break; + case 'sha512WithRSAEncryption': + md = forge.md.sha512.create(); + break; + case 'RSASSA-PSS': + md = forge.md.sha256.create(); + break; + } + } + if(md === null) { + var error = new Error( + 'Could not compute certification request digest. ' + + 'Unknown signature OID.'); + error.signatureOid = csr.signatureOid; + throw error; + } + + // produce DER formatted CertificationRequestInfo and digest it + var cri = csr.certificationRequestInfo || + pki.getCertificationRequestInfo(csr); + var bytes = asn1.toDer(cri); + md.update(bytes.getBytes()); + } + + if(md !== null) { + var scheme; + + switch(csr.signatureOid) { + case oids.sha1WithRSAEncryption: + /* use PKCS#1 v1.5 padding scheme */ + break; + case oids['RSASSA-PSS']: + var hash, mgf; + + /* initialize mgf */ + hash = oids[csr.signatureParameters.mgf.hash.algorithmOid]; + if(hash === undefined || forge.md[hash] === undefined) { + var error = new Error('Unsupported MGF hash function.'); + error.oid = csr.signatureParameters.mgf.hash.algorithmOid; + error.name = hash; + throw error; + } + + mgf = oids[csr.signatureParameters.mgf.algorithmOid]; + if(mgf === undefined || forge.mgf[mgf] === undefined) { + var error = new Error('Unsupported MGF function.'); + error.oid = csr.signatureParameters.mgf.algorithmOid; + error.name = mgf; + throw error; + } + + mgf = forge.mgf[mgf].create(forge.md[hash].create()); + + /* initialize hash function */ + hash = oids[csr.signatureParameters.hash.algorithmOid]; + if(hash === undefined || forge.md[hash] === undefined) { + var error = new Error('Unsupported RSASSA-PSS hash function.'); + error.oid = csr.signatureParameters.hash.algorithmOid; + error.name = hash; + throw error; + } + + scheme = forge.pss.create(forge.md[hash].create(), mgf, + csr.signatureParameters.saltLength); + break; + } + + // verify signature on csr using its public key + rval = csr.publicKey.verify( + md.digest().getBytes(), csr.signature, scheme); + } + + return rval; + }; + + return csr; +}; + +/** + * Converts an X.509 subject or issuer to an ASN.1 RDNSequence. + * + * @param obj the subject or issuer (distinguished name). + * + * @return the ASN.1 RDNSequence. + */ +function _dnToAsn1(obj) { + // create an empty RDNSequence + var rval = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + + // iterate over attributes + var attr, set; + var attrs = obj.attributes; + for(var i = 0; i < attrs.length; ++i) { + attr = attrs[i]; + var value = attr.value; + + // reuse tag class for attribute value if available + var valueTagClass = asn1.Type.PRINTABLESTRING; + if('valueTagClass' in attr) { + valueTagClass = attr.valueTagClass; + + if(valueTagClass === asn1.Type.UTF8) { + value = forge.util.encodeUtf8(value); + } + // FIXME: handle more encodings + } + + // create a RelativeDistinguishedName set + // each value in the set is an AttributeTypeAndValue first + // containing the type (an OID) and second the value + set = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // AttributeType + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(attr.type).getBytes()), + // AttributeValue + asn1.create(asn1.Class.UNIVERSAL, valueTagClass, false, value) + ]) + ]); + rval.value.push(set); + } + + return rval; +} + +/** + * Gets all printable attributes (typically of an issuer or subject) in a + * simplified JSON format for display. + * + * @param attrs the attributes. + * + * @return the JSON for display. + */ +function _getAttributesAsJson(attrs) { + var rval = {}; + for(var i = 0; i < attrs.length; ++i) { + var attr = attrs[i]; + if(attr.shortName && ( + attr.valueTagClass === asn1.Type.UTF8 || + attr.valueTagClass === asn1.Type.PRINTABLESTRING || + attr.valueTagClass === asn1.Type.IA5STRING)) { + var value = attr.value; + if(attr.valueTagClass === asn1.Type.UTF8) { + value = forge.util.encodeUtf8(attr.value); + } + if(!(attr.shortName in rval)) { + rval[attr.shortName] = value; + } else if(forge.util.isArray(rval[attr.shortName])) { + rval[attr.shortName].push(value); + } else { + rval[attr.shortName] = [rval[attr.shortName], value]; + } + } + } + return rval; +} + +/** + * Fills in missing fields in attributes. + * + * @param attrs the attributes to fill missing fields in. + */ +function _fillMissingFields(attrs) { + var attr; + for(var i = 0; i < attrs.length; ++i) { + attr = attrs[i]; + + // populate missing name + if(typeof attr.name === 'undefined') { + if(attr.type && attr.type in pki.oids) { + attr.name = pki.oids[attr.type]; + } else if(attr.shortName && attr.shortName in _shortNames) { + attr.name = pki.oids[_shortNames[attr.shortName]]; + } + } + + // populate missing type (OID) + if(typeof attr.type === 'undefined') { + if(attr.name && attr.name in pki.oids) { + attr.type = pki.oids[attr.name]; + } else { + var error = new Error('Attribute type not specified.'); + error.attribute = attr; + throw error; + } + } + + // populate missing shortname + if(typeof attr.shortName === 'undefined') { + if(attr.name && attr.name in _shortNames) { + attr.shortName = _shortNames[attr.name]; + } + } + + // convert extensions to value + if(attr.type === oids.extensionRequest) { + attr.valueConstructed = true; + attr.valueTagClass = asn1.Type.SEQUENCE; + if(!attr.value && attr.extensions) { + attr.value = []; + for(var ei = 0; ei < attr.extensions.length; ++ei) { + attr.value.push(pki.certificateExtensionToAsn1( + _fillMissingExtensionFields(attr.extensions[ei]))); + } + } + } + + if(typeof attr.value === 'undefined') { + var error = new Error('Attribute value not specified.'); + error.attribute = attr; + throw error; + } + } +} + +/** + * Fills in missing fields in certificate extensions. + * + * @param e the extension. + * @param [options] the options to use. + * [cert] the certificate the extensions are for. + * + * @return the extension. + */ +function _fillMissingExtensionFields(e, options) { + options = options || {}; + + // populate missing name + if(typeof e.name === 'undefined') { + if(e.id && e.id in pki.oids) { + e.name = pki.oids[e.id]; + } + } + + // populate missing id + if(typeof e.id === 'undefined') { + if(e.name && e.name in pki.oids) { + e.id = pki.oids[e.name]; + } else { + var error = new Error('Extension ID not specified.'); + error.extension = e; + throw error; + } + } + + if(typeof e.value !== 'undefined') { + return e; + } + + // handle missing value: + + // value is a BIT STRING + if(e.name === 'keyUsage') { + // build flags + var unused = 0; + var b2 = 0x00; + var b3 = 0x00; + if(e.digitalSignature) { + b2 |= 0x80; + unused = 7; + } + if(e.nonRepudiation) { + b2 |= 0x40; + unused = 6; + } + if(e.keyEncipherment) { + b2 |= 0x20; + unused = 5; + } + if(e.dataEncipherment) { + b2 |= 0x10; + unused = 4; + } + if(e.keyAgreement) { + b2 |= 0x08; + unused = 3; + } + if(e.keyCertSign) { + b2 |= 0x04; + unused = 2; + } + if(e.cRLSign) { + b2 |= 0x02; + unused = 1; + } + if(e.encipherOnly) { + b2 |= 0x01; + unused = 0; + } + if(e.decipherOnly) { + b3 |= 0x80; + unused = 7; + } + + // create bit string + var value = String.fromCharCode(unused); + if(b3 !== 0) { + value += String.fromCharCode(b2) + String.fromCharCode(b3); + } else if(b2 !== 0) { + value += String.fromCharCode(b2); + } + e.value = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value); + } else if(e.name === 'basicConstraints') { + // basicConstraints is a SEQUENCE + e.value = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + // cA BOOLEAN flag defaults to false + if(e.cA) { + e.value.value.push(asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false, + String.fromCharCode(0xFF))); + } + if('pathLenConstraint' in e) { + e.value.value.push(asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(e.pathLenConstraint).getBytes())); + } + } else if(e.name === 'extKeyUsage') { + // extKeyUsage is a SEQUENCE of OIDs + e.value = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + var seq = e.value.value; + for(var key in e) { + if(e[key] !== true) { + continue; + } + // key is name in OID map + if(key in oids) { + seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, + false, asn1.oidToDer(oids[key]).getBytes())); + } else if(key.indexOf('.') !== -1) { + // assume key is an OID + seq.push(asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, + false, asn1.oidToDer(key).getBytes())); + } + } + } else if(e.name === 'nsCertType') { + // nsCertType is a BIT STRING + // build flags + var unused = 0; + var b2 = 0x00; + + if(e.client) { + b2 |= 0x80; + unused = 7; + } + if(e.server) { + b2 |= 0x40; + unused = 6; + } + if(e.email) { + b2 |= 0x20; + unused = 5; + } + if(e.objsign) { + b2 |= 0x10; + unused = 4; + } + if(e.reserved) { + b2 |= 0x08; + unused = 3; + } + if(e.sslCA) { + b2 |= 0x04; + unused = 2; + } + if(e.emailCA) { + b2 |= 0x02; + unused = 1; + } + if(e.objCA) { + b2 |= 0x01; + unused = 0; + } + + // create bit string + var value = String.fromCharCode(unused); + if(b2 !== 0) { + value += String.fromCharCode(b2); + } + e.value = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, value); + } else if(e.name === 'subjectAltName' || e.name === 'issuerAltName') { + // SYNTAX SEQUENCE + e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + + var altName; + for(var n = 0; n < e.altNames.length; ++n) { + altName = e.altNames[n]; + var value = altName.value; + // handle IP + if(altName.type === 7 && altName.ip) { + value = forge.util.bytesFromIP(altName.ip); + if(value === null) { + var error = new Error( + 'Extension "ip" value is not a valid IPv4 or IPv6 address.'); + error.extension = e; + throw error; + } + } else if(altName.type === 8) { + // handle OID + if(altName.oid) { + value = asn1.oidToDer(asn1.oidToDer(altName.oid)); + } else { + // deprecated ... convert value to OID + value = asn1.oidToDer(value); + } + } + e.value.value.push(asn1.create( + asn1.Class.CONTEXT_SPECIFIC, altName.type, false, + value)); + } + } else if(e.name === 'nsComment' && options.cert) { + // sanity check value is ASCII (req'd) and not too big + if(!(/^[\x00-\x7F]*$/.test(e.comment)) || + (e.comment.length < 1) || (e.comment.length > 128)) { + throw new Error('Invalid "nsComment" content.'); + } + // IA5STRING opaque comment + e.value = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.IA5STRING, false, e.comment); + } else if(e.name === 'subjectKeyIdentifier' && options.cert) { + var ski = options.cert.generateSubjectKeyIdentifier(); + e.subjectKeyIdentifier = ski.toHex(); + // OCTETSTRING w/digest + e.value = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, ski.getBytes()); + } else if(e.name === 'authorityKeyIdentifier' && options.cert) { + // SYNTAX SEQUENCE + e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + var seq = e.value.value; + + if(e.keyIdentifier) { + var keyIdentifier = (e.keyIdentifier === true ? + options.cert.generateSubjectKeyIdentifier().getBytes() : + e.keyIdentifier); + seq.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, false, keyIdentifier)); + } + + if(e.authorityCertIssuer) { + var authorityCertIssuer = [ + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 4, true, [ + _dnToAsn1(e.authorityCertIssuer === true ? + options.cert.issuer : e.authorityCertIssuer) + ]) + ]; + seq.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, authorityCertIssuer)); + } + + if(e.serialNumber) { + var serialNumber = forge.util.hexToBytes(e.serialNumber === true ? + options.cert.serialNumber : e.serialNumber); + seq.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, false, serialNumber)); + } + } else if(e.name === 'cRLDistributionPoints') { + e.value = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + var seq = e.value.value; + + // Create sub SEQUENCE of DistributionPointName + var subSeq = asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + + // Create fullName CHOICE + var fullNameGeneralNames = asn1.create( + asn1.Class.CONTEXT_SPECIFIC, 0, true, []); + var altName; + for(var n = 0; n < e.altNames.length; ++n) { + altName = e.altNames[n]; + var value = altName.value; + // handle IP + if(altName.type === 7 && altName.ip) { + value = forge.util.bytesFromIP(altName.ip); + if(value === null) { + var error = new Error( + 'Extension "ip" value is not a valid IPv4 or IPv6 address.'); + error.extension = e; + throw error; + } + } else if(altName.type === 8) { + // handle OID + if(altName.oid) { + value = asn1.oidToDer(asn1.oidToDer(altName.oid)); + } else { + // deprecated ... convert value to OID + value = asn1.oidToDer(value); + } + } + fullNameGeneralNames.value.push(asn1.create( + asn1.Class.CONTEXT_SPECIFIC, altName.type, false, + value)); + } + + // Add to the parent SEQUENCE + subSeq.value.push(asn1.create( + asn1.Class.CONTEXT_SPECIFIC, 0, true, [fullNameGeneralNames])); + seq.push(subSeq); + } + + // ensure value has been defined by now + if(typeof e.value === 'undefined') { + var error = new Error('Extension value not specified.'); + error.extension = e; + throw error; + } + + return e; +} + +/** + * Convert signature parameters object to ASN.1 + * + * @param {String} oid Signature algorithm OID + * @param params The signature parametrs object + * @return ASN.1 object representing signature parameters + */ +function _signatureParametersToAsn1(oid, params) { + switch(oid) { + case oids['RSASSA-PSS']: + var parts = []; + + if(params.hash.algorithmOid !== undefined) { + parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(params.hash.algorithmOid).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ]) + ])); + } + + if(params.mgf.algorithmOid !== undefined) { + parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(params.mgf.algorithmOid).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(params.mgf.hash.algorithmOid).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, '') + ]) + ]) + ])); + } + + if(params.saltLength !== undefined) { + parts.push(asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(params.saltLength).getBytes()) + ])); + } + + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, parts); + + default: + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.NULL, false, ''); + } +} + +/** + * Converts a certification request's attributes to an ASN.1 set of + * CRIAttributes. + * + * @param csr certification request. + * + * @return the ASN.1 set of CRIAttributes. + */ +function _CRIAttributesToAsn1(csr) { + // create an empty context-specific container + var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, []); + + // no attributes, return empty container + if(csr.attributes.length === 0) { + return rval; + } + + // each attribute has a sequence with a type and a set of values + var attrs = csr.attributes; + for(var i = 0; i < attrs.length; ++i) { + var attr = attrs[i]; + var value = attr.value; + + // reuse tag class for attribute value if available + var valueTagClass = asn1.Type.UTF8; + if('valueTagClass' in attr) { + valueTagClass = attr.valueTagClass; + } + if(valueTagClass === asn1.Type.UTF8) { + value = forge.util.encodeUtf8(value); + } + var valueConstructed = false; + if('valueConstructed' in attr) { + valueConstructed = attr.valueConstructed; + } + // FIXME: handle more encodings + + // create a RelativeDistinguishedName set + // each value in the set is an AttributeTypeAndValue first + // containing the type (an OID) and second the value + var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // AttributeType + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(attr.type).getBytes()), + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SET, true, [ + // AttributeValue + asn1.create( + asn1.Class.UNIVERSAL, valueTagClass, valueConstructed, value) + ]) + ]); + rval.value.push(seq); + } + + return rval; +} + +var jan_1_1950 = new Date('1950-01-01T00:00:00Z'); +var jan_1_2050 = new Date('2050-01-01T00:00:00Z'); + +/** + * Converts a Date object to ASN.1 + * Handles the different format before and after 1st January 2050 + * + * @param date date object. + * + * @return the ASN.1 object representing the date. + */ +function _dateToAsn1(date) { + if(date >= jan_1_1950 && date < jan_1_2050) { + return asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.UTCTIME, false, + asn1.dateToUtcTime(date)); + } else { + return asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.GENERALIZEDTIME, false, + asn1.dateToGeneralizedTime(date)); + } +} + +/** + * Gets the ASN.1 TBSCertificate part of an X.509v3 certificate. + * + * @param cert the certificate. + * + * @return the asn1 TBSCertificate. + */ +pki.getTBSCertificate = function(cert) { + // TBSCertificate + var notBefore = _dateToAsn1(cert.validity.notBefore); + var notAfter = _dateToAsn1(cert.validity.notAfter); + var tbs = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // version + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 0, true, [ + // integer + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(cert.version).getBytes()) + ]), + // serialNumber + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + forge.util.hexToBytes(cert.serialNumber)), + // signature + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(cert.siginfo.algorithmOid).getBytes()), + // parameters + _signatureParametersToAsn1( + cert.siginfo.algorithmOid, cert.siginfo.parameters) + ]), + // issuer + _dnToAsn1(cert.issuer), + // validity + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + notBefore, + notAfter + ]), + // subject + _dnToAsn1(cert.subject), + // SubjectPublicKeyInfo + pki.publicKeyToAsn1(cert.publicKey) + ]); + + if(cert.issuer.uniqueId) { + // issuerUniqueID (optional) + tbs.value.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 1, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, + // TODO: support arbitrary bit length ids + String.fromCharCode(0x00) + + cert.issuer.uniqueId + ) + ]) + ); + } + if(cert.subject.uniqueId) { + // subjectUniqueID (optional) + tbs.value.push( + asn1.create(asn1.Class.CONTEXT_SPECIFIC, 2, true, [ + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, + // TODO: support arbitrary bit length ids + String.fromCharCode(0x00) + + cert.subject.uniqueId + ) + ]) + ); + } + + if(cert.extensions.length > 0) { + // extensions (optional) + tbs.value.push(pki.certificateExtensionsToAsn1(cert.extensions)); + } + + return tbs; +}; + +/** + * Gets the ASN.1 CertificationRequestInfo part of a + * PKCS#10 CertificationRequest. + * + * @param csr the certification request. + * + * @return the asn1 CertificationRequestInfo. + */ +pki.getCertificationRequestInfo = function(csr) { + // CertificationRequestInfo + var cri = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // version + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.INTEGER, false, + asn1.integerToDer(csr.version).getBytes()), + // subject + _dnToAsn1(csr.subject), + // SubjectPublicKeyInfo + pki.publicKeyToAsn1(csr.publicKey), + // attributes + _CRIAttributesToAsn1(csr) + ]); + + return cri; +}; + +/** + * Converts a DistinguishedName (subject or issuer) to an ASN.1 object. + * + * @param dn the DistinguishedName. + * + * @return the asn1 representation of a DistinguishedName. + */ +pki.distinguishedNameToAsn1 = function(dn) { + return _dnToAsn1(dn); +}; + +/** + * Converts an X.509v3 RSA certificate to an ASN.1 object. + * + * @param cert the certificate. + * + * @return the asn1 representation of an X.509v3 RSA certificate. + */ +pki.certificateToAsn1 = function(cert) { + // prefer cached TBSCertificate over generating one + var tbsCertificate = cert.tbsCertificate || pki.getTBSCertificate(cert); + + // Certificate + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // TBSCertificate + tbsCertificate, + // AlgorithmIdentifier (signature algorithm) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(cert.signatureOid).getBytes()), + // parameters + _signatureParametersToAsn1(cert.signatureOid, cert.signatureParameters) + ]), + // SignatureValue + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, + String.fromCharCode(0x00) + cert.signature) + ]); +}; + +/** + * Converts X.509v3 certificate extensions to ASN.1. + * + * @param exts the extensions to convert. + * + * @return the extensions in ASN.1 format. + */ +pki.certificateExtensionsToAsn1 = function(exts) { + // create top-level extension container + var rval = asn1.create(asn1.Class.CONTEXT_SPECIFIC, 3, true, []); + + // create extension sequence (stores a sequence for each extension) + var seq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + rval.value.push(seq); + + for(var i = 0; i < exts.length; ++i) { + seq.value.push(pki.certificateExtensionToAsn1(exts[i])); + } + + return rval; +}; + +/** + * Converts a single certificate extension to ASN.1. + * + * @param ext the extension to convert. + * + * @return the extension in ASN.1 format. + */ +pki.certificateExtensionToAsn1 = function(ext) { + // create a sequence for each extension + var extseq = asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, []); + + // extnID (OID) + extseq.value.push(asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(ext.id).getBytes())); + + // critical defaults to false + if(ext.critical) { + // critical BOOLEAN DEFAULT FALSE + extseq.value.push(asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.BOOLEAN, false, + String.fromCharCode(0xFF))); + } + + var value = ext.value; + if(typeof ext.value !== 'string') { + // value is asn.1 + value = asn1.toDer(value).getBytes(); + } + + // extnValue (OCTET STRING) + extseq.value.push(asn1.create( + asn1.Class.UNIVERSAL, asn1.Type.OCTETSTRING, false, value)); + + return extseq; +}; + +/** + * Converts a PKCS#10 certification request to an ASN.1 object. + * + * @param csr the certification request. + * + * @return the asn1 representation of a certification request. + */ +pki.certificationRequestToAsn1 = function(csr) { + // prefer cached CertificationRequestInfo over generating one + var cri = csr.certificationRequestInfo || + pki.getCertificationRequestInfo(csr); + + // Certificate + return asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // CertificationRequestInfo + cri, + // AlgorithmIdentifier (signature algorithm) + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.SEQUENCE, true, [ + // algorithm + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.OID, false, + asn1.oidToDer(csr.signatureOid).getBytes()), + // parameters + _signatureParametersToAsn1(csr.signatureOid, csr.signatureParameters) + ]), + // signature + asn1.create(asn1.Class.UNIVERSAL, asn1.Type.BITSTRING, false, + String.fromCharCode(0x00) + csr.signature) + ]); +}; + +/** + * Creates a CA store. + * + * @param certs an optional array of certificate objects or PEM-formatted + * certificate strings to add to the CA store. + * + * @return the CA store. + */ +pki.createCaStore = function(certs) { + // create CA store + var caStore = { + // stored certificates + certs: {} + }; + + /** + * Gets the certificate that issued the passed certificate or its + * 'parent'. + * + * @param cert the certificate to get the parent for. + * + * @return the parent certificate or null if none was found. + */ + caStore.getIssuer = function(cert) { + var rval = getBySubject(cert.issuer); + + // see if there are multiple matches + /*if(forge.util.isArray(rval)) { + // TODO: resolve multiple matches by checking + // authorityKey/subjectKey/issuerUniqueID/other identifiers, etc. + // FIXME: or alternatively do authority key mapping + // if possible (X.509v1 certs can't work?) + throw new Error('Resolving multiple issuer matches not implemented yet.'); + }*/ + + return rval; + }; + + /** + * Adds a trusted certificate to the store. + * + * @param cert the certificate to add as a trusted certificate (either a + * pki.certificate object or a PEM-formatted certificate). + */ + caStore.addCertificate = function(cert) { + // convert from pem if necessary + if(typeof cert === 'string') { + cert = forge.pki.certificateFromPem(cert); + } + + ensureSubjectHasHash(cert.subject); + + if(!caStore.hasCertificate(cert)) { // avoid duplicate certificates in store + if(cert.subject.hash in caStore.certs) { + // subject hash already exists, append to array + var tmp = caStore.certs[cert.subject.hash]; + if(!forge.util.isArray(tmp)) { + tmp = [tmp]; + } + tmp.push(cert); + caStore.certs[cert.subject.hash] = tmp; + } else { + caStore.certs[cert.subject.hash] = cert; + } + } + }; + + /** + * Checks to see if the given certificate is in the store. + * + * @param cert the certificate to check (either a pki.certificate or a + * PEM-formatted certificate). + * + * @return true if the certificate is in the store, false if not. + */ + caStore.hasCertificate = function(cert) { + // convert from pem if necessary + if(typeof cert === 'string') { + cert = forge.pki.certificateFromPem(cert); + } + + var match = getBySubject(cert.subject); + if(!match) { + return false; + } + if(!forge.util.isArray(match)) { + match = [match]; + } + // compare DER-encoding of certificates + var der1 = asn1.toDer(pki.certificateToAsn1(cert)).getBytes(); + for(var i = 0; i < match.length; ++i) { + var der2 = asn1.toDer(pki.certificateToAsn1(match[i])).getBytes(); + if(der1 === der2) { + return true; + } + } + return false; + }; + + /** + * Lists all of the certificates kept in the store. + * + * @return an array of all of the pki.certificate objects in the store. + */ + caStore.listAllCertificates = function() { + var certList = []; + + for(var hash in caStore.certs) { + if(caStore.certs.hasOwnProperty(hash)) { + var value = caStore.certs[hash]; + if(!forge.util.isArray(value)) { + certList.push(value); + } else { + for(var i = 0; i < value.length; ++i) { + certList.push(value[i]); + } + } + } + } + + return certList; + }; + + /** + * Removes a certificate from the store. + * + * @param cert the certificate to remove (either a pki.certificate or a + * PEM-formatted certificate). + * + * @return the certificate that was removed or null if the certificate + * wasn't in store. + */ + caStore.removeCertificate = function(cert) { + var result; + + // convert from pem if necessary + if(typeof cert === 'string') { + cert = forge.pki.certificateFromPem(cert); + } + ensureSubjectHasHash(cert.subject); + if(!caStore.hasCertificate(cert)) { + return null; + } + + var match = getBySubject(cert.subject); + + if(!forge.util.isArray(match)) { + result = caStore.certs[cert.subject.hash]; + delete caStore.certs[cert.subject.hash]; + return result; + } + + // compare DER-encoding of certificates + var der1 = asn1.toDer(pki.certificateToAsn1(cert)).getBytes(); + for(var i = 0; i < match.length; ++i) { + var der2 = asn1.toDer(pki.certificateToAsn1(match[i])).getBytes(); + if(der1 === der2) { + result = match[i]; + match.splice(i, 1); + } + } + if(match.length === 0) { + delete caStore.certs[cert.subject.hash]; + } + + return result; + }; + + function getBySubject(subject) { + ensureSubjectHasHash(subject); + return caStore.certs[subject.hash] || null; + } + + function ensureSubjectHasHash(subject) { + // produce subject hash if it doesn't exist + if(!subject.hash) { + var md = forge.md.sha1.create(); + subject.attributes = pki.RDNAttributesAsArray(_dnToAsn1(subject), md); + subject.hash = md.digest().toHex(); + } + } + + // auto-add passed in certs + if(certs) { + // parse PEM-formatted certificates as necessary + for(var i = 0; i < certs.length; ++i) { + var cert = certs[i]; + caStore.addCertificate(cert); + } + } + + return caStore; +}; + +/** + * Certificate verification errors, based on TLS. + */ +pki.certificateError = { + bad_certificate: 'forge.pki.BadCertificate', + unsupported_certificate: 'forge.pki.UnsupportedCertificate', + certificate_revoked: 'forge.pki.CertificateRevoked', + certificate_expired: 'forge.pki.CertificateExpired', + certificate_unknown: 'forge.pki.CertificateUnknown', + unknown_ca: 'forge.pki.UnknownCertificateAuthority' +}; + +/** + * Verifies a certificate chain against the given Certificate Authority store + * with an optional custom verify callback. + * + * @param caStore a certificate store to verify against. + * @param chain the certificate chain to verify, with the root or highest + * authority at the end (an array of certificates). + * @param options a callback to be called for every certificate in the chain or + * an object with: + * verify a callback to be called for every certificate in the + * chain + * validityCheckDate the date against which the certificate + * validity period should be checked. Pass null to not check + * the validity period. By default, the current date is used. + * + * The verify callback has the following signature: + * + * verified - Set to true if certificate was verified, otherwise the + * pki.certificateError for why the certificate failed. + * depth - The current index in the chain, where 0 is the end point's cert. + * certs - The certificate chain, *NOTE* an empty chain indicates an anonymous + * end point. + * + * The function returns true on success and on failure either the appropriate + * pki.certificateError or an object with 'error' set to the appropriate + * pki.certificateError and 'message' set to a custom error message. + * + * @return true if successful, error thrown if not. + */ +pki.verifyCertificateChain = function(caStore, chain, options) { + /* From: RFC3280 - Internet X.509 Public Key Infrastructure Certificate + Section 6: Certification Path Validation + See inline parentheticals related to this particular implementation. + + The primary goal of path validation is to verify the binding between + a subject distinguished name or a subject alternative name and subject + public key, as represented in the end entity certificate, based on the + public key of the trust anchor. This requires obtaining a sequence of + certificates that support that binding. That sequence should be provided + in the passed 'chain'. The trust anchor should be in the given CA + store. The 'end entity' certificate is the certificate provided by the + end point (typically a server) and is the first in the chain. + + To meet this goal, the path validation process verifies, among other + things, that a prospective certification path (a sequence of n + certificates or a 'chain') satisfies the following conditions: + + (a) for all x in {1, ..., n-1}, the subject of certificate x is + the issuer of certificate x+1; + + (b) certificate 1 is issued by the trust anchor; + + (c) certificate n is the certificate to be validated; and + + (d) for all x in {1, ..., n}, the certificate was valid at the + time in question. + + Note that here 'n' is index 0 in the chain and 1 is the last certificate + in the chain and it must be signed by a certificate in the connection's + CA store. + + The path validation process also determines the set of certificate + policies that are valid for this path, based on the certificate policies + extension, policy mapping extension, policy constraints extension, and + inhibit any-policy extension. + + Note: Policy mapping extension not supported (Not Required). + + Note: If the certificate has an unsupported critical extension, then it + must be rejected. + + Note: A certificate is self-issued if the DNs that appear in the subject + and issuer fields are identical and are not empty. + + The path validation algorithm assumes the following seven inputs are + provided to the path processing logic. What this specific implementation + will use is provided parenthetically: + + (a) a prospective certification path of length n (the 'chain') + (b) the current date/time: ('now'). + (c) user-initial-policy-set: A set of certificate policy identifiers + naming the policies that are acceptable to the certificate user. + The user-initial-policy-set contains the special value any-policy + if the user is not concerned about certificate policy + (Not implemented. Any policy is accepted). + (d) trust anchor information, describing a CA that serves as a trust + anchor for the certification path. The trust anchor information + includes: + + (1) the trusted issuer name, + (2) the trusted public key algorithm, + (3) the trusted public key, and + (4) optionally, the trusted public key parameters associated + with the public key. + + (Trust anchors are provided via certificates in the CA store). + + The trust anchor information may be provided to the path processing + procedure in the form of a self-signed certificate. The trusted anchor + information is trusted because it was delivered to the path processing + procedure by some trustworthy out-of-band procedure. If the trusted + public key algorithm requires parameters, then the parameters are + provided along with the trusted public key (No parameters used in this + implementation). + + (e) initial-policy-mapping-inhibit, which indicates if policy mapping is + allowed in the certification path. + (Not implemented, no policy checking) + + (f) initial-explicit-policy, which indicates if the path must be valid + for at least one of the certificate policies in the user-initial- + policy-set. + (Not implemented, no policy checking) + + (g) initial-any-policy-inhibit, which indicates whether the + anyPolicy OID should be processed if it is included in a + certificate. + (Not implemented, so any policy is valid provided that it is + not marked as critical) */ + + /* Basic Path Processing: + + For each certificate in the 'chain', the following is checked: + + 1. The certificate validity period includes the current time. + 2. The certificate was signed by its parent (where the parent is either + the next in the chain or from the CA store). Allow processing to + continue to the next step if no parent is found but the certificate is + in the CA store. + 3. TODO: The certificate has not been revoked. + 4. The certificate issuer name matches the parent's subject name. + 5. TODO: If the certificate is self-issued and not the final certificate + in the chain, skip this step, otherwise verify that the subject name + is within one of the permitted subtrees of X.500 distinguished names + and that each of the alternative names in the subjectAltName extension + (critical or non-critical) is within one of the permitted subtrees for + that name type. + 6. TODO: If the certificate is self-issued and not the final certificate + in the chain, skip this step, otherwise verify that the subject name + is not within one of the excluded subtrees for X.500 distinguished + names and none of the subjectAltName extension names are excluded for + that name type. + 7. The other steps in the algorithm for basic path processing involve + handling the policy extension which is not presently supported in this + implementation. Instead, if a critical policy extension is found, the + certificate is rejected as not supported. + 8. If the certificate is not the first or if its the only certificate in + the chain (having no parent from the CA store or is self-signed) and it + has a critical key usage extension, verify that the keyCertSign bit is + set. If the key usage extension exists, verify that the basic + constraints extension exists. If the basic constraints extension exists, + verify that the cA flag is set. If pathLenConstraint is set, ensure that + the number of certificates that precede in the chain (come earlier + in the chain as implemented below), excluding the very first in the + chain (typically the end-entity one), isn't greater than the + pathLenConstraint. This constraint limits the number of intermediate + CAs that may appear below a CA before only end-entity certificates + may be issued. */ + + // if a verify callback is passed as the third parameter, package it within + // the options object. This is to support a legacy function signature that + // expected the verify callback as the third parameter. + if(typeof options === 'function') { + options = {verify: options}; + } + options = options || {}; + + // copy cert chain references to another array to protect against changes + // in verify callback + chain = chain.slice(0); + var certs = chain.slice(0); + + var validityCheckDate = options.validityCheckDate; + // if no validityCheckDate is specified, default to the current date. Make + // sure to maintain the value null because it indicates that the validity + // period should not be checked. + if(typeof validityCheckDate === 'undefined') { + validityCheckDate = new Date(); + } + + // verify each cert in the chain using its parent, where the parent + // is either the next in the chain or from the CA store + var first = true; + var error = null; + var depth = 0; + do { + var cert = chain.shift(); + var parent = null; + var selfSigned = false; + + if(validityCheckDate) { + // 1. check valid time + if(validityCheckDate < cert.validity.notBefore || + validityCheckDate > cert.validity.notAfter) { + error = { + message: 'Certificate is not valid yet or has expired.', + error: pki.certificateError.certificate_expired, + notBefore: cert.validity.notBefore, + notAfter: cert.validity.notAfter, + // TODO: we might want to reconsider renaming 'now' to + // 'validityCheckDate' should this API be changed in the future. + now: validityCheckDate + }; + } + } + + // 2. verify with parent from chain or CA store + if(error === null) { + parent = chain[0] || caStore.getIssuer(cert); + if(parent === null) { + // check for self-signed cert + if(cert.isIssuer(cert)) { + selfSigned = true; + parent = cert; + } + } + + if(parent) { + // FIXME: current CA store implementation might have multiple + // certificates where the issuer can't be determined from the + // certificate (happens rarely with, eg: old certificates) so normalize + // by always putting parents into an array + // TODO: there's may be an extreme degenerate case currently uncovered + // where an old intermediate certificate seems to have a matching parent + // but none of the parents actually verify ... but the intermediate + // is in the CA and it should pass this check; needs investigation + var parents = parent; + if(!forge.util.isArray(parents)) { + parents = [parents]; + } + + // try to verify with each possible parent (typically only one) + var verified = false; + while(!verified && parents.length > 0) { + parent = parents.shift(); + try { + verified = parent.verify(cert); + } catch(ex) { + // failure to verify, don't care why, try next one + } + } + + if(!verified) { + error = { + message: 'Certificate signature is invalid.', + error: pki.certificateError.bad_certificate + }; + } + } + + if(error === null && (!parent || selfSigned) && + !caStore.hasCertificate(cert)) { + // no parent issuer and certificate itself is not trusted + error = { + message: 'Certificate is not trusted.', + error: pki.certificateError.unknown_ca + }; + } + } + + // TODO: 3. check revoked + + // 4. check for matching issuer/subject + if(error === null && parent && !cert.isIssuer(parent)) { + // parent is not issuer + error = { + message: 'Certificate issuer is invalid.', + error: pki.certificateError.bad_certificate + }; + } + + // 5. TODO: check names with permitted names tree + + // 6. TODO: check names against excluded names tree + + // 7. check for unsupported critical extensions + if(error === null) { + // supported extensions + var se = { + keyUsage: true, + basicConstraints: true + }; + for(var i = 0; error === null && i < cert.extensions.length; ++i) { + var ext = cert.extensions[i]; + if(ext.critical && !(ext.name in se)) { + error = { + message: + 'Certificate has an unsupported critical extension.', + error: pki.certificateError.unsupported_certificate + }; + } + } + } + + // 8. check for CA if cert is not first or is the only certificate + // remaining in chain with no parent or is self-signed + if(error === null && + (!first || (chain.length === 0 && (!parent || selfSigned)))) { + // first check keyUsage extension and then basic constraints + var bcExt = cert.getExtension('basicConstraints'); + var keyUsageExt = cert.getExtension('keyUsage'); + if(keyUsageExt !== null) { + // keyCertSign must be true and there must be a basic + // constraints extension + if(!keyUsageExt.keyCertSign || bcExt === null) { + // bad certificate + error = { + message: + 'Certificate keyUsage or basicConstraints conflict ' + + 'or indicate that the certificate is not a CA. ' + + 'If the certificate is the only one in the chain or ' + + 'isn\'t the first then the certificate must be a ' + + 'valid CA.', + error: pki.certificateError.bad_certificate + }; + } + } + // basic constraints cA flag must be set + if(error === null && bcExt !== null && !bcExt.cA) { + // bad certificate + error = { + message: + 'Certificate basicConstraints indicates the certificate ' + + 'is not a CA.', + error: pki.certificateError.bad_certificate + }; + } + // if error is not null and keyUsage is available, then we know it + // has keyCertSign and there is a basic constraints extension too, + // which means we can check pathLenConstraint (if it exists) + if(error === null && keyUsageExt !== null && + 'pathLenConstraint' in bcExt) { + // pathLen is the maximum # of intermediate CA certs that can be + // found between the current certificate and the end-entity (depth 0) + // certificate; this number does not include the end-entity (depth 0, + // last in the chain) even if it happens to be a CA certificate itself + var pathLen = depth - 1; + if(pathLen > bcExt.pathLenConstraint) { + // pathLenConstraint violated, bad certificate + error = { + message: + 'Certificate basicConstraints pathLenConstraint violated.', + error: pki.certificateError.bad_certificate + }; + } + } + } + + // call application callback + var vfd = (error === null) ? true : error.error; + var ret = options.verify ? options.verify(vfd, depth, certs) : vfd; + if(ret === true) { + // clear any set error + error = null; + } else { + // if passed basic tests, set default message and alert + if(vfd === true) { + error = { + message: 'The application rejected the certificate.', + error: pki.certificateError.bad_certificate + }; + } + + // check for custom error info + if(ret || ret === 0) { + // set custom message and error + if(typeof ret === 'object' && !forge.util.isArray(ret)) { + if(ret.message) { + error.message = ret.message; + } + if(ret.error) { + error.error = ret.error; + } + } else if(typeof ret === 'string') { + // set custom error + error.error = ret; + } + } + + // throw error + throw error; + } + + // no longer first cert in chain + first = false; + ++depth; + } while(chain.length > 0); + + return true; +}; diff --git a/node_modules/node-forge/lib/xhr.js b/node_modules/node-forge/lib/xhr.js new file mode 100644 index 0000000..e493c3b --- /dev/null +++ b/node_modules/node-forge/lib/xhr.js @@ -0,0 +1,736 @@ +/** + * XmlHttpRequest implementation that uses TLS and flash SocketPool. + * + * @author Dave Longley + * + * Copyright (c) 2010-2013 Digital Bazaar, Inc. + */ +var forge = require('./forge'); +require('./socket'); +require('./http'); + +/* XHR API */ +var xhrApi = module.exports = forge.xhr = forge.xhr || {}; + +(function($) { + +// logging category +var cat = 'forge.xhr'; + +/* +XMLHttpRequest interface definition from: +http://www.w3.org/TR/XMLHttpRequest + +interface XMLHttpRequest { + // event handler + attribute EventListener onreadystatechange; + + // state + const unsigned short UNSENT = 0; + const unsigned short OPENED = 1; + const unsigned short HEADERS_RECEIVED = 2; + const unsigned short LOADING = 3; + const unsigned short DONE = 4; + readonly attribute unsigned short readyState; + + // request + void open(in DOMString method, in DOMString url); + void open(in DOMString method, in DOMString url, in boolean async); + void open(in DOMString method, in DOMString url, + in boolean async, in DOMString user); + void open(in DOMString method, in DOMString url, + in boolean async, in DOMString user, in DOMString password); + void setRequestHeader(in DOMString header, in DOMString value); + void send(); + void send(in DOMString data); + void send(in Document data); + void abort(); + + // response + DOMString getAllResponseHeaders(); + DOMString getResponseHeader(in DOMString header); + readonly attribute DOMString responseText; + readonly attribute Document responseXML; + readonly attribute unsigned short status; + readonly attribute DOMString statusText; +}; +*/ + +// readyStates +var UNSENT = 0; +var OPENED = 1; +var HEADERS_RECEIVED = 2; +var LOADING = 3; +var DONE = 4; + +// exceptions +var INVALID_STATE_ERR = 11; +var SYNTAX_ERR = 12; +var SECURITY_ERR = 18; +var NETWORK_ERR = 19; +var ABORT_ERR = 20; + +// private flash socket pool vars +var _sp = null; +var _policyPort = 0; +var _policyUrl = null; + +// default client (used if no special URL provided when creating an XHR) +var _client = null; + +// all clients including the default, key'd by full base url +// (multiple cross-domain http clients are permitted so there may be more +// than one client in this map) +// TODO: provide optional clean up API for non-default clients +var _clients = {}; + +// the default maximum number of concurrents connections per client +var _maxConnections = 10; + +var net = forge.net; +var http = forge.http; + +/** + * Initializes flash XHR support. + * + * @param options: + * url: the default base URL to connect to if xhr URLs are relative, + * ie: https://myserver.com. + * flashId: the dom ID of the flash SocketPool. + * policyPort: the port that provides the server's flash policy, 0 to use + * the flash default. + * policyUrl: the policy file URL to use instead of a policy port. + * msie: true if browser is internet explorer, false if not. + * connections: the maximum number of concurrent connections. + * caCerts: a list of PEM-formatted certificates to trust. + * cipherSuites: an optional array of cipher suites to use, + * see forge.tls.CipherSuites. + * verify: optional TLS certificate verify callback to use (see forge.tls + * for details). + * getCertificate: an optional callback used to get a client-side + * certificate (see forge.tls for details). + * getPrivateKey: an optional callback used to get a client-side private + * key (see forge.tls for details). + * getSignature: an optional callback used to get a client-side signature + * (see forge.tls for details). + * persistCookies: true to use persistent cookies via flash local storage, + * false to only keep cookies in javascript. + * primeTlsSockets: true to immediately connect TLS sockets on their + * creation so that they will cache TLS sessions for reuse. + */ +xhrApi.init = function(options) { + forge.log.debug(cat, 'initializing', options); + + // update default policy port and max connections + _policyPort = options.policyPort || _policyPort; + _policyUrl = options.policyUrl || _policyUrl; + _maxConnections = options.connections || _maxConnections; + + // create the flash socket pool + _sp = net.createSocketPool({ + flashId: options.flashId, + policyPort: _policyPort, + policyUrl: _policyUrl, + msie: options.msie || false + }); + + // create default http client + _client = http.createClient({ + url: options.url || ( + window.location.protocol + '//' + window.location.host), + socketPool: _sp, + policyPort: _policyPort, + policyUrl: _policyUrl, + connections: options.connections || _maxConnections, + caCerts: options.caCerts, + cipherSuites: options.cipherSuites, + persistCookies: options.persistCookies || true, + primeTlsSockets: options.primeTlsSockets || false, + verify: options.verify, + getCertificate: options.getCertificate, + getPrivateKey: options.getPrivateKey, + getSignature: options.getSignature + }); + _clients[_client.url.full] = _client; + + forge.log.debug(cat, 'ready'); +}; + +/** + * Called to clean up the clients and socket pool. + */ +xhrApi.cleanup = function() { + // destroy all clients + for(var key in _clients) { + _clients[key].destroy(); + } + _clients = {}; + _client = null; + + // destroy socket pool + _sp.destroy(); + _sp = null; +}; + +/** + * Sets a cookie. + * + * @param cookie the cookie with parameters: + * name: the name of the cookie. + * value: the value of the cookie. + * comment: an optional comment string. + * maxAge: the age of the cookie in seconds relative to created time. + * secure: true if the cookie must be sent over a secure protocol. + * httpOnly: true to restrict access to the cookie from javascript + * (inaffective since the cookies are stored in javascript). + * path: the path for the cookie. + * domain: optional domain the cookie belongs to (must start with dot). + * version: optional version of the cookie. + * created: creation time, in UTC seconds, of the cookie. + */ +xhrApi.setCookie = function(cookie) { + // default cookie expiration to never + cookie.maxAge = cookie.maxAge || -1; + + // if the cookie's domain is set, use the appropriate client + if(cookie.domain) { + // add the cookies to the applicable domains + for(var key in _clients) { + var client = _clients[key]; + if(http.withinCookieDomain(client.url, cookie) && + client.secure === cookie.secure) { + client.setCookie(cookie); + } + } + } else { + // use the default domain + // FIXME: should a null domain cookie be added to all clients? should + // this be an option? + _client.setCookie(cookie); + } +}; + +/** + * Gets a cookie. + * + * @param name the name of the cookie. + * @param path an optional path for the cookie (if there are multiple cookies + * with the same name but different paths). + * @param domain an optional domain for the cookie (if not using the default + * domain). + * + * @return the cookie, cookies (if multiple matches), or null if not found. + */ +xhrApi.getCookie = function(name, path, domain) { + var rval = null; + + if(domain) { + // get the cookies from the applicable domains + for(var key in _clients) { + var client = _clients[key]; + if(http.withinCookieDomain(client.url, domain)) { + var cookie = client.getCookie(name, path); + if(cookie !== null) { + if(rval === null) { + rval = cookie; + } else if(!forge.util.isArray(rval)) { + rval = [rval, cookie]; + } else { + rval.push(cookie); + } + } + } + } + } else { + // get cookie from default domain + rval = _client.getCookie(name, path); + } + + return rval; +}; + +/** + * Removes a cookie. + * + * @param name the name of the cookie. + * @param path an optional path for the cookie (if there are multiple cookies + * with the same name but different paths). + * @param domain an optional domain for the cookie (if not using the default + * domain). + * + * @return true if a cookie was removed, false if not. + */ +xhrApi.removeCookie = function(name, path, domain) { + var rval = false; + + if(domain) { + // remove the cookies from the applicable domains + for(var key in _clients) { + var client = _clients[key]; + if(http.withinCookieDomain(client.url, domain)) { + if(client.removeCookie(name, path)) { + rval = true; + } + } + } + } else { + // remove cookie from default domain + rval = _client.removeCookie(name, path); + } + + return rval; +}; + +/** + * Creates a new XmlHttpRequest. By default the base URL, flash policy port, + * etc, will be used. However, an XHR can be created to point at another + * cross-domain URL. + * + * @param options: + * logWarningOnError: If true and an HTTP error status code is received then + * log a warning, otherwise log a verbose message. + * verbose: If true be very verbose in the output including the response + * event and response body, otherwise only include status, timing, and + * data size. + * logError: a multi-var log function for warnings that takes the log + * category as the first var. + * logWarning: a multi-var log function for warnings that takes the log + * category as the first var. + * logDebug: a multi-var log function for warnings that takes the log + * category as the first var. + * logVerbose: a multi-var log function for warnings that takes the log + * category as the first var. + * url: the default base URL to connect to if xhr URLs are relative, + * eg: https://myserver.com, and note that the following options will be + * ignored if the URL is absent or the same as the default base URL. + * policyPort: the port that provides the server's flash policy, 0 to use + * the flash default. + * policyUrl: the policy file URL to use instead of a policy port. + * connections: the maximum number of concurrent connections. + * caCerts: a list of PEM-formatted certificates to trust. + * cipherSuites: an optional array of cipher suites to use, see + * forge.tls.CipherSuites. + * verify: optional TLS certificate verify callback to use (see forge.tls + * for details). + * getCertificate: an optional callback used to get a client-side + * certificate. + * getPrivateKey: an optional callback used to get a client-side private key. + * getSignature: an optional callback used to get a client-side signature. + * persistCookies: true to use persistent cookies via flash local storage, + * false to only keep cookies in javascript. + * primeTlsSockets: true to immediately connect TLS sockets on their + * creation so that they will cache TLS sessions for reuse. + * + * @return the XmlHttpRequest. + */ +xhrApi.create = function(options) { + // set option defaults + options = $.extend({ + logWarningOnError: true, + verbose: false, + logError: function() {}, + logWarning: function() {}, + logDebug: function() {}, + logVerbose: function() {}, + url: null + }, options || {}); + + // private xhr state + var _state = { + // the http client to use + client: null, + // request storage + request: null, + // response storage + response: null, + // asynchronous, true if doing asynchronous communication + asynchronous: true, + // sendFlag, true if send has been called + sendFlag: false, + // errorFlag, true if a network error occurred + errorFlag: false + }; + + // private log functions + var _log = { + error: options.logError || forge.log.error, + warning: options.logWarning || forge.log.warning, + debug: options.logDebug || forge.log.debug, + verbose: options.logVerbose || forge.log.verbose + }; + + // create public xhr interface + var xhr = { + // an EventListener + onreadystatechange: null, + // readonly, the current readyState + readyState: UNSENT, + // a string with the response entity-body + responseText: '', + // a Document for response entity-bodies that are XML + responseXML: null, + // readonly, returns the HTTP status code (i.e. 404) + status: 0, + // readonly, returns the HTTP status message (i.e. 'Not Found') + statusText: '' + }; + + // determine which http client to use + if(options.url === null) { + // use default + _state.client = _client; + } else { + var url = http.parseUrl(options.url); + if(!url) { + var error = new Error('Invalid url.'); + error.details = { + url: options.url + }; + } + + // find client + if(url.full in _clients) { + // client found + _state.client = _clients[url.full]; + } else { + // create client + _state.client = http.createClient({ + url: options.url, + socketPool: _sp, + policyPort: options.policyPort || _policyPort, + policyUrl: options.policyUrl || _policyUrl, + connections: options.connections || _maxConnections, + caCerts: options.caCerts, + cipherSuites: options.cipherSuites, + persistCookies: options.persistCookies || true, + primeTlsSockets: options.primeTlsSockets || false, + verify: options.verify, + getCertificate: options.getCertificate, + getPrivateKey: options.getPrivateKey, + getSignature: options.getSignature + }); + _clients[url.full] = _state.client; + } + } + + /** + * Opens the request. This method will create the HTTP request to send. + * + * @param method the HTTP method (i.e. 'GET'). + * @param url the relative url (the HTTP request path). + * @param async always true, ignored. + * @param user always null, ignored. + * @param password always null, ignored. + */ + xhr.open = function(method, url, async, user, password) { + // 1. validate Document if one is associated + // TODO: not implemented (not used yet) + + // 2. validate method token + // 3. change method to uppercase if it matches a known + // method (here we just require it to be uppercase, and + // we do not allow the standard methods) + // 4. disallow CONNECT, TRACE, or TRACK with a security error + switch(method) { + case 'DELETE': + case 'GET': + case 'HEAD': + case 'OPTIONS': + case 'PATCH': + case 'POST': + case 'PUT': + // valid method + break; + case 'CONNECT': + case 'TRACE': + case 'TRACK': + throw new Error('CONNECT, TRACE and TRACK methods are disallowed'); + default: + throw new Error('Invalid method: ' + method); + } + + // TODO: other validation steps in algorithm are not implemented + + // 19. set send flag to false + // set response body to null + // empty list of request headers + // set request method to given method + // set request URL + // set username, password + // set asychronous flag + _state.sendFlag = false; + xhr.responseText = ''; + xhr.responseXML = null; + + // custom: reset status and statusText + xhr.status = 0; + xhr.statusText = ''; + + // create the HTTP request + _state.request = http.createRequest({ + method: method, + path: url + }); + + // 20. set state to OPENED + xhr.readyState = OPENED; + + // 21. dispatch onreadystatechange + if(xhr.onreadystatechange) { + xhr.onreadystatechange(); + } + }; + + /** + * Adds an HTTP header field to the request. + * + * @param header the name of the header field. + * @param value the value of the header field. + */ + xhr.setRequestHeader = function(header, value) { + // 1. if state is not OPENED or send flag is true, raise exception + if(xhr.readyState != OPENED || _state.sendFlag) { + throw new Error('XHR not open or sending'); + } + + // TODO: other validation steps in spec aren't implemented + + // set header + _state.request.setField(header, value); + }; + + /** + * Sends the request and any associated data. + * + * @param data a string or Document object to send, null to send no data. + */ + xhr.send = function(data) { + // 1. if state is not OPENED or 2. send flag is true, raise + // an invalid state exception + if(xhr.readyState != OPENED || _state.sendFlag) { + throw new Error('XHR not open or sending'); + } + + // 3. ignore data if method is GET or HEAD + if(data && + _state.request.method !== 'GET' && + _state.request.method !== 'HEAD') { + // handle non-IE case + if(typeof(XMLSerializer) !== 'undefined') { + if(data instanceof Document) { + var xs = new XMLSerializer(); + _state.request.body = xs.serializeToString(data); + } else { + _state.request.body = data; + } + } else { + // poorly implemented IE case + if(typeof(data.xml) !== 'undefined') { + _state.request.body = data.xml; + } else { + _state.request.body = data; + } + } + } + + // 4. release storage mutex (not used) + + // 5. set error flag to false + _state.errorFlag = false; + + // 6. if asynchronous is true (must be in this implementation) + + // 6.1 set send flag to true + _state.sendFlag = true; + + // 6.2 dispatch onreadystatechange + if(xhr.onreadystatechange) { + xhr.onreadystatechange(); + } + + // create send options + var options = {}; + options.request = _state.request; + options.headerReady = function(e) { + // make cookies available for ease of use/iteration + xhr.cookies = _state.client.cookies; + + // TODO: update document.cookie with any cookies where the + // script's domain matches + + // headers received + xhr.readyState = HEADERS_RECEIVED; + xhr.status = e.response.code; + xhr.statusText = e.response.message; + _state.response = e.response; + if(xhr.onreadystatechange) { + xhr.onreadystatechange(); + } + if(!_state.response.aborted) { + // now loading body + xhr.readyState = LOADING; + if(xhr.onreadystatechange) { + xhr.onreadystatechange(); + } + } + }; + options.bodyReady = function(e) { + xhr.readyState = DONE; + var ct = e.response.getField('Content-Type'); + // Note: this null/undefined check is done outside because IE + // dies otherwise on a "'null' is null" error + if(ct) { + if(ct.indexOf('text/xml') === 0 || + ct.indexOf('application/xml') === 0 || + ct.indexOf('+xml') !== -1) { + try { + var doc = new ActiveXObject('MicrosoftXMLDOM'); + doc.async = false; + doc.loadXML(e.response.body); + xhr.responseXML = doc; + } catch(ex) { + var parser = new DOMParser(); + xhr.responseXML = parser.parseFromString(ex.body, 'text/xml'); + } + } + } + + var length = 0; + if(e.response.body !== null) { + xhr.responseText = e.response.body; + length = e.response.body.length; + } + // build logging output + var req = _state.request; + var output = + req.method + ' ' + req.path + ' ' + + xhr.status + ' ' + xhr.statusText + ' ' + + length + 'B ' + + (e.request.connectTime + e.request.time + e.response.time) + + 'ms'; + var lFunc; + if(options.verbose) { + lFunc = (xhr.status >= 400 && options.logWarningOnError) ? + _log.warning : _log.verbose; + lFunc(cat, output, + e, e.response.body ? '\n' + e.response.body : '\nNo content'); + } else { + lFunc = (xhr.status >= 400 && options.logWarningOnError) ? + _log.warning : _log.debug; + lFunc(cat, output); + } + if(xhr.onreadystatechange) { + xhr.onreadystatechange(); + } + }; + options.error = function(e) { + var req = _state.request; + _log.error(cat, req.method + ' ' + req.path, e); + + // 1. set response body to null + xhr.responseText = ''; + xhr.responseXML = null; + + // 2. set error flag to true (and reset status) + _state.errorFlag = true; + xhr.status = 0; + xhr.statusText = ''; + + // 3. set state to done + xhr.readyState = DONE; + + // 4. asyc flag is always true, so dispatch onreadystatechange + if(xhr.onreadystatechange) { + xhr.onreadystatechange(); + } + }; + + // 7. send request + _state.client.send(options); + }; + + /** + * Aborts the request. + */ + xhr.abort = function() { + // 1. abort send + // 2. stop network activity + _state.request.abort(); + + // 3. set response to null + xhr.responseText = ''; + xhr.responseXML = null; + + // 4. set error flag to true (and reset status) + _state.errorFlag = true; + xhr.status = 0; + xhr.statusText = ''; + + // 5. clear user headers + _state.request = null; + _state.response = null; + + // 6. if state is DONE or UNSENT, or if OPENED and send flag is false + if(xhr.readyState === DONE || xhr.readyState === UNSENT || + (xhr.readyState === OPENED && !_state.sendFlag)) { + // 7. set ready state to unsent + xhr.readyState = UNSENT; + } else { + // 6.1 set state to DONE + xhr.readyState = DONE; + + // 6.2 set send flag to false + _state.sendFlag = false; + + // 6.3 dispatch onreadystatechange + if(xhr.onreadystatechange) { + xhr.onreadystatechange(); + } + + // 7. set state to UNSENT + xhr.readyState = UNSENT; + } + }; + + /** + * Gets all response headers as a string. + * + * @return the HTTP-encoded response header fields. + */ + xhr.getAllResponseHeaders = function() { + var rval = ''; + if(_state.response !== null) { + var fields = _state.response.fields; + $.each(fields, function(name, array) { + $.each(array, function(i, value) { + rval += name + ': ' + value + '\r\n'; + }); + }); + } + return rval; + }; + + /** + * Gets a single header field value or, if there are multiple + * fields with the same name, a comma-separated list of header + * values. + * + * @return the header field value(s) or null. + */ + xhr.getResponseHeader = function(header) { + var rval = null; + if(_state.response !== null) { + if(header in _state.response.fields) { + rval = _state.response.fields[header]; + if(forge.util.isArray(rval)) { + rval = rval.join(); + } + } + } + return rval; + }; + + return xhr; +}; + +})(jQuery); diff --git a/node_modules/node-forge/package.json b/node_modules/node-forge/package.json new file mode 100644 index 0000000..953105f --- /dev/null +++ b/node_modules/node-forge/package.json @@ -0,0 +1,157 @@ +{ + "_from": "node-forge@^0.9.0", + "_id": "node-forge@0.9.1", + "_inBundle": false, + "_integrity": "sha512-G6RlQt5Sb4GMBzXvhfkeFmbqR6MzhtnT7VTHuLadjkii3rdYHNdw0m8zA4BTxVIh68FicCQ2NSUANpsqkr9jvQ==", + "_location": "/node-forge", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "node-forge@^0.9.0", + "name": "node-forge", + "escapedName": "node-forge", + "rawSpec": "^0.9.0", + "saveSpec": null, + "fetchSpec": "^0.9.0" + }, + "_requiredBy": [ + "/google-p12-pem" + ], + "_resolved": "https://registry.npmjs.org/node-forge/-/node-forge-0.9.1.tgz", + "_shasum": "775368e6846558ab6676858a4d8c6e8d16c677b5", + "_spec": "node-forge@^0.9.0", + "_where": "/Users/cday/Code/zendesk/fetch-build-from-gcb/node_modules/google-p12-pem", + "author": { + "name": "Digital Bazaar, Inc.", + "email": "support@digitalbazaar.com", + "url": "http://digitalbazaar.com/" + }, + "browser": { + "buffer": false, + "crypto": false, + "process": false + }, + "bugs": { + "url": "https://github.com/digitalbazaar/forge/issues", + "email": "support@digitalbazaar.com" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Dave Longley", + "email": "dlongley@digitalbazaar.com" + }, + { + "name": "David I. Lehn", + "email": "dlehn@digitalbazaar.com" + }, + { + "name": "Stefan Siegl", + "email": "stesie@brokenpipe.de" + }, + { + "name": "Christoph Dorn", + "email": "christoph@christophdorn.com" + } + ], + "deprecated": false, + "description": "JavaScript implementations of network transports, cryptography, ciphers, PKI, message digests, and various utilities.", + "devDependencies": { + "browserify": "^16.1.0", + "commander": "^2.20.0", + "cross-env": "^5.1.3", + "eslint": "^5.16.0", + "eslint-config-digitalbazaar": "^2.0.0", + "express": "^4.16.2", + "karma": "^3.1.4", + "karma-browserify": "^6.0.0", + "karma-chrome-launcher": "^2.2.0", + "karma-edge-launcher": "^0.4.2", + "karma-firefox-launcher": "^1.1.0", + "karma-ie-launcher": "^1.0.0", + "karma-mocha": "^1.3.0", + "karma-mocha-reporter": "^2.2.5", + "karma-safari-launcher": "^1.0.0", + "karma-sauce-launcher": "^1.2.0", + "karma-sourcemap-loader": "^0.3.7", + "karma-tap-reporter": "0.0.6", + "karma-webpack": "^3.0.5", + "mocha": "^5.2.0", + "mocha-lcov-reporter": "^1.2.0", + "nodejs-websocket": "^1.7.1", + "nyc": "^14.1.1", + "opts": "^1.2.2", + "webpack": "^3.11.0", + "worker-loader": "^2.0.0" + }, + "engines": { + "node": ">= 4.5.0" + }, + "files": [ + "lib/*.js", + "flash/swf/*.swf", + "dist/*.min.js", + "dist/*.min.js.map" + ], + "homepage": "https://github.com/digitalbazaar/forge", + "jspm": { + "format": "amd" + }, + "keywords": [ + "aes", + "asn", + "asn.1", + "cbc", + "crypto", + "cryptography", + "csr", + "des", + "gcm", + "hmac", + "http", + "https", + "md5", + "network", + "pkcs", + "pki", + "prng", + "rc2", + "rsa", + "sha1", + "sha256", + "sha384", + "sha512", + "ssh", + "tls", + "x.509", + "x509" + ], + "license": "(BSD-3-Clause OR GPL-2.0)", + "main": "lib/index.js", + "name": "node-forge", + "nyc": { + "exclude": [ + "tests" + ] + }, + "repository": { + "type": "git", + "url": "git+https://github.com/digitalbazaar/forge.git" + }, + "scripts": { + "build": "webpack", + "coverage": "rm -rf coverage && nyc --reporter=lcov --reporter=text-summary npm test", + "coverage-report": "nyc report", + "lint": "eslint *.js lib/*.js tests/*.js tests/**/*.js examples/*.js flash/*.js", + "prepublish": "npm run build", + "test": "cross-env NODE_ENV=test mocha -t 30000 -R ${REPORTER:-spec} tests/unit/index.js", + "test-build": "webpack --config webpack-tests.config.js", + "test-karma": "karma start", + "test-karma-sauce": "karma start karma-sauce.conf", + "test-server": "node tests/server.js", + "test-server-webid": "node tests/websockets/server-webid.js", + "test-server-ws": "node tests/websockets/server-ws.js" + }, + "version": "0.9.1" +} diff --git a/node_modules/safe-buffer/LICENSE b/node_modules/safe-buffer/LICENSE new file mode 100644 index 0000000..0c068ce --- /dev/null +++ b/node_modules/safe-buffer/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) Feross Aboukhadijeh + +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. diff --git a/node_modules/safe-buffer/README.md b/node_modules/safe-buffer/README.md new file mode 100644 index 0000000..356e351 --- /dev/null +++ b/node_modules/safe-buffer/README.md @@ -0,0 +1,586 @@ +# safe-buffer [![travis][travis-image]][travis-url] [![npm][npm-image]][npm-url] [![downloads][downloads-image]][downloads-url] [![javascript style guide][standard-image]][standard-url] + +[travis-image]: https://img.shields.io/travis/feross/safe-buffer/master.svg +[travis-url]: https://travis-ci.org/feross/safe-buffer +[npm-image]: https://img.shields.io/npm/v/safe-buffer.svg +[npm-url]: https://npmjs.org/package/safe-buffer +[downloads-image]: https://img.shields.io/npm/dm/safe-buffer.svg +[downloads-url]: https://npmjs.org/package/safe-buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +#### Safer Node.js Buffer API + +**Use the new Node.js Buffer APIs (`Buffer.from`, `Buffer.alloc`, +`Buffer.allocUnsafe`, `Buffer.allocUnsafeSlow`) in all versions of Node.js.** + +**Uses the built-in implementation when available.** + +## install + +``` +npm install safe-buffer +``` + +[Get supported safe-buffer with the Tidelift Subscription](https://tidelift.com/subscription/pkg/npm-safe-buffer?utm_source=npm-safe-buffer&utm_medium=referral&utm_campaign=readme) + +## usage + +The goal of this package is to provide a safe replacement for the node.js `Buffer`. + +It's a drop-in replacement for `Buffer`. You can use it by adding one `require` line to +the top of your node.js modules: + +```js +var Buffer = require('safe-buffer').Buffer + +// Existing buffer code will continue to work without issues: + +new Buffer('hey', 'utf8') +new Buffer([1, 2, 3], 'utf8') +new Buffer(obj) +new Buffer(16) // create an uninitialized buffer (potentially unsafe) + +// But you can use these new explicit APIs to make clear what you want: + +Buffer.from('hey', 'utf8') // convert from many types to a Buffer +Buffer.alloc(16) // create a zero-filled buffer (safe) +Buffer.allocUnsafe(16) // create an uninitialized buffer (potentially unsafe) +``` + +## api + +### Class Method: Buffer.from(array) + + +* `array` {Array} + +Allocates a new `Buffer` using an `array` of octets. + +```js +const buf = Buffer.from([0x62,0x75,0x66,0x66,0x65,0x72]); + // creates a new Buffer containing ASCII bytes + // ['b','u','f','f','e','r'] +``` + +A `TypeError` will be thrown if `array` is not an `Array`. + +### Class Method: Buffer.from(arrayBuffer[, byteOffset[, length]]) + + +* `arrayBuffer` {ArrayBuffer} The `.buffer` property of a `TypedArray` or + a `new ArrayBuffer()` +* `byteOffset` {Number} Default: `0` +* `length` {Number} Default: `arrayBuffer.length - byteOffset` + +When passed a reference to the `.buffer` property of a `TypedArray` instance, +the newly created `Buffer` will share the same allocated memory as the +TypedArray. + +```js +const arr = new Uint16Array(2); +arr[0] = 5000; +arr[1] = 4000; + +const buf = Buffer.from(arr.buffer); // shares the memory with arr; + +console.log(buf); + // Prints: + +// changing the TypedArray changes the Buffer also +arr[1] = 6000; + +console.log(buf); + // Prints: +``` + +The optional `byteOffset` and `length` arguments specify a memory range within +the `arrayBuffer` that will be shared by the `Buffer`. + +```js +const ab = new ArrayBuffer(10); +const buf = Buffer.from(ab, 0, 2); +console.log(buf.length); + // Prints: 2 +``` + +A `TypeError` will be thrown if `arrayBuffer` is not an `ArrayBuffer`. + +### Class Method: Buffer.from(buffer) + + +* `buffer` {Buffer} + +Copies the passed `buffer` data onto a new `Buffer` instance. + +```js +const buf1 = Buffer.from('buffer'); +const buf2 = Buffer.from(buf1); + +buf1[0] = 0x61; +console.log(buf1.toString()); + // 'auffer' +console.log(buf2.toString()); + // 'buffer' (copy is not changed) +``` + +A `TypeError` will be thrown if `buffer` is not a `Buffer`. + +### Class Method: Buffer.from(str[, encoding]) + + +* `str` {String} String to encode. +* `encoding` {String} Encoding to use, Default: `'utf8'` + +Creates a new `Buffer` containing the given JavaScript string `str`. If +provided, the `encoding` parameter identifies the character encoding. +If not provided, `encoding` defaults to `'utf8'`. + +```js +const buf1 = Buffer.from('this is a tést'); +console.log(buf1.toString()); + // prints: this is a tést +console.log(buf1.toString('ascii')); + // prints: this is a tC)st + +const buf2 = Buffer.from('7468697320697320612074c3a97374', 'hex'); +console.log(buf2.toString()); + // prints: this is a tést +``` + +A `TypeError` will be thrown if `str` is not a string. + +### Class Method: Buffer.alloc(size[, fill[, encoding]]) + + +* `size` {Number} +* `fill` {Value} Default: `undefined` +* `encoding` {String} Default: `utf8` + +Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the +`Buffer` will be *zero-filled*. + +```js +const buf = Buffer.alloc(5); +console.log(buf); + // +``` + +The `size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +If `fill` is specified, the allocated `Buffer` will be initialized by calling +`buf.fill(fill)`. See [`buf.fill()`][] for more information. + +```js +const buf = Buffer.alloc(5, 'a'); +console.log(buf); + // +``` + +If both `fill` and `encoding` are specified, the allocated `Buffer` will be +initialized by calling `buf.fill(fill, encoding)`. For example: + +```js +const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); +console.log(buf); + // +``` + +Calling `Buffer.alloc(size)` can be significantly slower than the alternative +`Buffer.allocUnsafe(size)` but ensures that the newly created `Buffer` instance +contents will *never contain sensitive data*. + +A `TypeError` will be thrown if `size` is not a number. + +### Class Method: Buffer.allocUnsafe(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* `Buffer` of `size` bytes. The `size` must +be less than or equal to the value of `require('buffer').kMaxLength` (on 64-bit +architectures, `kMaxLength` is `(2^31)-1`). Otherwise, a [`RangeError`][] is +thrown. A zero-length Buffer will be created if a `size` less than or equal to +0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +```js +const buf = Buffer.allocUnsafe(5); +console.log(buf); + // + // (octets will be different, every time) +buf.fill(0); +console.log(buf); + // +``` + +A `TypeError` will be thrown if `size` is not a number. + +Note that the `Buffer` module pre-allocates an internal `Buffer` instance of +size `Buffer.poolSize` that is used as a pool for the fast allocation of new +`Buffer` instances created using `Buffer.allocUnsafe(size)` (and the deprecated +`new Buffer(size)` constructor) only when `size` is less than or equal to +`Buffer.poolSize >> 1` (floor of `Buffer.poolSize` divided by two). The default +value of `Buffer.poolSize` is `8192` but can be modified. + +Use of this pre-allocated internal memory pool is a key difference between +calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. +Specifically, `Buffer.alloc(size, fill)` will *never* use the internal Buffer +pool, while `Buffer.allocUnsafe(size).fill(fill)` *will* use the internal +Buffer pool if `size` is less than or equal to half `Buffer.poolSize`. The +difference is subtle but can be important when an application requires the +additional performance that `Buffer.allocUnsafe(size)` provides. + +### Class Method: Buffer.allocUnsafeSlow(size) + + +* `size` {Number} + +Allocates a new *non-zero-filled* and non-pooled `Buffer` of `size` bytes. The +`size` must be less than or equal to the value of +`require('buffer').kMaxLength` (on 64-bit architectures, `kMaxLength` is +`(2^31)-1`). Otherwise, a [`RangeError`][] is thrown. A zero-length Buffer will +be created if a `size` less than or equal to 0 is specified. + +The underlying memory for `Buffer` instances created in this way is *not +initialized*. The contents of the newly created `Buffer` are unknown and +*may contain sensitive data*. Use [`buf.fill(0)`][] to initialize such +`Buffer` instances to zeroes. + +When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, +allocations under 4KB are, by default, sliced from a single pre-allocated +`Buffer`. This allows applications to avoid the garbage collection overhead of +creating many individually allocated Buffers. This approach improves both +performance and memory usage by eliminating the need to track and cleanup as +many `Persistent` objects. + +However, in the case where a developer may need to retain a small chunk of +memory from a pool for an indeterminate amount of time, it may be appropriate +to create an un-pooled Buffer instance using `Buffer.allocUnsafeSlow()` then +copy out the relevant bits. + +```js +// need to keep around a few small chunks of memory +const store = []; + +socket.on('readable', () => { + const data = socket.read(); + // allocate for retained data + const sb = Buffer.allocUnsafeSlow(10); + // copy the data into the new allocation + data.copy(sb, 0, 0, 10); + store.push(sb); +}); +``` + +Use of `Buffer.allocUnsafeSlow()` should be used only as a last resort *after* +a developer has observed undue memory retention in their applications. + +A `TypeError` will be thrown if `size` is not a number. + +### All the Rest + +The rest of the `Buffer` API is exactly the same as in node.js. +[See the docs](https://nodejs.org/api/buffer.html). + + +## Related links + +- [Node.js issue: Buffer(number) is unsafe](https://github.com/nodejs/node/issues/4660) +- [Node.js Enhancement Proposal: Buffer.from/Buffer.alloc/Buffer.zalloc/Buffer() soft-deprecate](https://github.com/nodejs/node-eps/pull/4) + +## Why is `Buffer` unsafe? + +Today, the node.js `Buffer` constructor is overloaded to handle many different argument +types like `String`, `Array`, `Object`, `TypedArrayView` (`Uint8Array`, etc.), +`ArrayBuffer`, and also `Number`. + +The API is optimized for convenience: you can throw any type at it, and it will try to do +what you want. + +Because the Buffer constructor is so powerful, you often see code like this: + +```js +// Convert UTF-8 strings to hex +function toHex (str) { + return new Buffer(str).toString('hex') +} +``` + +***But what happens if `toHex` is called with a `Number` argument?*** + +### Remote Memory Disclosure + +If an attacker can make your program call the `Buffer` constructor with a `Number` +argument, then they can make it allocate uninitialized memory from the node.js process. +This could potentially disclose TLS private keys, user data, or database passwords. + +When the `Buffer` constructor is passed a `Number` argument, it returns an +**UNINITIALIZED** block of memory of the specified `size`. When you create a `Buffer` like +this, you **MUST** overwrite the contents before returning it to the user. + +From the [node.js docs](https://nodejs.org/api/buffer.html#buffer_new_buffer_size): + +> `new Buffer(size)` +> +> - `size` Number +> +> The underlying memory for `Buffer` instances created in this way is not initialized. +> **The contents of a newly created `Buffer` are unknown and could contain sensitive +> data.** Use `buf.fill(0)` to initialize a Buffer to zeroes. + +(Emphasis our own.) + +Whenever the programmer intended to create an uninitialized `Buffer` you often see code +like this: + +```js +var buf = new Buffer(16) + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### Would this ever be a problem in real code? + +Yes. It's surprisingly common to forget to check the type of your variables in a +dynamically-typed language like JavaScript. + +Usually the consequences of assuming the wrong type is that your program crashes with an +uncaught exception. But the failure mode for forgetting to check the type of arguments to +the `Buffer` constructor is more catastrophic. + +Here's an example of a vulnerable service that takes a JSON payload and converts it to +hex: + +```js +// Take a JSON payload {str: "some string"} and convert it to hex +var server = http.createServer(function (req, res) { + var data = '' + req.setEncoding('utf8') + req.on('data', function (chunk) { + data += chunk + }) + req.on('end', function () { + var body = JSON.parse(data) + res.end(new Buffer(body.str).toString('hex')) + }) +}) + +server.listen(8080) +``` + +In this example, an http client just has to send: + +```json +{ + "str": 1000 +} +``` + +and it will get back 1,000 bytes of uninitialized memory from the server. + +This is a very serious bug. It's similar in severity to the +[the Heartbleed bug](http://heartbleed.com/) that allowed disclosure of OpenSSL process +memory by remote attackers. + + +### Which real-world packages were vulnerable? + +#### [`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht) + +[Mathias Buus](https://github.com/mafintosh) and I +([Feross Aboukhadijeh](http://feross.org/)) found this issue in one of our own packages, +[`bittorrent-dht`](https://www.npmjs.com/package/bittorrent-dht). The bug would allow +anyone on the internet to send a series of messages to a user of `bittorrent-dht` and get +them to reveal 20 bytes at a time of uninitialized memory from the node.js process. + +Here's +[the commit](https://github.com/feross/bittorrent-dht/commit/6c7da04025d5633699800a99ec3fbadf70ad35b8) +that fixed it. We released a new fixed version, created a +[Node Security Project disclosure](https://nodesecurity.io/advisories/68), and deprecated all +vulnerable versions on npm so users will get a warning to upgrade to a newer version. + +#### [`ws`](https://www.npmjs.com/package/ws) + +That got us wondering if there were other vulnerable packages. Sure enough, within a short +period of time, we found the same issue in [`ws`](https://www.npmjs.com/package/ws), the +most popular WebSocket implementation in node.js. + +If certain APIs were called with `Number` parameters instead of `String` or `Buffer` as +expected, then uninitialized server memory would be disclosed to the remote peer. + +These were the vulnerable methods: + +```js +socket.send(number) +socket.ping(number) +socket.pong(number) +``` + +Here's a vulnerable socket server with some echo functionality: + +```js +server.on('connection', function (socket) { + socket.on('message', function (message) { + message = JSON.parse(message) + if (message.type === 'echo') { + socket.send(message.data) // send back the user's message + } + }) +}) +``` + +`socket.send(number)` called on the server, will disclose server memory. + +Here's [the release](https://github.com/websockets/ws/releases/tag/1.0.1) where the issue +was fixed, with a more detailed explanation. Props to +[Arnout Kazemier](https://github.com/3rd-Eden) for the quick fix. Here's the +[Node Security Project disclosure](https://nodesecurity.io/advisories/67). + + +### What's the solution? + +It's important that node.js offers a fast way to get memory otherwise performance-critical +applications would needlessly get a lot slower. + +But we need a better way to *signal our intent* as programmers. **When we want +uninitialized memory, we should request it explicitly.** + +Sensitive functionality should not be packed into a developer-friendly API that loosely +accepts many different types. This type of API encourages the lazy practice of passing +variables in without checking the type very carefully. + +#### A new API: `Buffer.allocUnsafe(number)` + +The functionality of creating buffers with uninitialized memory should be part of another +API. We propose `Buffer.allocUnsafe(number)`. This way, it's not part of an API that +frequently gets user input of all sorts of different types passed into it. + +```js +var buf = Buffer.allocUnsafe(16) // careful, uninitialized memory! + +// Immediately overwrite the uninitialized buffer with data from another buffer +for (var i = 0; i < buf.length; i++) { + buf[i] = otherBuf[i] +} +``` + + +### How do we fix node.js core? + +We sent [a PR to node.js core](https://github.com/nodejs/node/pull/4514) (merged as +`semver-major`) which defends against one case: + +```js +var str = 16 +new Buffer(str, 'utf8') +``` + +In this situation, it's implied that the programmer intended the first argument to be a +string, since they passed an encoding as a second argument. Today, node.js will allocate +uninitialized memory in the case of `new Buffer(number, encoding)`, which is probably not +what the programmer intended. + +But this is only a partial solution, since if the programmer does `new Buffer(variable)` +(without an `encoding` parameter) there's no way to know what they intended. If `variable` +is sometimes a number, then uninitialized memory will sometimes be returned. + +### What's the real long-term fix? + +We could deprecate and remove `new Buffer(number)` and use `Buffer.allocUnsafe(number)` when +we need uninitialized memory. But that would break 1000s of packages. + +~~We believe the best solution is to:~~ + +~~1. Change `new Buffer(number)` to return safe, zeroed-out memory~~ + +~~2. Create a new API for creating uninitialized Buffers. We propose: `Buffer.allocUnsafe(number)`~~ + +#### Update + +We now support adding three new APIs: + +- `Buffer.from(value)` - convert from any type to a buffer +- `Buffer.alloc(size)` - create a zero-filled buffer +- `Buffer.allocUnsafe(size)` - create an uninitialized buffer with given size + +This solves the core problem that affected `ws` and `bittorrent-dht` which is +`Buffer(variable)` getting tricked into taking a number argument. + +This way, existing code continues working and the impact on the npm ecosystem will be +minimal. Over time, npm maintainers can migrate performance-critical code to use +`Buffer.allocUnsafe(number)` instead of `new Buffer(number)`. + + +### Conclusion + +We think there's a serious design issue with the `Buffer` API as it exists today. It +promotes insecure software by putting high-risk functionality into a convenient API +with friendly "developer ergonomics". + +This wasn't merely a theoretical exercise because we found the issue in some of the +most popular npm packages. + +Fortunately, there's an easy fix that can be applied today. Use `safe-buffer` in place of +`buffer`. + +```js +var Buffer = require('safe-buffer').Buffer +``` + +Eventually, we hope that node.js core can switch to this new, safer behavior. We believe +the impact on the ecosystem would be minimal since it's not a breaking change. +Well-maintained, popular packages would be updated to use `Buffer.alloc` quickly, while +older, insecure packages would magically become safe from this attack vector. + + +## links + +- [Node.js PR: buffer: throw if both length and enc are passed](https://github.com/nodejs/node/pull/4514) +- [Node Security Project disclosure for `ws`](https://nodesecurity.io/advisories/67) +- [Node Security Project disclosure for`bittorrent-dht`](https://nodesecurity.io/advisories/68) + + +## credit + +The original issues in `bittorrent-dht` +([disclosure](https://nodesecurity.io/advisories/68)) and +`ws` ([disclosure](https://nodesecurity.io/advisories/67)) were discovered by +[Mathias Buus](https://github.com/mafintosh) and +[Feross Aboukhadijeh](http://feross.org/). + +Thanks to [Adam Baldwin](https://github.com/evilpacket) for helping disclose these issues +and for his work running the [Node Security Project](https://nodesecurity.io/). + +Thanks to [John Hiesey](https://github.com/jhiesey) for proofreading this README and +auditing the code. + + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org) diff --git a/node_modules/safe-buffer/index.d.ts b/node_modules/safe-buffer/index.d.ts new file mode 100644 index 0000000..e9fed80 --- /dev/null +++ b/node_modules/safe-buffer/index.d.ts @@ -0,0 +1,187 @@ +declare module "safe-buffer" { + export class Buffer { + length: number + write(string: string, offset?: number, length?: number, encoding?: string): number; + toString(encoding?: string, start?: number, end?: number): string; + toJSON(): { type: 'Buffer', data: any[] }; + equals(otherBuffer: Buffer): boolean; + compare(otherBuffer: Buffer, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): number; + copy(targetBuffer: Buffer, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + slice(start?: number, end?: number): Buffer; + writeUIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeUIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntLE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + writeIntBE(value: number, offset: number, byteLength: number, noAssert?: boolean): number; + readUIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readUIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntLE(offset: number, byteLength: number, noAssert?: boolean): number; + readIntBE(offset: number, byteLength: number, noAssert?: boolean): number; + readUInt8(offset: number, noAssert?: boolean): number; + readUInt16LE(offset: number, noAssert?: boolean): number; + readUInt16BE(offset: number, noAssert?: boolean): number; + readUInt32LE(offset: number, noAssert?: boolean): number; + readUInt32BE(offset: number, noAssert?: boolean): number; + readInt8(offset: number, noAssert?: boolean): number; + readInt16LE(offset: number, noAssert?: boolean): number; + readInt16BE(offset: number, noAssert?: boolean): number; + readInt32LE(offset: number, noAssert?: boolean): number; + readInt32BE(offset: number, noAssert?: boolean): number; + readFloatLE(offset: number, noAssert?: boolean): number; + readFloatBE(offset: number, noAssert?: boolean): number; + readDoubleLE(offset: number, noAssert?: boolean): number; + readDoubleBE(offset: number, noAssert?: boolean): number; + swap16(): Buffer; + swap32(): Buffer; + swap64(): Buffer; + writeUInt8(value: number, offset: number, noAssert?: boolean): number; + writeUInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeUInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeInt8(value: number, offset: number, noAssert?: boolean): number; + writeInt16LE(value: number, offset: number, noAssert?: boolean): number; + writeInt16BE(value: number, offset: number, noAssert?: boolean): number; + writeInt32LE(value: number, offset: number, noAssert?: boolean): number; + writeInt32BE(value: number, offset: number, noAssert?: boolean): number; + writeFloatLE(value: number, offset: number, noAssert?: boolean): number; + writeFloatBE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleLE(value: number, offset: number, noAssert?: boolean): number; + writeDoubleBE(value: number, offset: number, noAssert?: boolean): number; + fill(value: any, offset?: number, end?: number): this; + indexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + lastIndexOf(value: string | number | Buffer, byteOffset?: number, encoding?: string): number; + includes(value: string | number | Buffer, byteOffset?: number, encoding?: string): boolean; + + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + */ + constructor (str: string, encoding?: string); + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + */ + constructor (size: number); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: Uint8Array); + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}. + * + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + */ + constructor (arrayBuffer: ArrayBuffer); + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + */ + constructor (array: any[]); + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + */ + constructor (buffer: Buffer); + prototype: Buffer; + /** + * Allocates a new Buffer using an {array} of octets. + * + * @param array + */ + static from(array: any[]): Buffer; + /** + * When passed a reference to the .buffer property of a TypedArray instance, + * the newly created Buffer will share the same allocated memory as the TypedArray. + * The optional {byteOffset} and {length} arguments specify a memory range + * within the {arrayBuffer} that will be shared by the Buffer. + * + * @param arrayBuffer The .buffer property of a TypedArray or a new ArrayBuffer() + * @param byteOffset + * @param length + */ + static from(arrayBuffer: ArrayBuffer, byteOffset?: number, length?: number): Buffer; + /** + * Copies the passed {buffer} data onto a new Buffer instance. + * + * @param buffer + */ + static from(buffer: Buffer): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + * + * @param str + */ + static from(str: string, encoding?: string): Buffer; + /** + * Returns true if {obj} is a Buffer + * + * @param obj object to test. + */ + static isBuffer(obj: any): obj is Buffer; + /** + * Returns true if {encoding} is a valid encoding argument. + * Valid string encodings in Node 0.12: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'binary'(deprecated)|'hex' + * + * @param encoding string to test. + */ + static isEncoding(encoding: string): boolean; + /** + * Gives the actual byte length of a string. encoding defaults to 'utf8'. + * This is not the same as String.prototype.length since that returns the number of characters in a string. + * + * @param string string to test. + * @param encoding encoding used to evaluate (defaults to 'utf8') + */ + static byteLength(string: string, encoding?: string): number; + /** + * Returns a buffer which is the result of concatenating all the buffers in the list together. + * + * If the list has no items, or if the totalLength is 0, then it returns a zero-length buffer. + * If the list has exactly one item, then the first item of the list is returned. + * If the list has more than one item, then a new Buffer is created. + * + * @param list An array of Buffer objects to concatenate + * @param totalLength Total length of the buffers when concatenated. + * If totalLength is not provided, it is read from the buffers in the list. However, this adds an additional loop to the function, so it is faster to provide the length explicitly. + */ + static concat(list: Buffer[], totalLength?: number): Buffer; + /** + * The same as buf1.compare(buf2). + */ + static compare(buf1: Buffer, buf2: Buffer): number; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @param fill if specified, buffer will be initialized by calling buf.fill(fill). + * If parameter is omitted, buffer will be filled with zeros. + * @param encoding encoding used for call to buf.fill while initalizing + */ + static alloc(size: number, fill?: string | Buffer | number, encoding?: string): Buffer; + /** + * Allocates a new buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafe(size: number): Buffer; + /** + * Allocates a new non-pooled buffer of {size} octets, leaving memory not initialized, so the contents + * of the newly created Buffer are unknown and may contain sensitive data. + * + * @param size count of octets to allocate + */ + static allocUnsafeSlow(size: number): Buffer; + } +} \ No newline at end of file diff --git a/node_modules/safe-buffer/index.js b/node_modules/safe-buffer/index.js new file mode 100644 index 0000000..054c8d3 --- /dev/null +++ b/node_modules/safe-buffer/index.js @@ -0,0 +1,64 @@ +/* eslint-disable node/no-deprecated-api */ +var buffer = require('buffer') +var Buffer = buffer.Buffer + +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} + +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.prototype = Object.create(Buffer.prototype) + +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} + +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} diff --git a/node_modules/safe-buffer/package.json b/node_modules/safe-buffer/package.json new file mode 100644 index 0000000..01cee6d --- /dev/null +++ b/node_modules/safe-buffer/package.json @@ -0,0 +1,64 @@ +{ + "_from": "safe-buffer@^5.0.1", + "_id": "safe-buffer@5.2.0", + "_inBundle": false, + "_integrity": "sha512-fZEwUGbVl7kouZs1jCdMLdt95hdIv0ZeHg6L7qPeciMZhZ+/gdesW4wgTARkrFWEpspjEATAzUGPG8N2jJiwbg==", + "_location": "/safe-buffer", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "safe-buffer@^5.0.1", + "name": "safe-buffer", + "escapedName": "safe-buffer", + "rawSpec": "^5.0.1", + "saveSpec": null, + "fetchSpec": "^5.0.1" + }, + "_requiredBy": [ + "/ecdsa-sig-formatter", + "/jwa", + "/jws" + ], + "_resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.0.tgz", + "_shasum": "b74daec49b1148f88c64b68d49b1e815c1f2f519", + "_spec": "safe-buffer@^5.0.1", + "_where": "/Users/cday/Code/zendesk/fetch-build-from-gcb/node_modules/ecdsa-sig-formatter", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "http://feross.org" + }, + "bugs": { + "url": "https://github.com/feross/safe-buffer/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Safer Node.js Buffer API", + "devDependencies": { + "standard": "*", + "tape": "^4.0.0" + }, + "homepage": "https://github.com/feross/safe-buffer", + "keywords": [ + "buffer", + "buffer allocate", + "node security", + "safe", + "safe-buffer", + "security", + "uninitialized" + ], + "license": "MIT", + "main": "index.js", + "name": "safe-buffer", + "repository": { + "type": "git", + "url": "git://github.com/feross/safe-buffer.git" + }, + "scripts": { + "test": "standard && tape test/*.js" + }, + "types": "index.d.ts", + "version": "5.2.0" +} diff --git a/node_modules/yallist/LICENSE b/node_modules/yallist/LICENSE new file mode 100644 index 0000000..19129e3 --- /dev/null +++ b/node_modules/yallist/LICENSE @@ -0,0 +1,15 @@ +The ISC License + +Copyright (c) Isaac Z. Schlueter and Contributors + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted, provided that the above +copyright notice and this permission notice appear in all copies. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR +IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. diff --git a/node_modules/yallist/README.md b/node_modules/yallist/README.md new file mode 100644 index 0000000..f586101 --- /dev/null +++ b/node_modules/yallist/README.md @@ -0,0 +1,204 @@ +# yallist + +Yet Another Linked List + +There are many doubly-linked list implementations like it, but this +one is mine. + +For when an array would be too big, and a Map can't be iterated in +reverse order. + + +[![Build Status](https://travis-ci.org/isaacs/yallist.svg?branch=master)](https://travis-ci.org/isaacs/yallist) [![Coverage Status](https://coveralls.io/repos/isaacs/yallist/badge.svg?service=github)](https://coveralls.io/github/isaacs/yallist) + +## basic usage + +```javascript +var yallist = require('yallist') +var myList = yallist.create([1, 2, 3]) +myList.push('foo') +myList.unshift('bar') +// of course pop() and shift() are there, too +console.log(myList.toArray()) // ['bar', 1, 2, 3, 'foo'] +myList.forEach(function (k) { + // walk the list head to tail +}) +myList.forEachReverse(function (k, index, list) { + // walk the list tail to head +}) +var myDoubledList = myList.map(function (k) { + return k + k +}) +// now myDoubledList contains ['barbar', 2, 4, 6, 'foofoo'] +// mapReverse is also a thing +var myDoubledListReverse = myList.mapReverse(function (k) { + return k + k +}) // ['foofoo', 6, 4, 2, 'barbar'] + +var reduced = myList.reduce(function (set, entry) { + set += entry + return set +}, 'start') +console.log(reduced) // 'startfoo123bar' +``` + +## api + +The whole API is considered "public". + +Functions with the same name as an Array method work more or less the +same way. + +There's reverse versions of most things because that's the point. + +### Yallist + +Default export, the class that holds and manages a list. + +Call it with either a forEach-able (like an array) or a set of +arguments, to initialize the list. + +The Array-ish methods all act like you'd expect. No magic length, +though, so if you change that it won't automatically prune or add +empty spots. + +### Yallist.create(..) + +Alias for Yallist function. Some people like factories. + +#### yallist.head + +The first node in the list + +#### yallist.tail + +The last node in the list + +#### yallist.length + +The number of nodes in the list. (Change this at your peril. It is +not magic like Array length.) + +#### yallist.toArray() + +Convert the list to an array. + +#### yallist.forEach(fn, [thisp]) + +Call a function on each item in the list. + +#### yallist.forEachReverse(fn, [thisp]) + +Call a function on each item in the list, in reverse order. + +#### yallist.get(n) + +Get the data at position `n` in the list. If you use this a lot, +probably better off just using an Array. + +#### yallist.getReverse(n) + +Get the data at position `n`, counting from the tail. + +#### yallist.map(fn, thisp) + +Create a new Yallist with the result of calling the function on each +item. + +#### yallist.mapReverse(fn, thisp) + +Same as `map`, but in reverse. + +#### yallist.pop() + +Get the data from the list tail, and remove the tail from the list. + +#### yallist.push(item, ...) + +Insert one or more items to the tail of the list. + +#### yallist.reduce(fn, initialValue) + +Like Array.reduce. + +#### yallist.reduceReverse + +Like Array.reduce, but in reverse. + +#### yallist.reverse + +Reverse the list in place. + +#### yallist.shift() + +Get the data from the list head, and remove the head from the list. + +#### yallist.slice([from], [to]) + +Just like Array.slice, but returns a new Yallist. + +#### yallist.sliceReverse([from], [to]) + +Just like yallist.slice, but the result is returned in reverse. + +#### yallist.toArray() + +Create an array representation of the list. + +#### yallist.toArrayReverse() + +Create a reversed array representation of the list. + +#### yallist.unshift(item, ...) + +Insert one or more items to the head of the list. + +#### yallist.unshiftNode(node) + +Move a Node object to the front of the list. (That is, pull it out of +wherever it lives, and make it the new head.) + +If the node belongs to a different list, then that list will remove it +first. + +#### yallist.pushNode(node) + +Move a Node object to the end of the list. (That is, pull it out of +wherever it lives, and make it the new tail.) + +If the node belongs to a list already, then that list will remove it +first. + +#### yallist.removeNode(node) + +Remove a node from the list, preserving referential integrity of head +and tail and other nodes. + +Will throw an error if you try to have a list remove a node that +doesn't belong to it. + +### Yallist.Node + +The class that holds the data and is actually the list. + +Call with `var n = new Node(value, previousNode, nextNode)` + +Note that if you do direct operations on Nodes themselves, it's very +easy to get into weird states where the list is broken. Be careful :) + +#### node.next + +The next node in the list. + +#### node.prev + +The previous node in the list. + +#### node.value + +The data the node contains. + +#### node.list + +The list to which this node belongs. (Null if it does not belong to +any list.) diff --git a/node_modules/yallist/iterator.js b/node_modules/yallist/iterator.js new file mode 100644 index 0000000..d41c97a --- /dev/null +++ b/node_modules/yallist/iterator.js @@ -0,0 +1,8 @@ +'use strict' +module.exports = function (Yallist) { + Yallist.prototype[Symbol.iterator] = function* () { + for (let walker = this.head; walker; walker = walker.next) { + yield walker.value + } + } +} diff --git a/node_modules/yallist/package.json b/node_modules/yallist/package.json new file mode 100644 index 0000000..eb890e6 --- /dev/null +++ b/node_modules/yallist/package.json @@ -0,0 +1,62 @@ +{ + "_from": "yallist@^3.0.2", + "_id": "yallist@3.1.1", + "_inBundle": false, + "_integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "_location": "/yallist", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "yallist@^3.0.2", + "name": "yallist", + "escapedName": "yallist", + "rawSpec": "^3.0.2", + "saveSpec": null, + "fetchSpec": "^3.0.2" + }, + "_requiredBy": [ + "/lru-cache" + ], + "_resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "_shasum": "dbb7daf9bfd8bac9ab45ebf602b8cbad0d5d08fd", + "_spec": "yallist@^3.0.2", + "_where": "/Users/cday/Code/zendesk/fetch-build-from-gcb/node_modules/lru-cache", + "author": { + "name": "Isaac Z. Schlueter", + "email": "i@izs.me", + "url": "http://blog.izs.me/" + }, + "bugs": { + "url": "https://github.com/isaacs/yallist/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "Yet Another Linked List", + "devDependencies": { + "tap": "^12.1.0" + }, + "directories": { + "test": "test" + }, + "files": [ + "yallist.js", + "iterator.js" + ], + "homepage": "https://github.com/isaacs/yallist#readme", + "license": "ISC", + "main": "yallist.js", + "name": "yallist", + "repository": { + "type": "git", + "url": "git+https://github.com/isaacs/yallist.git" + }, + "scripts": { + "postpublish": "git push origin --all; git push origin --tags", + "postversion": "npm publish", + "preversion": "npm test", + "test": "tap test/*.js --100" + }, + "version": "3.1.1" +} diff --git a/node_modules/yallist/yallist.js b/node_modules/yallist/yallist.js new file mode 100644 index 0000000..ed4e730 --- /dev/null +++ b/node_modules/yallist/yallist.js @@ -0,0 +1,426 @@ +'use strict' +module.exports = Yallist + +Yallist.Node = Node +Yallist.create = Yallist + +function Yallist (list) { + var self = this + if (!(self instanceof Yallist)) { + self = new Yallist() + } + + self.tail = null + self.head = null + self.length = 0 + + if (list && typeof list.forEach === 'function') { + list.forEach(function (item) { + self.push(item) + }) + } else if (arguments.length > 0) { + for (var i = 0, l = arguments.length; i < l; i++) { + self.push(arguments[i]) + } + } + + return self +} + +Yallist.prototype.removeNode = function (node) { + if (node.list !== this) { + throw new Error('removing node which does not belong to this list') + } + + var next = node.next + var prev = node.prev + + if (next) { + next.prev = prev + } + + if (prev) { + prev.next = next + } + + if (node === this.head) { + this.head = next + } + if (node === this.tail) { + this.tail = prev + } + + node.list.length-- + node.next = null + node.prev = null + node.list = null + + return next +} + +Yallist.prototype.unshiftNode = function (node) { + if (node === this.head) { + return + } + + if (node.list) { + node.list.removeNode(node) + } + + var head = this.head + node.list = this + node.next = head + if (head) { + head.prev = node + } + + this.head = node + if (!this.tail) { + this.tail = node + } + this.length++ +} + +Yallist.prototype.pushNode = function (node) { + if (node === this.tail) { + return + } + + if (node.list) { + node.list.removeNode(node) + } + + var tail = this.tail + node.list = this + node.prev = tail + if (tail) { + tail.next = node + } + + this.tail = node + if (!this.head) { + this.head = node + } + this.length++ +} + +Yallist.prototype.push = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + push(this, arguments[i]) + } + return this.length +} + +Yallist.prototype.unshift = function () { + for (var i = 0, l = arguments.length; i < l; i++) { + unshift(this, arguments[i]) + } + return this.length +} + +Yallist.prototype.pop = function () { + if (!this.tail) { + return undefined + } + + var res = this.tail.value + this.tail = this.tail.prev + if (this.tail) { + this.tail.next = null + } else { + this.head = null + } + this.length-- + return res +} + +Yallist.prototype.shift = function () { + if (!this.head) { + return undefined + } + + var res = this.head.value + this.head = this.head.next + if (this.head) { + this.head.prev = null + } else { + this.tail = null + } + this.length-- + return res +} + +Yallist.prototype.forEach = function (fn, thisp) { + thisp = thisp || this + for (var walker = this.head, i = 0; walker !== null; i++) { + fn.call(thisp, walker.value, i, this) + walker = walker.next + } +} + +Yallist.prototype.forEachReverse = function (fn, thisp) { + thisp = thisp || this + for (var walker = this.tail, i = this.length - 1; walker !== null; i--) { + fn.call(thisp, walker.value, i, this) + walker = walker.prev + } +} + +Yallist.prototype.get = function (n) { + for (var i = 0, walker = this.head; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.next + } + if (i === n && walker !== null) { + return walker.value + } +} + +Yallist.prototype.getReverse = function (n) { + for (var i = 0, walker = this.tail; walker !== null && i < n; i++) { + // abort out of the list early if we hit a cycle + walker = walker.prev + } + if (i === n && walker !== null) { + return walker.value + } +} + +Yallist.prototype.map = function (fn, thisp) { + thisp = thisp || this + var res = new Yallist() + for (var walker = this.head; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)) + walker = walker.next + } + return res +} + +Yallist.prototype.mapReverse = function (fn, thisp) { + thisp = thisp || this + var res = new Yallist() + for (var walker = this.tail; walker !== null;) { + res.push(fn.call(thisp, walker.value, this)) + walker = walker.prev + } + return res +} + +Yallist.prototype.reduce = function (fn, initial) { + var acc + var walker = this.head + if (arguments.length > 1) { + acc = initial + } else if (this.head) { + walker = this.head.next + acc = this.head.value + } else { + throw new TypeError('Reduce of empty list with no initial value') + } + + for (var i = 0; walker !== null; i++) { + acc = fn(acc, walker.value, i) + walker = walker.next + } + + return acc +} + +Yallist.prototype.reduceReverse = function (fn, initial) { + var acc + var walker = this.tail + if (arguments.length > 1) { + acc = initial + } else if (this.tail) { + walker = this.tail.prev + acc = this.tail.value + } else { + throw new TypeError('Reduce of empty list with no initial value') + } + + for (var i = this.length - 1; walker !== null; i--) { + acc = fn(acc, walker.value, i) + walker = walker.prev + } + + return acc +} + +Yallist.prototype.toArray = function () { + var arr = new Array(this.length) + for (var i = 0, walker = this.head; walker !== null; i++) { + arr[i] = walker.value + walker = walker.next + } + return arr +} + +Yallist.prototype.toArrayReverse = function () { + var arr = new Array(this.length) + for (var i = 0, walker = this.tail; walker !== null; i++) { + arr[i] = walker.value + walker = walker.prev + } + return arr +} + +Yallist.prototype.slice = function (from, to) { + to = to || this.length + if (to < 0) { + to += this.length + } + from = from || 0 + if (from < 0) { + from += this.length + } + var ret = new Yallist() + if (to < from || to < 0) { + return ret + } + if (from < 0) { + from = 0 + } + if (to > this.length) { + to = this.length + } + for (var i = 0, walker = this.head; walker !== null && i < from; i++) { + walker = walker.next + } + for (; walker !== null && i < to; i++, walker = walker.next) { + ret.push(walker.value) + } + return ret +} + +Yallist.prototype.sliceReverse = function (from, to) { + to = to || this.length + if (to < 0) { + to += this.length + } + from = from || 0 + if (from < 0) { + from += this.length + } + var ret = new Yallist() + if (to < from || to < 0) { + return ret + } + if (from < 0) { + from = 0 + } + if (to > this.length) { + to = this.length + } + for (var i = this.length, walker = this.tail; walker !== null && i > to; i--) { + walker = walker.prev + } + for (; walker !== null && i > from; i--, walker = walker.prev) { + ret.push(walker.value) + } + return ret +} + +Yallist.prototype.splice = function (start, deleteCount /*, ...nodes */) { + if (start > this.length) { + start = this.length - 1 + } + if (start < 0) { + start = this.length + start; + } + + for (var i = 0, walker = this.head; walker !== null && i < start; i++) { + walker = walker.next + } + + var ret = [] + for (var i = 0; walker && i < deleteCount; i++) { + ret.push(walker.value) + walker = this.removeNode(walker) + } + if (walker === null) { + walker = this.tail + } + + if (walker !== this.head && walker !== this.tail) { + walker = walker.prev + } + + for (var i = 2; i < arguments.length; i++) { + walker = insert(this, walker, arguments[i]) + } + return ret; +} + +Yallist.prototype.reverse = function () { + var head = this.head + var tail = this.tail + for (var walker = head; walker !== null; walker = walker.prev) { + var p = walker.prev + walker.prev = walker.next + walker.next = p + } + this.head = tail + this.tail = head + return this +} + +function insert (self, node, value) { + var inserted = node === self.head ? + new Node(value, null, node, self) : + new Node(value, node, node.next, self) + + if (inserted.next === null) { + self.tail = inserted + } + if (inserted.prev === null) { + self.head = inserted + } + + self.length++ + + return inserted +} + +function push (self, item) { + self.tail = new Node(item, self.tail, null, self) + if (!self.head) { + self.head = self.tail + } + self.length++ +} + +function unshift (self, item) { + self.head = new Node(item, null, self.head, self) + if (!self.tail) { + self.tail = self.head + } + self.length++ +} + +function Node (value, prev, next, list) { + if (!(this instanceof Node)) { + return new Node(value, prev, next, list) + } + + this.list = list + this.value = value + + if (prev) { + prev.next = this + this.prev = prev + } else { + this.prev = null + } + + if (next) { + next.prev = this + this.next = next + } else { + this.next = null + } +} + +try { + // add if support for Symbol.iterator is present + require('./iterator.js')(Yallist) +} catch (er) {} diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..f28ac40 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,243 @@ +{ + "name": "fetch-build-from-gcb", + "version": "0.0.0", + "lockfileVersion": 1, + "requires": true, + "dependencies": { + "@actions/core": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/@actions/core/-/core-1.2.3.tgz", + "integrity": "sha512-Wp4xnyokakM45Uuj4WLUxdsa8fJjKVl1fDTsPbTEcTcuu0Nb26IPQbOtjmnfaCPGcaoPOOqId8H9NapZ8gii4w==" + }, + "abort-controller": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/abort-controller/-/abort-controller-3.0.0.tgz", + "integrity": "sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg==", + "requires": { + "event-target-shim": "^5.0.0" + } + }, + "agent-base": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.0.tgz", + "integrity": "sha512-j1Q7cSCqN+AwrmDd+pzgqc0/NpC655x2bUf5ZjRIO77DcNBFmh+OgRNzF6OKdCC9RSCb19fGd99+bhXFdkRNqw==", + "requires": { + "debug": "4" + } + }, + "arrify": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/arrify/-/arrify-2.0.1.tgz", + "integrity": "sha512-3duEwti880xqi4eAMN8AyR4a0ByT90zoYdLlevfrvU43vb0YZwZVfxOgxWrLXXXpyugL0hNZc9G6BiB5B3nUug==" + }, + "base64-js": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/base64-js/-/base64-js-1.3.1.tgz", + "integrity": "sha512-mLQ4i2QO1ytvGWFWmcngKO//JXAQueZvwEKtjgQFM4jIK0kU+ytMfplL8j+n5mspOfjHwoAg+9yhb7BwAHm36g==" + }, + "bignumber.js": { + "version": "7.2.1", + "resolved": "https://registry.npmjs.org/bignumber.js/-/bignumber.js-7.2.1.tgz", + "integrity": "sha512-S4XzBk5sMB+Rcb/LNcpzXr57VRTxgAvaAEDAl1AwRx27j00hT84O6OkteE7u8UB3NuaaygCRrEpqox4uDOrbdQ==" + }, + "buffer-equal-constant-time": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/buffer-equal-constant-time/-/buffer-equal-constant-time-1.0.1.tgz", + "integrity": "sha1-+OcRMvf/5uAaXJaXpMbz5I1cyBk=" + }, + "debug": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.1.1.tgz", + "integrity": "sha512-pYAIzeRo8J6KPEaJ0VWOh5Pzkbw/RetuzehGM7QRRX5he4fPHx2rdKMB256ehJCkX+XRQm16eZLqLNS8RSZXZw==", + "requires": { + "ms": "^2.1.1" + } + }, + "ecdsa-sig-formatter": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/ecdsa-sig-formatter/-/ecdsa-sig-formatter-1.0.11.tgz", + "integrity": "sha512-nagl3RYrbNv6kQkeJIpt6NJZy8twLB/2vtz6yN9Z4vRKHN4/QZJIEbqohALSgwKdnksuY3k5Addp5lg8sVoVcQ==", + "requires": { + "safe-buffer": "^5.0.1" + } + }, + "event-target-shim": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/event-target-shim/-/event-target-shim-5.0.1.tgz", + "integrity": "sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ==" + }, + "extend": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/extend/-/extend-3.0.2.tgz", + "integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==" + }, + "fast-text-encoding": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/fast-text-encoding/-/fast-text-encoding-1.0.1.tgz", + "integrity": "sha512-x4FEgaz3zNRtJfLFqJmHWxkMDDvXVtaznj2V9jiP8ACUJrUgist4bP9FmDL2Vew2Y9mEQI/tG4GqabaitYp9CQ==" + }, + "gaxios": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-3.0.2.tgz", + "integrity": "sha512-cLOetrsKOBLPwjzVyFzirYaGjrhtYjbKUHp6fQpsio2HH8Mil35JTFQLgkV5D3CCXV7Gnd5V69/m4C9rMBi9bA==", + "requires": { + "abort-controller": "^3.0.0", + "extend": "^3.0.2", + "https-proxy-agent": "^5.0.0", + "is-stream": "^2.0.0", + "node-fetch": "^2.3.0" + } + }, + "gcp-metadata": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/gcp-metadata/-/gcp-metadata-4.0.0.tgz", + "integrity": "sha512-bu5APZrp6hXa+N8P6unMn8ZDwsSrbFd8lD83l6itbkx/9AoH0nS/1Zbg9DyYEAgNkk12pg2BS7d83ePZ2UCuGw==", + "requires": { + "gaxios": "^2.1.0", + "json-bigint": "^0.3.0" + }, + "dependencies": { + "gaxios": { + "version": "2.3.4", + "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-2.3.4.tgz", + "integrity": "sha512-US8UMj8C5pRnao3Zykc4AAVr+cffoNKRTg9Rsf2GiuZCW69vgJj38VK2PzlPuQU73FZ/nTk9/Av6/JGcE1N9vA==", + "requires": { + "abort-controller": "^3.0.0", + "extend": "^3.0.2", + "https-proxy-agent": "^5.0.0", + "is-stream": "^2.0.0", + "node-fetch": "^2.3.0" + } + } + } + }, + "google-auth-library": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/google-auth-library/-/google-auth-library-6.0.0.tgz", + "integrity": "sha512-uLydy1t6SHN/EvYUJrtN3GCHFrnJ0c8HJjOxXiGjoTuYHIoCUT3jVxnzmjHwVnSdkfE9Akasm2rM6qG1COTXfQ==", + "requires": { + "arrify": "^2.0.0", + "base64-js": "^1.3.0", + "ecdsa-sig-formatter": "^1.0.11", + "fast-text-encoding": "^1.0.0", + "gaxios": "^3.0.0", + "gcp-metadata": "^4.0.0", + "gtoken": "^5.0.0", + "jws": "^4.0.0", + "lru-cache": "^5.0.0" + } + }, + "google-p12-pem": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/google-p12-pem/-/google-p12-pem-2.0.4.tgz", + "integrity": "sha512-S4blHBQWZRnEW44OcR7TL9WR+QCqByRvhNDZ/uuQfpxywfupikf/miba8js1jZi6ZOGv5slgSuoshCWh6EMDzg==", + "requires": { + "node-forge": "^0.9.0" + } + }, + "gtoken": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/gtoken/-/gtoken-5.0.0.tgz", + "integrity": "sha512-+TM/Mn9fm2LsAA3bZVSlCG20b0KfDdF6IC/mV/rRWuIUAwvXd2aMCGFNf1ont1qFzJh0tznnfEyY8YLQ1awqdw==", + "requires": { + "gaxios": "^2.1.0", + "google-p12-pem": "^2.0.0", + "jws": "^4.0.0", + "mime": "^2.2.0" + }, + "dependencies": { + "gaxios": { + "version": "2.3.4", + "resolved": "https://registry.npmjs.org/gaxios/-/gaxios-2.3.4.tgz", + "integrity": "sha512-US8UMj8C5pRnao3Zykc4AAVr+cffoNKRTg9Rsf2GiuZCW69vgJj38VK2PzlPuQU73FZ/nTk9/Av6/JGcE1N9vA==", + "requires": { + "abort-controller": "^3.0.0", + "extend": "^3.0.2", + "https-proxy-agent": "^5.0.0", + "is-stream": "^2.0.0", + "node-fetch": "^2.3.0" + } + } + } + }, + "https-proxy-agent": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.0.tgz", + "integrity": "sha512-EkYm5BcKUGiduxzSt3Eppko+PiNWNEpa4ySk9vTC6wDsQJW9rHSa+UhGNJoRYp7bz6Ht1eaRIa6QaJqO5rCFbA==", + "requires": { + "agent-base": "6", + "debug": "4" + } + }, + "is-stream": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.0.tgz", + "integrity": "sha512-XCoy+WlUr7d1+Z8GgSuXmpuUFC9fOhRXglJMx+dwLKTkL44Cjd4W1Z5P+BQZpr+cR93aGP4S/s7Ftw6Nd/kiEw==" + }, + "json-bigint": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/json-bigint/-/json-bigint-0.3.0.tgz", + "integrity": "sha1-DM2RLEuCcNBfBW+9E4FLU9OCWx4=", + "requires": { + "bignumber.js": "^7.0.0" + } + }, + "jwa": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.0.tgz", + "integrity": "sha512-jrZ2Qx916EA+fq9cEAeCROWPTfCwi1IVHqT2tapuqLEVVDKFDENFw1oL+MwrTvH6msKxsd1YTDVw6uKEcsrLEA==", + "requires": { + "buffer-equal-constant-time": "1.0.1", + "ecdsa-sig-formatter": "1.0.11", + "safe-buffer": "^5.0.1" + } + }, + "jws": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.0.tgz", + "integrity": "sha512-KDncfTmOZoOMTFG4mBlG0qUIOlc03fmzH+ru6RgYVZhPkyiy/92Owlt/8UEN+a4TXR1FQetfIpJE8ApdvdVxTg==", + "requires": { + "jwa": "^2.0.0", + "safe-buffer": "^5.0.1" + } + }, + "lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "requires": { + "yallist": "^3.0.2" + } + }, + "mime": { + "version": "2.4.4", + "resolved": "https://registry.npmjs.org/mime/-/mime-2.4.4.tgz", + "integrity": "sha512-LRxmNwziLPT828z+4YkNzloCFC2YM4wrB99k+AV5ZbEyfGNWfG8SO1FUXLmLDBSo89NrJZ4DIWeLjy1CHGhMGA==" + }, + "ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "node-fetch": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.6.0.tgz", + "integrity": "sha512-8dG4H5ujfvFiqDmVu9fQ5bOHUC15JMjMY/Zumv26oOvvVJjM67KF8koCWIabKQ1GJIa9r2mMZscBq/TbdOcmNA==" + }, + "node-forge": { + "version": "0.9.1", + "resolved": "https://registry.npmjs.org/node-forge/-/node-forge-0.9.1.tgz", + "integrity": "sha512-G6RlQt5Sb4GMBzXvhfkeFmbqR6MzhtnT7VTHuLadjkii3rdYHNdw0m8zA4BTxVIh68FicCQ2NSUANpsqkr9jvQ==" + }, + "safe-buffer": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.0.tgz", + "integrity": "sha512-fZEwUGbVl7kouZs1jCdMLdt95hdIv0ZeHg6L7qPeciMZhZ+/gdesW4wgTARkrFWEpspjEATAzUGPG8N2jJiwbg==" + }, + "yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..2688159 --- /dev/null +++ b/package.json @@ -0,0 +1,23 @@ +{ + "name": "fetch-build-from-gcb", + "version": "0.0.0", + "description": "", + "main": "action.js", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/zendesk/fetch-build-from-gcb.git" + }, + "author": "Craig Day", + "license": "private", + "bugs": { + "url": "https://github.com/zendesk/fetch-build-from-gcb/issues" + }, + "homepage": "https://github.com/zendesk/fetch-build-from-gcb#readme", + "dependencies": { + "@actions/core": "^1.2.3", + "google-auth-library": "^6.0.0" + } +}