From 4cb47ac043c4760a730c93f251919d8802b5ac5f Mon Sep 17 00:00:00 2001
From: seebees
Date: Tue, 21 Apr 2020 11:38:44 -0700
Subject: [PATCH 1/4] chore: move to eslint and prettier
Typescript is moving to eslint and prettier is now the standard.
This first PR updates all source files
with these new linting/formatting rules.
The test are NOT changed.
This is to help the reviews confirm
that all changes are format only.
---
.eslintrc.js | 68 +
.prettierrc.js | 9 +
modules/cache-material/package.json | 4 +-
...yptographic_materials_cache_key_helpers.ts | 40 +-
...hing_cryptographic_materials_decorators.ts | 179 +-
.../src/cryptographic_materials_cache.ts | 25 +-
...get_local_cryptographic_materials_cache.ts | 48 +-
.../cache-material/src/portable_compare.ts | 6 +-
.../package.json | 4 +-
.../src/caching_materials_manager_browser.ts | 48 +-
.../src/sha512.ts | 11 +-
.../package.json | 4 +-
.../src/caching_materials_manager_node.ts | 46 +-
.../src/sha512.ts | 9 +-
modules/client-browser/package.json | 4 +-
modules/client-node/package.json | 4 +-
modules/decrypt-browser/package.json | 4 +-
modules/decrypt-browser/src/decrypt.ts | 101 +-
modules/decrypt-node/package.json | 4 +-
modules/decrypt-node/src/decipher_stream.ts | 73 +-
modules/decrypt-node/src/decrypt.ts | 28 +-
modules/decrypt-node/src/decrypt_stream.ts | 37 +-
.../decrypt-node/src/parse_header_stream.ts | 60 +-
modules/decrypt-node/src/verify_stream.ts | 87 +-
modules/encrypt-browser/package.json | 4 +-
modules/encrypt-browser/src/encrypt.ts | 77 +-
modules/encrypt-node/package.json | 4 +-
modules/encrypt-node/src/encrypt.ts | 31 +-
modules/encrypt-node/src/encrypt_stream.ts | 80 +-
.../encrypt-node/src/framed_encrypt_stream.ts | 113 +-
modules/encrypt-node/src/signature_stream.ts | 10 +-
modules/example-browser/package.json | 4 +-
modules/example-browser/src/aes_simple.ts | 34 +-
modules/example-browser/src/caching_cmm.ts | 40 +-
modules/example-browser/src/fallback.ts | 45 +-
modules/example-browser/src/index.ts | 6 +-
modules/example-browser/src/kms_simple.ts | 42 +-
modules/example-browser/src/multi_keyring.ts | 62 +-
modules/example-browser/src/rsa_simple.ts | 68 +-
modules/example-node/package.json | 4 +-
modules/example-node/src/aes_simple.ts | 34 +-
modules/example-node/src/caching_cmm.ts | 37 +-
.../src/kms_regional_discovery.ts | 16 +-
modules/example-node/src/kms_simple.ts | 24 +-
modules/example-node/src/kms_stream.ts | 30 +-
modules/example-node/src/multi_keyring.ts | 48 +-
modules/example-node/src/rsa_simple.ts | 21 +-
modules/hkdf-node/package.json | 4 +-
modules/hkdf-node/src/errors.ts | 13 +-
modules/hkdf-node/src/hkdf.ts | 49 +-
modules/integration-browser/package.json | 4 +-
.../src/build_decrypt_fixtures.ts | 80 +-
.../src/build_encrypt_fixtures.ts | 68 +-
modules/integration-browser/src/cli.ts | 108 +-
.../decrypt_materials_manager_web_crypto.ts | 90 +-
.../src/integration.decrypt.test.ts | 6 +-
.../src/integration.encrypt.test.ts | 10 +-
modules/integration-browser/src/types.ts | 39 +-
modules/integration-node/package.json | 4 +-
modules/integration-node/src/cli.ts | 108 +-
.../src/decrypt_materials_manager_node.ts | 77 +-
.../src/get_decrypt_test_iterator.ts | 85 +-
.../src/get_encrypt_test_iterator.ts | 60 +-
modules/integration-node/src/index.ts | 1 -
.../integration-node/src/integration_tests.ts | 81 +-
modules/integration-node/src/types.ts | 39 +-
modules/kms-keyring-browser/package.json | 4 +-
.../src/kms_keyring_browser.ts | 55 +-
modules/kms-keyring-node/package.json | 4 +-
.../kms-keyring-node/src/kms_keyring_node.ts | 44 +-
modules/kms-keyring/package.json | 4 +-
modules/kms-keyring/src/helpers.ts | 132 +-
.../kms-keyring/src/kms_client_supplier.ts | 89 +-
modules/kms-keyring/src/kms_keyring.ts | 192 +-
modules/kms-keyring/src/kms_types.ts | 23 +-
.../src/region_from_kms_key_arn.ts | 26 +-
.../material-management-browser/package.json | 4 +-
...browser_cryptographic_materials_manager.ts | 151 +-
.../src/bytes2_jwk.ts | 9 +-
.../material-management-browser/src/index.ts | 27 +-
.../src/keyring_helpers.ts | 40 +-
.../src/material_helpers.ts | 190 +-
modules/material-management-node/package.json | 4 +-
modules/material-management-node/src/index.ts | 25 +-
.../src/material_helpers.ts | 136 +-
.../node_cryptographic_materials_manager.ts | 117 +-
modules/material-management/package.json | 4 +-
.../src/algorithm_suites.ts | 74 +-
.../src/clone_cryptographic_material.ts | 43 +-
.../src/cryptographic_material.ts | 429 ++-
modules/material-management/src/ecc_decode.ts | 52 +-
modules/material-management/src/ecc_encode.ts | 16 +-
.../src/encrypted_data_key.ts | 33 +-
.../src/immutable_class.ts | 26 +-
modules/material-management/src/index.ts | 59 +-
modules/material-management/src/keyring.ts | 54 +-
.../material-management/src/keyring_trace.ts | 51 +-
.../src/materials_manager.ts | 18 +-
.../material-management/src/multi_keyring.ts | 88 +-
modules/material-management/src/needs.ts | 24 +-
.../src/node_algorithms.ts | 73 +-
.../material-management/src/pem_helpers.ts | 80 +-
.../material-management/src/signature_key.ts | 60 +-
modules/material-management/src/types.ts | 54 +-
.../src/web_crypto_algorithms.ts | 132 +-
modules/raw-aes-keyring-browser/package.json | 4 +-
modules/raw-aes-keyring-browser/src/index.ts | 5 +-
.../src/raw_aes_keyring_browser.ts | 148 +-
modules/raw-aes-keyring-node/package.json | 4 +-
modules/raw-aes-keyring-node/src/index.ts | 5 +-
.../src/raw_aes_keyring_node.ts | 111 +-
modules/raw-keyring/package.json | 4 +-
.../src/raw_aes_algorithm_suite.ts | 27 +-
.../src/raw_aes_encrypted_data_keys.ts | 74 +-
modules/raw-keyring/src/raw_aes_material.ts | 65 +-
.../raw-keyring/src/raw_keyring_decorators.ts | 36 +-
modules/raw-rsa-keyring-browser/package.json | 4 +-
.../src/get_import_options.ts | 84 +-
.../src/raw_rsa_keyring_web_crypto.ts | 117 +-
modules/raw-rsa-keyring-browser/src/types.ts | 24 +-
modules/raw-rsa-keyring-node/package.json | 4 +-
.../src/oaep_hash_supported.ts | 22 +-
.../src/raw_rsa_keyring_node.ts | 94 +-
modules/serialize/package.json | 4 +-
modules/serialize/src/aad_factory.ts | 23 +-
modules/serialize/src/concat_buffers.ts | 30 +-
modules/serialize/src/decode_body_header.ts | 100 +-
modules/serialize/src/deserialize_factory.ts | 91 +-
modules/serialize/src/ecdsa_signature.ts | 34 +-
modules/serialize/src/identifiers.ts | 32 +-
modules/serialize/src/kdf_info.ts | 14 +-
modules/serialize/src/read_element.ts | 16 +-
modules/serialize/src/serialize_factory.ts | 87 +-
modules/serialize/src/signature_info.ts | 8 +-
modules/serialize/src/types.ts | 50 +-
modules/serialize/src/uint_util.ts | 6 +-
modules/web-crypto-backend/package.json | 4 +-
.../web-crypto-backend/src/backend-factory.ts | 76 +-
modules/web-crypto-backend/src/index.ts | 9 +-
.../src/promisify-ms-crypto.ts | 28 +-
.../src/synchronous_random_values.ts | 2 +-
package-lock.json | 2750 +++++++++++------
package.json | 24 +-
143 files changed, 6290 insertions(+), 3239 deletions(-)
create mode 100644 .eslintrc.js
create mode 100644 .prettierrc.js
diff --git a/.eslintrc.js b/.eslintrc.js
new file mode 100644
index 000000000..bb7d534c1
--- /dev/null
+++ b/.eslintrc.js
@@ -0,0 +1,68 @@
+// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+module.exports = {
+ root: true,
+ parser: '@typescript-eslint/parser',
+ plugins: [
+ '@typescript-eslint',
+ ],
+ extends: [
+ 'eslint:recommended',
+ 'plugin:@typescript-eslint/eslint-recommended',
+ 'plugin:@typescript-eslint/recommended',
+ 'prettier',
+ ],
+ ignorePatterns: ['node_modules/'],
+ rules: {
+ // I disagree with this rule.
+ // Humans read from less specific to more specific.
+ // No on puts the outline at the end of the book.
+ // Since the exported functions should be composed
+ // of lower level functions,
+ // it is good for understanding
+ // for the source files to get more detailed
+ // as you read down from the top.
+ "no-use-before-define": ["error", { "functions": false }],
+ "@typescript-eslint/no-use-before-define": ["error", { "functions": false }],
+ // This is used in a few specific ways.
+ // It may be that adding this to overrides for the tests
+ // and then manual line overrides would be
+ // the best way to handle this later.
+ '@typescript-eslint/no-explicit-any': 'off',
+ // Minimize churn.
+ '@typescript-eslint/member-delimiter-style': ['error', {
+ 'multiline': {
+ 'delimiter': 'none',
+ 'requireLast': false
+ },
+ 'singleline': {
+ 'delimiter': 'semi',
+ 'requireLast': false
+ }
+ }],
+ // The ESDK exports some interfaces
+ // that conflict with this rule.
+ // At a later date, this might be
+ // able to be turned on,
+ // but to ensure ZERO interface changes
+ // this rule is disabled.
+ // To be clear this would only impact
+ // Typescript use of some types/interfaces.
+ "@typescript-eslint/no-empty-interface": 'off',
+ // To minimize the source change,
+ // this is turned of.
+ "@typescript-eslint/ban-ts-ignore": 'off',
+ },
+ // This is a good rule,
+ // but in many tests,
+ // we are just looking to mock specific functions.
+ "overrides": [
+ {
+ "files": ["modules/**/test/**/*.ts"],
+ "rules": {
+ "@typescript-eslint/no-empty-function": "off"
+ }
+ }
+ ]
+};
diff --git a/.prettierrc.js b/.prettierrc.js
new file mode 100644
index 000000000..83f388a03
--- /dev/null
+++ b/.prettierrc.js
@@ -0,0 +1,9 @@
+// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
+// SPDX-License-Identifier: Apache-2.0
+
+// I would prefer to use the default configuration
+// but then the diff is out of control.
+module.exports = {
+ semi: false,
+ singleQuote: true
+}
\ No newline at end of file
diff --git a/modules/cache-material/package.json b/modules/cache-material/package.json
index 29b5c3559..2da52cc92 100644
--- a/modules/cache-material/package.json
+++ b/modules/cache-material/package.json
@@ -4,7 +4,9 @@
"scripts": {
"prepublishOnly": "npm run build",
"build": "tsc -b tsconfig.json && tsc -b tsconfig.module.json",
- "lint": "standard src/*.ts test/**/*.ts",
+ "lint": "run-s lint-*",
+ "lint-eslint": "npx eslint modules/**/src/*.ts modules/**/test/**/*.ts",
+ "lint-prettier": "prettier -c modules/**/src/*.ts modules/**/test/**/*.ts",
"mocha": "mocha --require ts-node/register test/**/*test.ts",
"test": "npm run lint && npm run coverage",
"coverage": "nyc -e .ts npm run mocha"
diff --git a/modules/cache-material/src/build_cryptographic_materials_cache_key_helpers.ts b/modules/cache-material/src/build_cryptographic_materials_cache_key_helpers.ts
index bbf508410..66d500ee5 100644
--- a/modules/cache-material/src/build_cryptographic_materials_cache_key_helpers.ts
+++ b/modules/cache-material/src/build_cryptographic_materials_cache_key_helpers.ts
@@ -2,11 +2,11 @@
// SPDX-License-Identifier: Apache-2.0
import {
- SupportedAlgorithmSuites, // eslint-disable-line no-unused-vars
- DecryptionRequest, // eslint-disable-line no-unused-vars
- EncryptionRequest, // eslint-disable-line no-unused-vars
- EncryptedDataKey, // eslint-disable-line no-unused-vars
- EncryptionContext // eslint-disable-line no-unused-vars
+ SupportedAlgorithmSuites,
+ DecryptionRequest,
+ EncryptionRequest,
+ EncryptedDataKey,
+ EncryptionContext,
} from '@aws-crypto/material-management'
import { serializeFactory, uInt16BE } from '@aws-crypto/serialize'
import { compare } from './portable_compare'
@@ -14,24 +14,26 @@ import { compare } from './portable_compare'
// 512 bits of 0 for padding between hashes in decryption materials cache ID generation.
const BIT_PAD_512 = Buffer.alloc(64)
-export function buildCryptographicMaterialsCacheKeyHelpers (
+export function buildCryptographicMaterialsCacheKeyHelpers<
+ S extends SupportedAlgorithmSuites
+>(
fromUtf8: (input: string) => Uint8Array,
toUtf8: (input: Uint8Array) => string,
- sha512: (...data: ((Uint8Array|string))[]) => Promise
+ sha512: (...data: (Uint8Array | string)[]) => Promise
): CryptographicMaterialsCacheKeyHelpersInterface {
const {
serializeEncryptionContext,
- serializeEncryptedDataKey
+ serializeEncryptedDataKey,
} = serializeFactory(fromUtf8)
return {
buildEncryptionMaterialCacheKey,
buildDecryptionMaterialCacheKey,
encryptedDataKeysHash,
- encryptionContextHash
+ encryptionContextHash,
}
- async function buildEncryptionMaterialCacheKey (
+ async function buildEncryptionMaterialCacheKey(
partition: string,
{ suite, encryptionContext }: EncryptionRequest
) {
@@ -47,7 +49,7 @@ export function buildCryptographicMaterialsCacheKeyHelpers
) {
@@ -63,16 +65,18 @@ export function buildCryptographicMaterialsCacheKeyHelpers) {
+ async function encryptedDataKeysHash(
+ encryptedDataKeys: ReadonlyArray
+ ) {
const hashes = await Promise.all(
encryptedDataKeys
.map(serializeEncryptedDataKey)
- .map(edk => sha512(edk))
+ .map(async (edk) => sha512(edk))
)
return hashes.sort(compare)
}
- function encryptionContextHash (context: EncryptionContext) {
+ async function encryptionContextHash(context: EncryptionContext) {
/* The AAD section is uInt16BE(length) + AAD
* see: https://docs.aws.amazon.com/encryption-sdk/latest/developer-guide/message-format.html#header-aad
* However, the RAW Keyring wants _only_ the ADD.
@@ -83,7 +87,9 @@ export function buildCryptographicMaterialsCacheKeyHelpers {
+export interface CryptographicMaterialsCacheKeyHelpersInterface<
+ S extends SupportedAlgorithmSuites
+> {
buildEncryptionMaterialCacheKey(
partition: string,
{ suite, encryptionContext }: EncryptionRequest
@@ -92,6 +98,8 @@ export interface CryptographicMaterialsCacheKeyHelpersInterface
): Promise
- encryptedDataKeysHash(encryptedDataKeys: ReadonlyArray): Promise
+ encryptedDataKeysHash(
+ encryptedDataKeys: ReadonlyArray
+ ): Promise
encryptionContextHash(context: EncryptionContext): Promise
}
diff --git a/modules/cache-material/src/caching_cryptographic_materials_decorators.ts b/modules/cache-material/src/caching_cryptographic_materials_decorators.ts
index 32dd52b12..7235f8b97 100644
--- a/modules/cache-material/src/caching_cryptographic_materials_decorators.ts
+++ b/modules/cache-material/src/caching_cryptographic_materials_decorators.ts
@@ -2,33 +2,38 @@
// SPDX-License-Identifier: Apache-2.0
import {
- GetEncryptionMaterials, // eslint-disable-line no-unused-vars
- GetDecryptMaterials, // eslint-disable-line no-unused-vars
- DecryptionMaterial, // eslint-disable-line no-unused-vars
- SupportedAlgorithmSuites, // eslint-disable-line no-unused-vars
- EncryptionRequest, // eslint-disable-line no-unused-vars
- EncryptionMaterial, // eslint-disable-line no-unused-vars
- MaterialsManager, // eslint-disable-line no-unused-vars
- DecryptionRequest, // eslint-disable-line no-unused-vars
+ GetEncryptionMaterials,
+ GetDecryptMaterials,
+ DecryptionMaterial,
+ SupportedAlgorithmSuites,
+ EncryptionRequest,
+ EncryptionMaterial,
+ MaterialsManager,
+ DecryptionRequest,
needs,
readOnlyProperty,
- Keyring, // eslint-disable-line no-unused-vars
- cloneMaterial
+ Keyring,
+ cloneMaterial,
} from '@aws-crypto/material-management'
import { Maximum } from '@aws-crypto/serialize'
import {
- CryptographicMaterialsCache, // eslint-disable-line no-unused-vars
- Entry // eslint-disable-line no-unused-vars
+ CryptographicMaterialsCache,
+ Entry,
} from './cryptographic_materials_cache'
-import {
- CryptographicMaterialsCacheKeyHelpersInterface // eslint-disable-line no-unused-vars
-} from './build_cryptographic_materials_cache_key_helpers'
+import { CryptographicMaterialsCacheKeyHelpersInterface } from './build_cryptographic_materials_cache_key_helpers'
-export function decorateProperties (
+export function decorateProperties(
obj: CachingMaterialsManager,
input: CachingMaterialsManagerDecorateInput
) {
- const { cache, backingMaterialsManager, maxAge, maxBytesEncrypted, maxMessagesEncrypted, partition } = input
+ const {
+ cache,
+ backingMaterialsManager,
+ maxAge,
+ maxBytesEncrypted,
+ maxMessagesEncrypted,
+ partition,
+ } = input
/* Precondition: A caching material manager needs a cache. */
needs(cache, 'You must provide a cache.')
@@ -37,36 +42,64 @@ export function decorateProperties (
/* Precondition: You *can not* cache something forever. */
needs(maxAge > 0, 'You must configure a maxAge')
/* Precondition: maxBytesEncrypted must be inside bounds. i.e. positive and not more than the maximum. */
- needs(!maxBytesEncrypted || (maxBytesEncrypted > 0 && Maximum.BYTES_PER_CACHED_KEY_LIMIT >= maxBytesEncrypted), 'maxBytesEncrypted is outside of bounds.')
+ needs(
+ !maxBytesEncrypted ||
+ (maxBytesEncrypted > 0 &&
+ Maximum.BYTES_PER_CACHED_KEY_LIMIT >= maxBytesEncrypted),
+ 'maxBytesEncrypted is outside of bounds.'
+ )
/* Precondition: maxMessagesEncrypted must be inside bounds. i.e. positive and not more than the maximum. */
- needs(!maxMessagesEncrypted || (maxMessagesEncrypted > 0 && Maximum.MESSAGES_PER_CACHED_KEY_LIMIT >= maxMessagesEncrypted), 'maxMessagesEncrypted is outside of bounds.')
+ needs(
+ !maxMessagesEncrypted ||
+ (maxMessagesEncrypted > 0 &&
+ Maximum.MESSAGES_PER_CACHED_KEY_LIMIT >= maxMessagesEncrypted),
+ 'maxMessagesEncrypted is outside of bounds.'
+ )
/* Precondition: partition must be a string. */
- needs(partition && typeof partition === 'string', 'partition must be a string.')
+ needs(
+ partition && typeof partition === 'string',
+ 'partition must be a string.'
+ )
readOnlyProperty(obj, '_cache', cache)
readOnlyProperty(obj, '_backingMaterialsManager', backingMaterialsManager)
readOnlyProperty(obj, '_maxAge', maxAge)
- readOnlyProperty(obj, '_maxBytesEncrypted', maxBytesEncrypted || Maximum.BYTES_PER_CACHED_KEY_LIMIT)
- readOnlyProperty(obj, '_maxMessagesEncrypted', maxMessagesEncrypted || Maximum.MESSAGES_PER_CACHED_KEY_LIMIT)
+ readOnlyProperty(
+ obj,
+ '_maxBytesEncrypted',
+ maxBytesEncrypted || Maximum.BYTES_PER_CACHED_KEY_LIMIT
+ )
+ readOnlyProperty(
+ obj,
+ '_maxMessagesEncrypted',
+ maxMessagesEncrypted || Maximum.MESSAGES_PER_CACHED_KEY_LIMIT
+ )
readOnlyProperty(obj, '_partition', partition)
}
-export function getEncryptionMaterials (
- { buildEncryptionMaterialCacheKey }: CryptographicMaterialsCacheKeyHelpersInterface
-): GetEncryptionMaterials {
- return async function getEncryptionMaterials (
+export function getEncryptionMaterials({
+ buildEncryptionMaterialCacheKey,
+}: CryptographicMaterialsCacheKeyHelpersInterface): GetEncryptionMaterials<
+ S
+> {
+ return async function getEncryptionMaterials(
this: CachingMaterialsManager,
request: EncryptionRequest
): Promise> {
const { suite, encryptionContext, plaintextLength } = request
/* Check for early return (Postcondition): If I can not cache the EncryptionMaterial, do not even look. */
- if ((suite && !suite.cacheSafe) || typeof plaintextLength !== 'number' || plaintextLength < 0) {
- return this
- ._backingMaterialsManager
- .getEncryptionMaterials(request)
+ if (
+ (suite && !suite.cacheSafe) ||
+ typeof plaintextLength !== 'number' ||
+ plaintextLength < 0
+ ) {
+ return this._backingMaterialsManager.getEncryptionMaterials(request)
}
- const cacheKey = await buildEncryptionMaterialCacheKey(this._partition, { suite, encryptionContext })
+ const cacheKey = await buildEncryptionMaterialCacheKey(this._partition, {
+ suite,
+ encryptionContext,
+ })
const entry = this._cache.getEncryptionMaterial(cacheKey, plaintextLength)
/* Check for early return (Postcondition): If I have a valid EncryptionMaterial, return it. */
if (entry && !this._cacheEntryHasExceededLimits(entry)) {
@@ -75,8 +108,7 @@ export function getEncryptionMaterials (
this._cache.del(cacheKey)
}
- const material = await this
- ._backingMaterialsManager
+ const material = await this._backingMaterialsManager
/* Strip any information about the plaintext from the backing request,
* because the resulting response may be used to encrypt multiple plaintexts.
*/
@@ -94,10 +126,15 @@ export function getEncryptionMaterials (
response: material,
now: Date.now(),
messagesEncrypted: 1,
- bytesEncrypted: plaintextLength
+ bytesEncrypted: plaintextLength,
}
if (!this._cacheEntryHasExceededLimits(testEntry)) {
- this._cache.putEncryptionMaterial(cacheKey, material, plaintextLength, this._maxAge)
+ this._cache.putEncryptionMaterial(
+ cacheKey,
+ material,
+ plaintextLength,
+ this._maxAge
+ )
return cloneResponse(material)
} else {
/* Postcondition: If the material has exceeded limits it MUST NOT be cloned.
@@ -110,22 +147,23 @@ export function getEncryptionMaterials (
}
}
-export function decryptMaterials (
- { buildDecryptionMaterialCacheKey }: CryptographicMaterialsCacheKeyHelpersInterface
-): GetDecryptMaterials {
- return async function decryptMaterials (
+export function decryptMaterials({
+ buildDecryptionMaterialCacheKey,
+}: CryptographicMaterialsCacheKeyHelpersInterface): GetDecryptMaterials {
+ return async function decryptMaterials(
this: CachingMaterialsManager,
request: DecryptionRequest
): Promise> {
const { suite } = request
/* Check for early return (Postcondition): If I can not cache the DecryptionMaterial, do not even look. */
if (!suite.cacheSafe) {
- return this
- ._backingMaterialsManager
- .decryptMaterials(request)
+ return this._backingMaterialsManager.decryptMaterials(request)
}
- const cacheKey = await buildDecryptionMaterialCacheKey(this._partition, request)
+ const cacheKey = await buildDecryptionMaterialCacheKey(
+ this._partition,
+ request
+ )
const entry = this._cache.getDecryptionMaterial(cacheKey)
/* Check for early return (Postcondition): If I have a valid DecryptionMaterial, return it. */
if (entry && !this._cacheEntryHasExceededLimits(entry)) {
@@ -134,24 +172,28 @@ export function decryptMaterials (
this._cache.del(cacheKey)
}
- const material = await this
- ._backingMaterialsManager
- .decryptMaterials(request)
+ const material = await this._backingMaterialsManager.decryptMaterials(
+ request
+ )
this._cache.putDecryptionMaterial(cacheKey, material, this._maxAge)
return cloneResponse(material)
}
}
-export function cacheEntryHasExceededLimits (): CacheEntryHasExceededLimits {
- return function cacheEntryHasExceededLimits (
+export function cacheEntryHasExceededLimits<
+ S extends SupportedAlgorithmSuites
+>(): CacheEntryHasExceededLimits {
+ return function cacheEntryHasExceededLimits(
this: CachingMaterialsManager,
{ now, messagesEncrypted, bytesEncrypted }: Entry
): boolean {
const age = Date.now() - now
- return age > this._maxAge ||
+ return (
+ age > this._maxAge ||
messagesEncrypted > this._maxMessagesEncrypted ||
bytesEncrypted > this._maxBytesEncrypted
+ )
}
}
@@ -163,27 +205,34 @@ export function cacheEntryHasExceededLimits
* @param material EncryptionMaterial|DecryptionMaterial
* @return EncryptionMaterial|DecryptionMaterial
*/
-function cloneResponse|DecryptionMaterial> (
- material: M
-): M {
+function cloneResponse<
+ S extends SupportedAlgorithmSuites,
+ M extends EncryptionMaterial | DecryptionMaterial
+>(material: M): M {
return cloneMaterial(material)
}
-export interface CachingMaterialsManagerInput extends Readonly<{
- cache: CryptographicMaterialsCache
- backingMaterials: MaterialsManager|Keyring
- partition?: string
- maxBytesEncrypted?: number
- maxMessagesEncrypted?: number
- maxAge: number
-}>{}
-
-export interface CachingMaterialsManagerDecorateInput extends CachingMaterialsManagerInput {
+export interface CachingMaterialsManagerInput<
+ S extends SupportedAlgorithmSuites
+>
+ extends Readonly<{
+ cache: CryptographicMaterialsCache
+ backingMaterials: MaterialsManager | Keyring
+ partition?: string
+ maxBytesEncrypted?: number
+ maxMessagesEncrypted?: number
+ maxAge: number
+ }> {}
+
+export interface CachingMaterialsManagerDecorateInput<
+ S extends SupportedAlgorithmSuites
+> extends CachingMaterialsManagerInput {
backingMaterialsManager: MaterialsManager
partition: string
}
-export interface CachingMaterialsManager extends MaterialsManager {
+export interface CachingMaterialsManager
+ extends MaterialsManager {
readonly _partition: string
readonly _cache: CryptographicMaterialsCache
readonly _backingMaterialsManager: MaterialsManager
@@ -194,6 +243,8 @@ export interface CachingMaterialsManager ext
_cacheEntryHasExceededLimits: CacheEntryHasExceededLimits
}
-export interface CacheEntryHasExceededLimits {
+export interface CacheEntryHasExceededLimits<
+ S extends SupportedAlgorithmSuites
+> {
(entry: Entry): boolean
}
diff --git a/modules/cache-material/src/cryptographic_materials_cache.ts b/modules/cache-material/src/cryptographic_materials_cache.ts
index 81a887675..068aa4d18 100644
--- a/modules/cache-material/src/cryptographic_materials_cache.ts
+++ b/modules/cache-material/src/cryptographic_materials_cache.ts
@@ -2,12 +2,14 @@
// SPDX-License-Identifier: Apache-2.0
import {
- EncryptionMaterial, // eslint-disable-line no-unused-vars
- DecryptionMaterial, // eslint-disable-line no-unused-vars
- SupportedAlgorithmSuites // eslint-disable-line no-unused-vars
+ EncryptionMaterial,
+ DecryptionMaterial,
+ SupportedAlgorithmSuites,
} from '@aws-crypto/material-management'
-export interface CryptographicMaterialsCache {
+export interface CryptographicMaterialsCache<
+ S extends SupportedAlgorithmSuites
+> {
putEncryptionMaterial(
key: string,
response: EncryptionMaterial,
@@ -19,22 +21,27 @@ export interface CryptographicMaterialsCache
response: DecryptionMaterial,
maxAge?: number
): void
- getEncryptionMaterial(key: string, plaintextLength: number): EncryptionMaterialEntry|false
- getDecryptionMaterial(key: string): DecryptionMaterialEntry|false
+ getEncryptionMaterial(
+ key: string,
+ plaintextLength: number
+ ): EncryptionMaterialEntry | false
+ getDecryptionMaterial(key: string): DecryptionMaterialEntry | false
del(key: string): void
}
export interface Entry {
- response: EncryptionMaterial|DecryptionMaterial
+ response: EncryptionMaterial | DecryptionMaterial
bytesEncrypted: number
messagesEncrypted: number
readonly now: number
}
-export interface EncryptionMaterialEntry extends Entry {
+export interface EncryptionMaterialEntry
+ extends Entry {
readonly response: EncryptionMaterial
}
-export interface DecryptionMaterialEntry extends Entry {
+export interface DecryptionMaterialEntry
+ extends Entry {
readonly response: DecryptionMaterial
}
diff --git a/modules/cache-material/src/get_local_cryptographic_materials_cache.ts b/modules/cache-material/src/get_local_cryptographic_materials_cache.ts
index 316bf385f..8708b3a07 100644
--- a/modules/cache-material/src/get_local_cryptographic_materials_cache.ts
+++ b/modules/cache-material/src/get_local_cryptographic_materials_cache.ts
@@ -3,31 +3,33 @@
import LRU from 'lru-cache'
import {
- EncryptionMaterial, // eslint-disable-line no-unused-vars
- DecryptionMaterial, // eslint-disable-line no-unused-vars
- SupportedAlgorithmSuites, // eslint-disable-line no-unused-vars
+ EncryptionMaterial,
+ DecryptionMaterial,
+ SupportedAlgorithmSuites,
needs,
isEncryptionMaterial,
- isDecryptionMaterial
+ isDecryptionMaterial,
} from '@aws-crypto/material-management'
import {
- CryptographicMaterialsCache, // eslint-disable-line no-unused-vars
- Entry, // eslint-disable-line no-unused-vars
- EncryptionMaterialEntry, // eslint-disable-line no-unused-vars
- DecryptionMaterialEntry // eslint-disable-line no-unused-vars
+ CryptographicMaterialsCache,
+ Entry,
+ EncryptionMaterialEntry,
+ DecryptionMaterialEntry,
} from './cryptographic_materials_cache'
-export function getLocalCryptographicMaterialsCache (
+export function getLocalCryptographicMaterialsCache<
+ S extends SupportedAlgorithmSuites
+>(
capacity: number,
proactiveFrequency: number = 1000 * 60
): CryptographicMaterialsCache {
const cache = new LRU>({
max: capacity,
- dispose (_key, value) {
+ dispose(_key, value) {
/* Zero out the unencrypted dataKey, when the material is removed from the cache. */
value.response.zeroUnencryptedDataKey()
- }
+ },
})
/* It is not a guarantee that the last item in the LRU will be the Oldest Item.
@@ -43,7 +45,7 @@ export function getLocalCryptographicMaterialsCache {
mayEvictTail()
proactivelyTryAndEvictTail()
@@ -59,7 +61,7 @@ export function getLocalCryptographicMaterialsCache,
plaintextLength: number,
@@ -75,12 +77,12 @@ export function getLocalCryptographicMaterialsCache,
maxAge?: number
@@ -93,12 +95,12 @@ export function getLocalCryptographicMaterialsCache= 0, 'Malformed plaintextLength')
const entry = cache.get(key)
@@ -110,23 +112,23 @@ export function getLocalCryptographicMaterialsCache>entry
+ return entry as EncryptionMaterialEntry
},
- getDecryptionMaterial (key: string) {
+ getDecryptionMaterial(key: string) {
const entry = cache.get(key)
/* Check for early return (Postcondition): If this key does not have a DecryptionMaterial, return false. */
if (!entry) return false
/* Postcondition: Only return DecryptionMaterial. */
needs(isDecryptionMaterial(entry.response), 'Malformed response.')
- return >entry
+ return entry as DecryptionMaterialEntry
},
- del (key: string) {
+ del(key: string) {
cache.del(key)
- }
+ },
}
- function mayEvictTail () {
+ function mayEvictTail() {
// @ts-ignore
const { tail } = cache.dumpLru()
/* Check for early return (Postcondition) UNTESTED: If there is no tail, then the cache is empty. */
diff --git a/modules/cache-material/src/portable_compare.ts b/modules/cache-material/src/portable_compare.ts
index 6c1f79698..e87ebb054 100644
--- a/modules/cache-material/src/portable_compare.ts
+++ b/modules/cache-material/src/portable_compare.ts
@@ -6,10 +6,8 @@
* This is a simple compare function that is portable.
* This function is *not* constant time.
*/
-export function compare (a: Uint8Array, b: Uint8Array) {
- const length = a.byteLength > b.byteLength
- ? b.byteLength
- : a.byteLength
+export function compare(a: Uint8Array, b: Uint8Array) {
+ const length = a.byteLength > b.byteLength ? b.byteLength : a.byteLength
for (let i = 0; length > i; i += 1) {
if (a[i] > b[i]) return 1
diff --git a/modules/caching-materials-manager-browser/package.json b/modules/caching-materials-manager-browser/package.json
index 724370cc4..1cb39b2e7 100644
--- a/modules/caching-materials-manager-browser/package.json
+++ b/modules/caching-materials-manager-browser/package.json
@@ -4,7 +4,9 @@
"scripts": {
"prepublishOnly": "npm run build",
"build": "tsc -b tsconfig.json && tsc -b tsconfig.module.json",
- "lint": "standard src/*.ts test/**/*.ts",
+ "lint": "run-s lint-*",
+ "lint-eslint": "npx eslint modules/**/src/*.ts modules/**/test/**/*.ts",
+ "lint-prettier": "prettier -c modules/**/src/*.ts modules/**/test/**/*.ts",
"karma": "karma start karma.conf.js",
"test": "npm run lint && npm run coverage",
"coverage": "npm run karma && nyc report --exclude-after-remap false -t .karma_output --check-coverage"
diff --git a/modules/caching-materials-manager-browser/src/caching_materials_manager_browser.ts b/modules/caching-materials-manager-browser/src/caching_materials_manager_browser.ts
index 8bd6a3f07..f99f9b49c 100644
--- a/modules/caching-materials-manager-browser/src/caching_materials_manager_browser.ts
+++ b/modules/caching-materials-manager-browser/src/caching_materials_manager_browser.ts
@@ -2,31 +2,36 @@
// SPDX-License-Identifier: Apache-2.0
import {
- CachingMaterialsManager, // eslint-disable-line no-unused-vars
+ CachingMaterialsManager,
decorateProperties,
getEncryptionMaterials,
decryptMaterials,
cacheEntryHasExceededLimits,
buildCryptographicMaterialsCacheKeyHelpers,
- CachingMaterialsManagerInput, // eslint-disable-line no-unused-vars
- CryptographicMaterialsCache // eslint-disable-line no-unused-vars
+ CachingMaterialsManagerInput,
+ CryptographicMaterialsCache,
} from '@aws-crypto/cache-material'
import {
- WebCryptoMaterialsManager, // eslint-disable-line no-unused-vars
+ WebCryptoMaterialsManager,
WebCryptoDefaultCryptographicMaterialsManager,
- WebCryptoAlgorithmSuite, // eslint-disable-line no-unused-vars
+ WebCryptoAlgorithmSuite,
KeyringWebCrypto,
- WebCryptoGetEncryptionMaterials, // eslint-disable-line no-unused-vars
- WebCryptoGetDecryptMaterials // eslint-disable-line no-unused-vars
+ WebCryptoGetEncryptionMaterials,
+ WebCryptoGetDecryptMaterials,
} from '@aws-crypto/material-management-browser'
import { fromUtf8, toUtf8 } from '@aws-sdk/util-utf8-browser'
import { toBase64 } from '@aws-sdk/util-base64-browser'
import { synchronousRandomValues } from '@aws-crypto/web-crypto-backend'
import { sha512 } from './sha512'
-const cacheKeyHelpers = buildCryptographicMaterialsCacheKeyHelpers(fromUtf8, toUtf8, sha512)
+const cacheKeyHelpers = buildCryptographicMaterialsCacheKeyHelpers(
+ fromUtf8,
+ toUtf8,
+ sha512
+)
-export class WebCryptoCachingMaterialsManager implements CachingMaterialsManager {
+export class WebCryptoCachingMaterialsManager
+ implements CachingMaterialsManager {
readonly _cache!: CryptographicMaterialsCache
readonly _backingMaterialsManager!: WebCryptoMaterialsManager
readonly _partition!: string
@@ -34,10 +39,13 @@ export class WebCryptoCachingMaterialsManager implements CachingMaterialsManager
readonly _maxMessagesEncrypted!: number
readonly _maxAge!: number
- constructor (input: CachingMaterialsManagerInput) {
- const backingMaterialsManager = input.backingMaterials instanceof KeyringWebCrypto
- ? new WebCryptoDefaultCryptographicMaterialsManager(input.backingMaterials)
- : input.backingMaterials
+ constructor(input: CachingMaterialsManagerInput) {
+ const backingMaterialsManager =
+ input.backingMaterials instanceof KeyringWebCrypto
+ ? new WebCryptoDefaultCryptographicMaterialsManager(
+ input.backingMaterials
+ )
+ : (input.backingMaterials as WebCryptoDefaultCryptographicMaterialsManager)
/* Precondition: A partition value must exist for WebCryptoCachingMaterialsManager.
* The maximum hash function at this time is 512.
@@ -48,11 +56,17 @@ export class WebCryptoCachingMaterialsManager implements CachingMaterialsManager
decorateProperties(this, {
...input,
backingMaterialsManager,
- partition
+ partition,
})
}
- getEncryptionMaterials: WebCryptoGetEncryptionMaterials = getEncryptionMaterials(cacheKeyHelpers)
- decryptMaterials: WebCryptoGetDecryptMaterials = decryptMaterials(cacheKeyHelpers)
- _cacheEntryHasExceededLimits = cacheEntryHasExceededLimits()
+ getEncryptionMaterials: WebCryptoGetEncryptionMaterials = getEncryptionMaterials<
+ WebCryptoAlgorithmSuite
+ >(cacheKeyHelpers)
+ decryptMaterials: WebCryptoGetDecryptMaterials = decryptMaterials<
+ WebCryptoAlgorithmSuite
+ >(cacheKeyHelpers)
+ _cacheEntryHasExceededLimits = cacheEntryHasExceededLimits<
+ WebCryptoAlgorithmSuite
+ >()
}
diff --git a/modules/caching-materials-manager-browser/src/sha512.ts b/modules/caching-materials-manager-browser/src/sha512.ts
index 318c65b02..e367eae34 100644
--- a/modules/caching-materials-manager-browser/src/sha512.ts
+++ b/modules/caching-materials-manager-browser/src/sha512.ts
@@ -2,12 +2,17 @@
// SPDX-License-Identifier: Apache-2.0
import { fromUtf8 } from '@aws-sdk/util-utf8-browser'
-import { getWebCryptoBackend, getNonZeroByteBackend } from '@aws-crypto/web-crypto-backend'
+import {
+ getWebCryptoBackend,
+ getNonZeroByteBackend,
+} from '@aws-crypto/web-crypto-backend'
import { concatBuffers } from '@aws-crypto/serialize'
-export const sha512 = async (...inputs: (Uint8Array|string)[]) => {
+export const sha512 = async (...inputs: (Uint8Array | string)[]) => {
// Normalize to Uint8Array and squash into a single value.
- const data = concatBuffers(...inputs.map(u => typeof u === 'string' ? fromUtf8(u) : u))
+ const data = concatBuffers(
+ ...inputs.map((u) => (typeof u === 'string' ? fromUtf8(u) : u))
+ )
// Prefer the non-zero byte because this will always be the native implementation.
const backend = getNonZeroByteBackend(await getWebCryptoBackend())
// Do the hash
diff --git a/modules/caching-materials-manager-node/package.json b/modules/caching-materials-manager-node/package.json
index ff9389b55..1851461ff 100644
--- a/modules/caching-materials-manager-node/package.json
+++ b/modules/caching-materials-manager-node/package.json
@@ -4,7 +4,9 @@
"scripts": {
"prepublishOnly": "npm run build",
"build": "tsc -b tsconfig.json && tsc -b tsconfig.module.json",
- "lint": "standard src/*.ts test/**/*.ts",
+ "lint": "run-s lint-*",
+ "lint-eslint": "npx eslint modules/**/src/*.ts modules/**/test/**/*.ts",
+ "lint-prettier": "prettier -c modules/**/src/*.ts modules/**/test/**/*.ts",
"mocha": "mocha --require ts-node/register test/**/*test.ts",
"test": "npm run lint && npm run coverage",
"coverage": "nyc -e .ts npm run mocha"
diff --git a/modules/caching-materials-manager-node/src/caching_materials_manager_node.ts b/modules/caching-materials-manager-node/src/caching_materials_manager_node.ts
index f968fbace..bf5fe34a0 100644
--- a/modules/caching-materials-manager-node/src/caching_materials_manager_node.ts
+++ b/modules/caching-materials-manager-node/src/caching_materials_manager_node.ts
@@ -2,22 +2,22 @@
// SPDX-License-Identifier: Apache-2.0
import {
- CachingMaterialsManager, // eslint-disable-line no-unused-vars
+ CachingMaterialsManager,
decorateProperties,
getEncryptionMaterials,
decryptMaterials,
cacheEntryHasExceededLimits,
buildCryptographicMaterialsCacheKeyHelpers,
- CachingMaterialsManagerInput, // eslint-disable-line no-unused-vars
- CryptographicMaterialsCache // eslint-disable-line no-unused-vars
+ CachingMaterialsManagerInput,
+ CryptographicMaterialsCache,
} from '@aws-crypto/cache-material'
import {
- NodeMaterialsManager, // eslint-disable-line no-unused-vars
+ NodeMaterialsManager,
NodeDefaultCryptographicMaterialsManager,
- NodeAlgorithmSuite, // eslint-disable-line no-unused-vars
+ NodeAlgorithmSuite,
KeyringNode,
- NodeGetEncryptionMaterials, // eslint-disable-line no-unused-vars
- NodeGetDecryptMaterials // eslint-disable-line no-unused-vars
+ NodeGetEncryptionMaterials,
+ NodeGetDecryptMaterials,
} from '@aws-crypto/material-management-node'
import { sha512 } from './sha512'
import { randomBytes } from 'crypto'
@@ -25,9 +25,14 @@ import { randomBytes } from 'crypto'
const fromUtf8 = (input: string) => Buffer.from(input, 'utf8')
const toUtf8 = (input: Uint8Array) => Buffer.from(input).toString('utf8')
-const cacheKeyHelpers = buildCryptographicMaterialsCacheKeyHelpers(fromUtf8, toUtf8, sha512)
+const cacheKeyHelpers = buildCryptographicMaterialsCacheKeyHelpers(
+ fromUtf8,
+ toUtf8,
+ sha512
+)
-export class NodeCachingMaterialsManager implements CachingMaterialsManager {
+export class NodeCachingMaterialsManager
+ implements CachingMaterialsManager {
readonly _cache!: CryptographicMaterialsCache
readonly _backingMaterialsManager!: NodeMaterialsManager
readonly _partition!: string
@@ -35,10 +40,11 @@ export class NodeCachingMaterialsManager implements CachingMaterialsManager) {
- const backingMaterialsManager = input.backingMaterials instanceof KeyringNode
- ? new NodeDefaultCryptographicMaterialsManager(input.backingMaterials)
- : input.backingMaterials
+ constructor(input: CachingMaterialsManagerInput) {
+ const backingMaterialsManager =
+ input.backingMaterials instanceof KeyringNode
+ ? new NodeDefaultCryptographicMaterialsManager(input.backingMaterials)
+ : (input.backingMaterials as NodeDefaultCryptographicMaterialsManager)
/* Precondition: A partition value must exist for NodeCachingMaterialsManager.
* The maximum hash function at this time is 512.
@@ -49,11 +55,17 @@ export class NodeCachingMaterialsManager implements CachingMaterialsManager(cacheKeyHelpers)
- decryptMaterials: NodeGetDecryptMaterials = decryptMaterials(cacheKeyHelpers)
- _cacheEntryHasExceededLimits = cacheEntryHasExceededLimits()
+ getEncryptionMaterials: NodeGetEncryptionMaterials = getEncryptionMaterials<
+ NodeAlgorithmSuite
+ >(cacheKeyHelpers)
+ decryptMaterials: NodeGetDecryptMaterials = decryptMaterials<
+ NodeAlgorithmSuite
+ >(cacheKeyHelpers)
+ _cacheEntryHasExceededLimits = cacheEntryHasExceededLimits<
+ NodeAlgorithmSuite
+ >()
}
diff --git a/modules/caching-materials-manager-node/src/sha512.ts b/modules/caching-materials-manager-node/src/sha512.ts
index 1cef41ea3..903ee9411 100644
--- a/modules/caching-materials-manager-node/src/sha512.ts
+++ b/modules/caching-materials-manager-node/src/sha512.ts
@@ -3,7 +3,8 @@
import { createHash } from 'crypto'
-export const sha512 = async (...data: (Uint8Array|string)[]) => data
- .map(item => typeof item === 'string' ? Buffer.from(item) : item)
- .reduce((hash, item) => hash.update(item), createHash('sha512'))
- .digest()
+export const sha512 = async (...data: (Uint8Array | string)[]) =>
+ data
+ .map((item) => (typeof item === 'string' ? Buffer.from(item) : item))
+ .reduce((hash, item) => hash.update(item), createHash('sha512'))
+ .digest()
diff --git a/modules/client-browser/package.json b/modules/client-browser/package.json
index dd87afb0b..ab70fcc30 100644
--- a/modules/client-browser/package.json
+++ b/modules/client-browser/package.json
@@ -12,7 +12,9 @@
"version": "1.0.5",
"scripts": {
"build": "tsc -b tsconfig.json",
- "lint": "standard src/*.ts test/**/*.ts"
+ "lint": "run-s lint-*",
+ "lint-eslint": "npx eslint modules/**/src/*.ts modules/**/test/**/*.ts",
+ "lint-prettier": "prettier -c modules/**/src/*.ts modules/**/test/**/*.ts"
},
"author": {
"name": "AWS Crypto Tools Team",
diff --git a/modules/client-node/package.json b/modules/client-node/package.json
index 0d63ab248..3dcc49b52 100644
--- a/modules/client-node/package.json
+++ b/modules/client-node/package.json
@@ -12,7 +12,9 @@
"version": "1.0.4",
"scripts": {
"build": "tsc -b tsconfig.json",
- "lint": "standard src/*.ts test/**/*.ts"
+ "lint": "run-s lint-*",
+ "lint-eslint": "npx eslint modules/**/src/*.ts modules/**/test/**/*.ts",
+ "lint-prettier": "prettier -c modules/**/src/*.ts modules/**/test/**/*.ts"
},
"author": {
"name": "AWS Crypto Tools Team",
diff --git a/modules/decrypt-browser/package.json b/modules/decrypt-browser/package.json
index d002039cd..8d1aeb3b2 100644
--- a/modules/decrypt-browser/package.json
+++ b/modules/decrypt-browser/package.json
@@ -3,7 +3,9 @@
"version": "1.1.1",
"scripts": {
"prepublishOnly": "tsc -p tsconfig.json && tsc -p tsconfig.module.json",
- "lint": "standard src/*.ts test/**/*.ts",
+ "lint": "run-s lint-*",
+ "lint-eslint": "npx eslint modules/**/src/*.ts modules/**/test/**/*.ts",
+ "lint-prettier": "prettier -c modules/**/src/*.ts modules/**/test/**/*.ts",
"karma": "karma start karma.conf.js",
"test": "npm run lint && npm run coverage",
"coverage": "npm run karma && nyc report --exclude-after-remap false -t .karma_output --check-coverage"
diff --git a/modules/decrypt-browser/src/decrypt.ts b/modules/decrypt-browser/src/decrypt.ts
index c1efbf288..917d5eb2c 100644
--- a/modules/decrypt-browser/src/decrypt.ts
+++ b/modules/decrypt-browser/src/decrypt.ts
@@ -6,20 +6,20 @@ import {
KeyringWebCrypto,
WebCryptoDefaultCryptographicMaterialsManager,
getDecryptionHelper,
- GetSubtleDecrypt, // eslint-disable-line no-unused-vars
+ GetSubtleDecrypt,
needs,
- WebCryptoMaterialsManager // eslint-disable-line no-unused-vars
+ WebCryptoMaterialsManager,
} from '@aws-crypto/material-management-browser'
import {
deserializeSignature,
- MessageHeader, // eslint-disable-line no-unused-vars
+ MessageHeader,
deserializeFactory,
kdfInfo,
decodeBodyHeader,
aadFactory,
concatBuffers,
der2raw,
- HeaderInfo // eslint-disable-line no-unused-vars
+ HeaderInfo,
} from '@aws-crypto/serialize'
import { fromUtf8, toUtf8 } from '@aws-sdk/util-utf8-browser'
@@ -31,31 +31,49 @@ export interface DecryptResult {
plaintext: Uint8Array
}
-export async function decrypt (
- cmm: KeyringWebCrypto|WebCryptoMaterialsManager,
+export async function decrypt(
+ cmm: KeyringWebCrypto | WebCryptoMaterialsManager,
ciphertext: Uint8Array
): Promise {
/* If the cmm is a Keyring, wrap it with WebCryptoDefaultCryptographicMaterialsManager. */
- cmm = cmm instanceof KeyringWebCrypto
- ? new WebCryptoDefaultCryptographicMaterialsManager(cmm)
- : cmm
+ cmm =
+ cmm instanceof KeyringWebCrypto
+ ? new WebCryptoDefaultCryptographicMaterialsManager(cmm)
+ : cmm
const headerInfo = deserialize.deserializeMessageHeader(ciphertext)
if (headerInfo === false) throw new Error('Unable to parse Header')
const { messageHeader } = headerInfo
const { rawHeader, headerIv, headerAuthTag } = headerInfo
- const { encryptionContext, encryptedDataKeys, suiteId, messageId } = messageHeader
+ const {
+ encryptionContext,
+ encryptedDataKeys,
+ suiteId,
+ messageId,
+ } = messageHeader
const suite = new WebCryptoAlgorithmSuite(suiteId)
- const material = await cmm.decryptMaterials({ suite, encryptionContext, encryptedDataKeys })
- const { kdfGetSubtleDecrypt, subtleVerify, dispose } = await getDecryptionHelper(material)
+ const material = await cmm.decryptMaterials({
+ suite,
+ encryptionContext,
+ encryptedDataKeys,
+ })
+ const {
+ kdfGetSubtleDecrypt,
+ subtleVerify,
+ dispose,
+ } = await getDecryptionHelper(material)
const info = kdfInfo(suiteId, messageId)
const getSubtleDecrypt = kdfGetSubtleDecrypt(info)
// The tag is appended to the Data
await getSubtleDecrypt(headerIv, rawHeader)(headerAuthTag) // will throw if invalid
- const { plaintext, readPos } = await bodyDecrypt({ buffer: ciphertext, getSubtleDecrypt, headerInfo })
+ const { plaintext, readPos } = await bodyDecrypt({
+ buffer: ciphertext,
+ getSubtleDecrypt,
+ headerInfo,
+ })
dispose()
@@ -85,15 +103,33 @@ interface FramedDecryptOptions extends BodyDecryptOptions {
readPos: number
}
-async function bodyDecrypt ({ buffer, getSubtleDecrypt, headerInfo }: BodyDecryptOptions) {
- let readPos = headerInfo.headerIv.byteLength + headerInfo.rawHeader.byteLength + headerInfo.headerAuthTag.byteLength
+async function bodyDecrypt({
+ buffer,
+ getSubtleDecrypt,
+ headerInfo,
+}: BodyDecryptOptions) {
+ let readPos =
+ headerInfo.headerIv.byteLength +
+ headerInfo.rawHeader.byteLength +
+ headerInfo.headerAuthTag.byteLength
const clearBuffers: ArrayBuffer[] = []
let sequenceNumber = 0
+ // This is unfortunate, ideally the eslint no-constant-condition could be resolve
+ // but at this time, I'm just going to disable this line
+ // and leave a note to keep myself from replicating this kind of logic.
+ /* eslint-disable no-constant-condition */
while (true) {
+ /* eslint-enable no-constant-condition */
+
/* Keeping track of the sequence number myself. */
sequenceNumber += 1
- const { clearBlob, frameInfo } = await framedDecrypt({ buffer, getSubtleDecrypt, headerInfo, readPos })
+ const { clearBlob, frameInfo } = await framedDecrypt({
+ buffer,
+ getSubtleDecrypt,
+ headerInfo,
+ readPos,
+ })
/* Precondition: The sequenceNumber is required to monotonically increase, starting from 1.
* This is to avoid a bad actor from abusing the sequence number on un-signed algorithm suites.
@@ -101,7 +137,10 @@ async function bodyDecrypt ({ buffer, getSubtleDecrypt, headerInfo }: BodyDecryp
* then the data could be significantly altered just by rearranging the frames.
* Non-framed data returns a sequenceNumber of 1.
*/
- needs(frameInfo.sequenceNumber === sequenceNumber, 'Encrypted body sequence out of order.')
+ needs(
+ frameInfo.sequenceNumber === sequenceNumber,
+ 'Encrypted body sequence out of order.'
+ )
clearBuffers.push(clearBlob)
readPos = frameInfo.readPos
@@ -116,15 +155,33 @@ async function bodyDecrypt ({ buffer, getSubtleDecrypt, headerInfo }: BodyDecryp
* non-framed decrypt. The names not-withstanding, this supports non-framed decrypt
* See decodeBodyHeader (it abstracts framed and non-framed body headers)
*/
-async function framedDecrypt ({ buffer, getSubtleDecrypt, headerInfo, readPos }: FramedDecryptOptions) {
- const { messageHeader: { messageId } } = headerInfo
+async function framedDecrypt({
+ buffer,
+ getSubtleDecrypt,
+ headerInfo,
+ readPos,
+}: FramedDecryptOptions) {
+ const {
+ messageHeader: { messageId },
+ } = headerInfo
const frameInfo = decodeBodyHeader(buffer, headerInfo, readPos)
if (!frameInfo) throw new Error('Format Error')
const cipherLength = frameInfo.contentLength + frameInfo.tagLength / 8
const contentString = messageAADContentString(frameInfo)
- const messageAdditionalData = messageAAD(messageId, contentString, frameInfo.sequenceNumber, frameInfo.contentLength)
- const cipherBlob = buffer.slice(frameInfo.readPos, frameInfo.readPos + cipherLength)
- const clearBlob = await getSubtleDecrypt(frameInfo.iv, messageAdditionalData)(cipherBlob)
+ const messageAdditionalData = messageAAD(
+ messageId,
+ contentString,
+ frameInfo.sequenceNumber,
+ frameInfo.contentLength
+ )
+ const cipherBlob = buffer.slice(
+ frameInfo.readPos,
+ frameInfo.readPos + cipherLength
+ )
+ const clearBlob = await getSubtleDecrypt(
+ frameInfo.iv,
+ messageAdditionalData
+ )(cipherBlob)
frameInfo.readPos += cipherLength
return { clearBlob, frameInfo }
}
diff --git a/modules/decrypt-node/package.json b/modules/decrypt-node/package.json
index f451a3efd..066961eaf 100644
--- a/modules/decrypt-node/package.json
+++ b/modules/decrypt-node/package.json
@@ -4,7 +4,9 @@
"scripts": {
"prepublishOnly": "npm run build",
"build": "tsc -b tsconfig.json && tsc -b tsconfig.module.json",
- "lint": "standard src/*.ts test/**/*.ts",
+ "lint": "run-s lint-*",
+ "lint-eslint": "npx eslint modules/**/src/*.ts modules/**/test/**/*.ts",
+ "lint-prettier": "prettier -c modules/**/src/*.ts modules/**/test/**/*.ts",
"mocha": "mocha --require ts-node/register test/**/*test.ts",
"test": "npm run lint && npm run coverage",
"coverage": "nyc -e .ts npm run mocha"
diff --git a/modules/decrypt-node/src/decipher_stream.ts b/modules/decrypt-node/src/decipher_stream.ts
index b1e5cf1ab..81766bce4 100644
--- a/modules/decrypt-node/src/decipher_stream.ts
+++ b/modules/decrypt-node/src/decipher_stream.ts
@@ -3,21 +3,20 @@
// @ts-ignore
import { Transform as PortableTransform } from 'readable-stream'
-import { Transform } from 'stream' // eslint-disable-line no-unused-vars
+import { Transform } from 'stream'
import {
needs,
- GetDecipher, // eslint-disable-line no-unused-vars
- AwsEsdkJsDecipherGCM // eslint-disable-line no-unused-vars
+ GetDecipher,
+ AwsEsdkJsDecipherGCM,
} from '@aws-crypto/material-management-node'
-import {
- aadFactory,
- ContentType // eslint-disable-line no-unused-vars
-} from '@aws-crypto/serialize'
+import { aadFactory, ContentType } from '@aws-crypto/serialize'
import { VerifyStream } from './verify_stream'
const fromUtf8 = (input: string) => Buffer.from(input, 'utf8')
const aadUtility = aadFactory(fromUtf8)
-const PortableTransformWithType = ( Transform>PortableTransform)
+const PortableTransformWithType = PortableTransform as new (
+ ...args: any[]
+) => Transform
export interface DecipherInfo {
messageId: Buffer
@@ -39,17 +38,17 @@ export interface BodyInfo {
isFinalFrame: boolean
}
-const ioTick = () => new Promise(resolve => setImmediate(resolve))
-const noop = () => {}
+const ioTick = async () => new Promise((resolve) => setImmediate(resolve))
+const noop = () => {} // eslint-disable-line @typescript-eslint/no-empty-function
-export function getDecipherStream () {
+export function getDecipherStream() {
let decipherInfo: DecipherInfo
let decipherState: DecipherState = {} as any
let pathologicalDrain: Function = noop
- let frameComplete: Function|false = false
+ let frameComplete: Function | false = false
return new (class DecipherStream extends PortableTransformWithType {
- constructor () {
+ constructor() {
super()
this.on('pipe', (source: VerifyStream) => {
/* Precondition: The source must be a VerifyStream to emit the required events. */
@@ -59,32 +58,46 @@ export function getDecipherStream () {
decipherInfo = info
})
.on('BodyInfo', this._onBodyHeader)
- .on('AuthTag', async (authTag: Buffer, next: Function) => {
- try {
- await this._onAuthTag(authTag, next)
- } catch (e) {
- this.emit('error', e)
- }
+ .on('AuthTag', (authTag: Buffer, next: Function) => {
+ this._onAuthTag(authTag, next).catch((e) => this.emit('error', e))
})
})
}
- _onBodyHeader = ({ iv, contentLength, sequenceNumber, isFinalFrame }: BodyInfo) => {
+ _onBodyHeader = ({
+ iv,
+ contentLength,
+ sequenceNumber,
+ isFinalFrame,
+ }: BodyInfo) => {
/* Precondition: decipherInfo must be set before BodyInfo is sent. */
needs(decipherInfo, 'Malformed State.')
/* Precondition: Ciphertext must not be flowing before a BodyHeader is processed. */
needs(!decipherState.decipher, 'Malformed State.')
const { messageId, contentType, getDecipher } = decipherInfo
- const aadString = aadUtility.messageAADContentString({ contentType, isFinalFrame })
- const messageAAD = aadUtility.messageAAD(messageId, aadString, sequenceNumber, contentLength)
- const decipher = getDecipher(iv)
- .setAAD(Buffer.from(messageAAD.buffer, messageAAD.byteOffset, messageAAD.byteLength))
+ const aadString = aadUtility.messageAADContentString({
+ contentType,
+ isFinalFrame,
+ })
+ const messageAAD = aadUtility.messageAAD(
+ messageId,
+ aadString,
+ sequenceNumber,
+ contentLength
+ )
+ const decipher = getDecipher(iv).setAAD(
+ Buffer.from(
+ messageAAD.buffer,
+ messageAAD.byteOffset,
+ messageAAD.byteLength
+ )
+ )
const content: Buffer[] = []
decipherState = { decipher, content, contentLength }
}
- _transform (chunk: any, _encoding: string, callback: Function) {
+ _transform(chunk: any, _encoding: string, callback: Function) {
/* Precondition: BodyHeader must be parsed before frame data. */
needs(decipherState.decipher, 'Malformed State.')
@@ -107,7 +120,7 @@ export function getDecipherStream () {
}
}
- _read (size: number) {
+ _read(size: number) {
/* The _onAuthTag decrypts and pushes the encrypted frame.
* If this.push returns false then this stream
* should wait until the destination stream calls read.
@@ -125,7 +138,7 @@ export function getDecipherStream () {
super._read(size)
}
- _onAuthTag = async (authTag: Buffer, next:Function) => {
+ _onAuthTag = async (authTag: Buffer, next: Function) => {
const { decipher, content, contentLength } = decipherState
/* Precondition: _onAuthTag must be called only after a frame has been accumulated.
* However there is an edge case. The final frame _can_ be zero length.
@@ -169,7 +182,9 @@ export function getDecipherStream () {
/* back pressure: if push returns false, wait until _read
* has been called.
*/
- await new Promise(resolve => { pathologicalDrain = resolve })
+ await new Promise((resolve) => {
+ pathologicalDrain = resolve
+ })
}
}
@@ -190,7 +205,7 @@ export function getDecipherStream () {
frameComplete = false
}
- _destroy () {
+ _destroy() {
// It is possible to have to destroy the stream before
// decipherInfo is set. Especially if the HeaderAuth
// is not valid.
diff --git a/modules/decrypt-node/src/decrypt.ts b/modules/decrypt-node/src/decrypt.ts
index 1adeaf8b2..fb605b709 100644
--- a/modules/decrypt-node/src/decrypt.ts
+++ b/modules/decrypt-node/src/decrypt.ts
@@ -2,15 +2,15 @@
// SPDX-License-Identifier: Apache-2.0
import {
- NodeMaterialsManager, // eslint-disable-line no-unused-vars
- KeyringNode // eslint-disable-line no-unused-vars
+ NodeMaterialsManager,
+ KeyringNode,
} from '@aws-crypto/material-management-node'
import { decryptStream } from './decrypt_stream'
// @ts-ignore
import { finished } from 'readable-stream'
-import { Readable, Duplex } from 'stream' // eslint-disable-line no-unused-vars
-import { MessageHeader } from '@aws-crypto/serialize' // eslint-disable-line no-unused-vars
+import { Readable, Duplex } from 'stream'
+import { MessageHeader } from '@aws-crypto/serialize'
export interface DecryptOutput {
plaintext: Buffer
@@ -22,17 +22,19 @@ export interface DecryptOptions {
maxBodySize?: number
}
-export async function decrypt (
- cmm: NodeMaterialsManager|KeyringNode,
- ciphertext: Buffer|Uint8Array|Readable|string|NodeJS.ReadableStream,
- { encoding, maxBodySize } : DecryptOptions = {}
+export async function decrypt(
+ cmm: NodeMaterialsManager | KeyringNode,
+ ciphertext: Buffer | Uint8Array | Readable | string | NodeJS.ReadableStream,
+ { encoding, maxBodySize }: DecryptOptions = {}
): Promise {
const stream = decryptStream(cmm, { maxBodySize })
const plaintext: Buffer[] = []
- let messageHeader: MessageHeader|false = false
+ let messageHeader: MessageHeader | false = false
stream
- .once('MessageHeader', (header: MessageHeader) => { messageHeader = header })
+ .once('MessageHeader', (header: MessageHeader) => {
+ messageHeader = header
+ })
.on('data', (chunk: Buffer) => plaintext.push(chunk))
// This will check both Uint8Array|Buffer
@@ -51,12 +53,12 @@ export async function decrypt (
return {
plaintext: Buffer.concat(plaintext),
- messageHeader
+ messageHeader,
}
}
-function finishedAsync (stream: Duplex) {
+async function finishedAsync(stream: Duplex) {
return new Promise((resolve, reject) => {
- finished(stream, (err: Error) => err ? reject(err) : resolve())
+ finished(stream, (err: Error) => (err ? reject(err) : resolve()))
})
}
diff --git a/modules/decrypt-node/src/decrypt_stream.ts b/modules/decrypt-node/src/decrypt_stream.ts
index a6e047989..28a0c2d63 100644
--- a/modules/decrypt-node/src/decrypt_stream.ts
+++ b/modules/decrypt-node/src/decrypt_stream.ts
@@ -4,13 +4,13 @@
import {
NodeDefaultCryptographicMaterialsManager,
KeyringNode,
- NodeMaterialsManager // eslint-disable-line no-unused-vars
+ NodeMaterialsManager,
} from '@aws-crypto/material-management-node'
import { ParseHeaderStream } from './parse_header_stream'
import { VerifyStream } from './verify_stream'
import { getDecipherStream } from './decipher_stream'
import Duplexify from 'duplexify'
-import { Duplex } from 'stream' // eslint-disable-line no-unused-vars
+import { Duplex } from 'stream'
// @ts-ignore
import { pipeline, PassThrough } from 'readable-stream'
@@ -19,32 +19,39 @@ export interface DecryptStreamOptions {
maxBodySize?: number
}
-export function decryptStream (
- cmm: KeyringNode|NodeMaterialsManager,
- { maxBodySize } : DecryptStreamOptions = {}
+export function decryptStream(
+ cmm: KeyringNode | NodeMaterialsManager,
+ { maxBodySize }: DecryptStreamOptions = {}
): Duplex {
/* If the cmm is a Keyring, wrap it with NodeDefaultCryptographicMaterialsManager. */
- cmm = cmm instanceof KeyringNode
- ? new NodeDefaultCryptographicMaterialsManager(cmm)
- : cmm
+ cmm =
+ cmm instanceof KeyringNode
+ ? new NodeDefaultCryptographicMaterialsManager(cmm)
+ : cmm
const parseHeaderStream = new ParseHeaderStream(cmm)
const verifyStream = new VerifyStream({ maxBodySize })
const decipherStream = getDecipherStream()
+ const stream = new Duplexify(parseHeaderStream, decipherStream)
/* pipeline will _either_ stream.destroy or the callback.
* decipherStream uses destroy to dispose the material.
* So I tack a pass though stream onto the end.
*/
- pipeline(parseHeaderStream, verifyStream, decipherStream, new PassThrough(), (err: Error) => {
- if (err) stream.emit('error', err)
- })
-
- const stream = new Duplexify(parseHeaderStream, decipherStream)
+ pipeline(
+ parseHeaderStream,
+ verifyStream,
+ decipherStream,
+ new PassThrough(),
+ (err: Error) => {
+ if (err) stream.emit('error', err)
+ }
+ )
// Forward header events
- parseHeaderStream
- .once('MessageHeader', header => stream.emit('MessageHeader', header))
+ parseHeaderStream.once('MessageHeader', (header) =>
+ stream.emit('MessageHeader', header)
+ )
return stream
}
diff --git a/modules/decrypt-node/src/parse_header_stream.ts b/modules/decrypt-node/src/parse_header_stream.ts
index 9a416bf16..2987d015e 100644
--- a/modules/decrypt-node/src/parse_header_stream.ts
+++ b/modules/decrypt-node/src/parse_header_stream.ts
@@ -3,20 +3,21 @@
// @ts-ignore
import { Transform as PortableTransform } from 'readable-stream'
-import { Transform } from 'stream' // eslint-disable-line no-unused-vars
+import { Transform } from 'stream'
import {
NodeAlgorithmSuite,
- NodeMaterialsManager, // eslint-disable-line no-unused-vars
- getDecryptionHelper
+ NodeMaterialsManager,
+ getDecryptionHelper,
} from '@aws-crypto/material-management-node'
import { deserializeFactory, kdfInfo } from '@aws-crypto/serialize'
-import { VerifyInfo } from './verify_stream' // eslint-disable-line no-unused-vars
+import { VerifyInfo } from './verify_stream'
-const toUtf8 = (input: Uint8Array) => Buffer
- .from(input.buffer, input.byteOffset, input.byteLength)
- .toString('utf8')
+const toUtf8 = (input: Uint8Array) =>
+ Buffer.from(input.buffer, input.byteOffset, input.byteLength).toString('utf8')
const deserialize = deserializeFactory(toUtf8, NodeAlgorithmSuite)
-const PortableTransformWithType = ( Transform>PortableTransform)
+const PortableTransformWithType = PortableTransform as new (
+ ...args: any[]
+) => Transform
interface HeaderState {
buffer: Buffer
@@ -25,15 +26,18 @@ interface HeaderState {
export class ParseHeaderStream extends PortableTransformWithType {
private materialsManager!: NodeMaterialsManager
private _headerState: HeaderState
- constructor (cmm: NodeMaterialsManager) {
+ constructor(cmm: NodeMaterialsManager) {
super()
- Object.defineProperty(this, 'materialsManager', { value: cmm, enumerable: true })
+ Object.defineProperty(this, 'materialsManager', {
+ value: cmm,
+ enumerable: true,
+ })
this._headerState = {
- buffer: Buffer.alloc(0)
+ buffer: Buffer.alloc(0),
}
}
- _transform (chunk: any, encoding: string, callback: Function) {
+ _transform(chunk: any, encoding: string, callback: Function) {
const { buffer } = this._headerState
const headerBuffer = Buffer.concat([buffer, chunk])
const headerInfo = deserialize.deserializeMessageHeader(headerBuffer)
@@ -53,24 +57,44 @@ export class ParseHeaderStream extends PortableTransformWithType {
.then((material) => {
this._headerState.buffer = Buffer.alloc(0) // clear the Buffer...
- const { kdfGetDecipher, getVerify, dispose } = getDecryptionHelper(material)
+ const { kdfGetDecipher, getVerify, dispose } = getDecryptionHelper(
+ material
+ )
const info = kdfInfo(messageHeader.suiteId, messageHeader.messageId)
const getDecipher = kdfGetDecipher(info)
const headerAuth = getDecipher(headerIv)
- headerAuth.setAAD(Buffer.from(rawHeader.buffer, rawHeader.byteOffset, rawHeader.byteLength))
- headerAuth.setAuthTag(Buffer.from(headerAuthTag.buffer, headerAuthTag.byteOffset, headerAuthTag.byteLength))
+ headerAuth.setAAD(
+ Buffer.from(
+ rawHeader.buffer,
+ rawHeader.byteOffset,
+ rawHeader.byteLength
+ )
+ )
+ headerAuth.setAuthTag(
+ Buffer.from(
+ headerAuthTag.buffer,
+ headerAuthTag.byteOffset,
+ headerAuthTag.byteLength
+ )
+ )
headerAuth.update(Buffer.alloc(0))
headerAuth.final() // will throw if invalid
const verify = getVerify ? getVerify() : void 0
- const verifyInfo: VerifyInfo = { headerInfo, getDecipher, verify, dispose }
+ const verifyInfo: VerifyInfo = {
+ headerInfo,
+ getDecipher,
+ verify,
+ dispose,
+ }
this.emit('VerifyInfo', verifyInfo)
this.emit('MessageHeader', headerInfo.messageHeader)
// The header is parsed, pass control
- const readPos = rawHeader.byteLength + headerIv.byteLength + headerAuthTag.byteLength
+ const readPos =
+ rawHeader.byteLength + headerIv.byteLength + headerAuthTag.byteLength
const tail = headerBuffer.slice(readPos)
/* needs calls in downstream _transform streams will throw.
* But streams are async.
@@ -86,6 +110,6 @@ export class ParseHeaderStream extends PortableTransformWithType {
// flush the tail. Stream control is now in the verify and decrypt streams
return setImmediate(() => this._transform(tail, encoding, callback))
})
- .catch(err => callback(err))
+ .catch((err) => callback(err))
}
}
diff --git a/modules/decrypt-node/src/verify_stream.ts b/modules/decrypt-node/src/verify_stream.ts
index 521a6c31e..3bfbdc8be 100644
--- a/modules/decrypt-node/src/verify_stream.ts
+++ b/modules/decrypt-node/src/verify_stream.ts
@@ -3,23 +3,25 @@
// @ts-ignore
import { Transform as PortableTransform } from 'readable-stream'
-import { Transform } from 'stream' // eslint-disable-line no-unused-vars
+import { Transform } from 'stream'
import {
needs,
- GetVerify, // eslint-disable-line no-unused-vars
- GetDecipher // eslint-disable-line no-unused-vars
+ GetVerify,
+ GetDecipher,
} from '@aws-crypto/material-management-node'
import {
deserializeSignature,
decodeBodyHeader,
- BodyHeader, // eslint-disable-line no-unused-vars
- HeaderInfo // eslint-disable-line no-unused-vars
+ BodyHeader,
+ HeaderInfo,
} from '@aws-crypto/serialize'
import { ParseHeaderStream } from './parse_header_stream'
-import { DecipherInfo } from './decipher_stream' // eslint-disable-line no-unused-vars
+import { DecipherInfo } from './decipher_stream'
type AWSVerify = ReturnType
-const PortableTransformWithType = ( Transform>PortableTransform)
+const PortableTransformWithType = PortableTransform as new (
+ ...args: any[]
+) => Transform
export interface VerifyInfo {
headerInfo: HeaderInfo
@@ -46,15 +48,21 @@ export class VerifyStream extends PortableTransformWithType {
buffer: Buffer.alloc(0),
authTagBuffer: Buffer.alloc(0),
signatureInfo: Buffer.alloc(0),
- sequenceNumber: 0
+ sequenceNumber: 0,
}
private _verify?: AWSVerify
private _maxBodySize?: number
- constructor ({ maxBodySize }: VerifyStreamOptions) {
+ constructor({ maxBodySize }: VerifyStreamOptions) {
super()
/* Precondition: VerifyStream requires maxBodySize must be falsey or a number. */
- needs(!maxBodySize || typeof maxBodySize === 'number', 'Unsupported MaxBodySize.')
- Object.defineProperty(this, '_maxBodySize', { value: maxBodySize, enumerable: true })
+ needs(
+ !maxBodySize || typeof maxBodySize === 'number',
+ 'Unsupported MaxBodySize.'
+ )
+ Object.defineProperty(this, '_maxBodySize', {
+ value: maxBodySize,
+ enumerable: true,
+ })
this.on('pipe', (source: ParseHeaderStream) => {
/* Precondition: The source must a ParseHeaderStream emit the required events. */
@@ -68,26 +76,38 @@ export class VerifyStream extends PortableTransformWithType {
*/
if (verify) {
const { rawHeader, headerIv, headerAuthTag } = headerInfo
- ;[rawHeader, headerIv, headerAuthTag].forEach(e => verify.update(e))
+ ;[rawHeader, headerIv, headerAuthTag].forEach((e) => verify.update(e))
}
- Object.defineProperty(this, '_headerInfo', { value: headerInfo, enumerable: true })
- Object.defineProperty(this, '_verify', { value: verify, enumerable: true })
+ Object.defineProperty(this, '_headerInfo', {
+ value: headerInfo,
+ enumerable: true,
+ })
+ Object.defineProperty(this, '_verify', {
+ value: verify,
+ enumerable: true,
+ })
const decipherInfo: DecipherInfo = {
- // @ts-ignore
- messageId: Buffer.from(messageId.buffer, messageId.byteOffset, messageId.byteLength),
+ messageId: Buffer.from(
+ (messageId as Uint8Array).buffer || messageId,
+ (messageId as Uint8Array).byteOffset || 0,
+ messageId.byteLength
+ ),
contentType,
getDecipher,
- dispose
+ dispose,
}
this.emit('DecipherInfo', decipherInfo)
})
})
}
- _transform (chunk: Buffer, enc: string, callback: Function): any {
+ _transform(chunk: Buffer, enc: string, callback: Function): any {
/* Precondition: VerifyInfo must have initialized the stream. */
- needs(this._headerInfo, 'VerifyStream not configured, VerifyInfo event not yet received.')
+ needs(
+ this._headerInfo,
+ 'VerifyStream not configured, VerifyInfo event not yet received.'
+ )
// BodyHeader
const state = this._verifyState
@@ -106,7 +126,10 @@ export class VerifyStream extends PortableTransformWithType {
* Before returning *any* cleartext, the stream **MUST** verify the decryption.
* This means that I must buffer the message until the AuthTag is reached.
*/
- needs(!this._maxBodySize || this._maxBodySize >= frameHeader.contentLength, 'maxBodySize exceeded.')
+ needs(
+ !this._maxBodySize || this._maxBodySize >= frameHeader.contentLength,
+ 'maxBodySize exceeded.'
+ )
/* Keeping track of the sequence number myself. */
state.sequenceNumber += 1
@@ -117,7 +140,10 @@ export class VerifyStream extends PortableTransformWithType {
* then the data could be significantly altered just by rearranging the frames.
* Non-framed data returns a sequenceNumber of 1.
*/
- needs(frameHeader.sequenceNumber === state.sequenceNumber, 'Encrypted body sequence out of order.')
+ needs(
+ frameHeader.sequenceNumber === state.sequenceNumber,
+ 'Encrypted body sequence out of order.'
+ )
if (this._verify) {
this._verify.update(frameBuffer.slice(0, frameHeader.readPos))
@@ -154,7 +180,10 @@ export class VerifyStream extends PortableTransformWithType {
state.authTagBuffer = Buffer.concat([authTagBuffer, chunk])
return callback()
} else {
- const finalAuthTagBuffer = Buffer.concat([authTagBuffer, chunk], tagLengthBytes)
+ const finalAuthTagBuffer = Buffer.concat(
+ [authTagBuffer, chunk],
+ tagLengthBytes
+ )
if (this._verify) {
this._verify.update(finalAuthTagBuffer)
}
@@ -172,7 +201,11 @@ export class VerifyStream extends PortableTransformWithType {
/* Overwriting the _transform function.
* Data flow control is not handled here.
*/
- this._transform = (chunk: Buffer, _enc: string, callback: Function) => {
+ this._transform = (
+ chunk: Buffer,
+ _enc: string,
+ callback: Function
+ ) => {
if (chunk.length) {
state.signatureInfo = Buffer.concat([state.signatureInfo, chunk])
}
@@ -202,7 +235,7 @@ export class VerifyStream extends PortableTransformWithType {
callback()
}
- push (chunk: any, encoding?: string | undefined): boolean {
+ push(chunk: any, encoding?: string | undefined): boolean {
// Typescript???? this._verify instanceof Verify is better....
if (this._verify && chunk) {
this._verify.update(chunk)
@@ -210,11 +243,13 @@ export class VerifyStream extends PortableTransformWithType {
return super.push(chunk, encoding)
}
- _flush (callback: Function) {
+ _flush(callback: Function) {
/* Check for early return (Postcondition): If there is no verify stream do not attempt to verify. */
if (!this._verify) return callback()
const { signatureInfo } = this._verifyState
- const { buffer, byteOffset, byteLength } = deserializeSignature(signatureInfo)
+ const { buffer, byteOffset, byteLength } = deserializeSignature(
+ signatureInfo
+ )
const signature = Buffer.from(buffer, byteOffset, byteLength)
const isVerified = this._verify.awsCryptoVerify(signature)
/* Postcondition: The signature must be valid. */
diff --git a/modules/encrypt-browser/package.json b/modules/encrypt-browser/package.json
index b076c51c0..47cf2e554 100644
--- a/modules/encrypt-browser/package.json
+++ b/modules/encrypt-browser/package.json
@@ -3,7 +3,9 @@
"version": "1.1.1",
"scripts": {
"prepublishOnly": "tsc -p tsconfig.json && tsc -p tsconfig.module.json",
- "lint": "standard src/*.ts test/**/*.ts",
+ "lint": "run-s lint-*",
+ "lint-eslint": "npx eslint modules/**/src/*.ts modules/**/test/**/*.ts",
+ "lint-prettier": "prettier -c modules/**/src/*.ts modules/**/test/**/*.ts",
"karma": "karma start karma.conf.js",
"test": "npm run lint && npm run coverage",
"coverage": "npm run karma && nyc report --exclude-after-remap false -t .karma_output --check-coverage"
diff --git a/modules/encrypt-browser/src/encrypt.ts b/modules/encrypt-browser/src/encrypt.ts
index b0c8af710..49ab0625c 100644
--- a/modules/encrypt-browser/src/encrypt.ts
+++ b/modules/encrypt-browser/src/encrypt.ts
@@ -3,21 +3,21 @@
import {
WebCryptoAlgorithmSuite,
- WebCryptoDefaultCryptographicMaterialsManager, // eslint-disable-line no-unused-vars
- WebCryptoEncryptionRequest, // eslint-disable-line no-unused-vars
- EncryptionContext, // eslint-disable-line no-unused-vars
+ WebCryptoDefaultCryptographicMaterialsManager,
+ WebCryptoEncryptionRequest,
+ EncryptionContext,
AlgorithmSuiteIdentifier,
getEncryptHelper,
KeyringWebCrypto,
needs,
- WebCryptoMaterialsManager // eslint-disable-line no-unused-vars
+ WebCryptoMaterialsManager,
} from '@aws-crypto/material-management-browser'
import {
serializeFactory,
aadFactory,
kdfInfo,
concatBuffers,
- MessageHeader, // eslint-disable-line no-unused-vars
+ MessageHeader,
SerializationVersion,
ObjectType,
ContentType,
@@ -25,7 +25,7 @@ import {
FRAME_LENGTH,
MESSAGE_ID_LENGTH,
raw2der,
- Maximum
+ Maximum,
} from '@aws-crypto/serialize'
import { fromUtf8 } from '@aws-sdk/util-utf8-browser'
import { getWebCryptoBackend } from '@aws-crypto/web-crypto-backend'
@@ -45,34 +45,48 @@ export interface EncryptResult {
result: Uint8Array
}
-export async function encrypt (
- cmm: KeyringWebCrypto|WebCryptoMaterialsManager,
+export async function encrypt(
+ cmm: KeyringWebCrypto | WebCryptoMaterialsManager,
plaintext: Uint8Array,
- { suiteId, encryptionContext = {}, frameLength = FRAME_LENGTH }: EncryptInput = {}
+ {
+ suiteId,
+ encryptionContext = {},
+ frameLength = FRAME_LENGTH,
+ }: EncryptInput = {}
): Promise {
/* Precondition: The frameLength must be less than the maximum frame size for browser encryption. */
- needs(frameLength > 0 && Maximum.FRAME_SIZE >= frameLength, `frameLength out of bounds: 0 > frameLength >= ${Maximum.FRAME_SIZE}`)
+ needs(
+ frameLength > 0 && Maximum.FRAME_SIZE >= frameLength,
+ `frameLength out of bounds: 0 > frameLength >= ${Maximum.FRAME_SIZE}`
+ )
const backend = await getWebCryptoBackend()
if (!backend) throw new Error('No supported crypto backend')
/* If the cmm is a Keyring, wrap it with WebCryptoDefaultCryptographicMaterialsManager. */
- cmm = cmm instanceof KeyringWebCrypto
- ? new WebCryptoDefaultCryptographicMaterialsManager(cmm)
- : cmm
+ cmm =
+ cmm instanceof KeyringWebCrypto
+ ? new WebCryptoDefaultCryptographicMaterialsManager(cmm)
+ : cmm
// Subtle Crypto functions are all one-shot so all the plaintext needs to be available.
const plaintextLength = plaintext.byteLength
- const suite = suiteId ? new WebCryptoAlgorithmSuite(suiteId) : new WebCryptoAlgorithmSuite(AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384)
+ const suite = suiteId
+ ? new WebCryptoAlgorithmSuite(suiteId)
+ : new WebCryptoAlgorithmSuite(
+ AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384
+ )
const encryptionRequest: WebCryptoEncryptionRequest = {
suite,
encryptionContext,
- plaintextLength
+ plaintextLength,
}
const material = await cmm.getEncryptionMaterials(encryptionRequest)
- const { kdfGetSubtleEncrypt, subtleSign, dispose } = await getEncryptHelper(material)
+ const { kdfGetSubtleEncrypt, subtleSign, dispose } = await getEncryptHelper(
+ material
+ )
const messageId = await backend.randomValues(MESSAGE_ID_LENGTH)
@@ -87,7 +101,7 @@ export async function encrypt (
encryptedDataKeys: material.encryptedDataKeys,
contentType: ContentType.FRAMED_DATA,
headerIvLength: ivLength,
- frameLength
+ frameLength,
}
const header = serialize.serializeMessageHeader(messageHeader)
@@ -95,7 +109,10 @@ export async function encrypt (
const getSubtleEncrypt = kdfGetSubtleEncrypt(info)
const headerAuthIv = serialize.headerAuthIv(ivLength)
- const headerAuthTag = await getSubtleEncrypt(headerAuthIv, header)(new Uint8Array(0))
+ const headerAuthTag = await getSubtleEncrypt(
+ headerAuthIv,
+ header
+ )(new Uint8Array(0))
const numberOfFrames = Math.ceil(plaintextLength / frameLength)
/* The final frame has a variable length.
@@ -103,16 +120,24 @@ export async function encrypt (
* So I calculate how much of a frame I should have at the end.
* This value will NEVER be larger than the frameLength.
*/
- const finalFrameLength = frameLength - ((numberOfFrames * frameLength) - plaintextLength)
+ const finalFrameLength =
+ frameLength - (numberOfFrames * frameLength - plaintextLength)
const bodyContent = []
- for (let sequenceNumber = 1; numberOfFrames >= sequenceNumber; sequenceNumber += 1) {
+ for (
+ let sequenceNumber = 1;
+ numberOfFrames >= sequenceNumber;
+ sequenceNumber += 1
+ ) {
const frameIv = serialize.frameIv(ivLength, sequenceNumber)
const isFinalFrame = sequenceNumber === numberOfFrames
const frameHeader = isFinalFrame
? serialize.finalFrameHeader(sequenceNumber, frameIv, finalFrameLength)
: serialize.frameHeader(sequenceNumber, frameIv)
- const contentString = messageAADContentString({ contentType: messageHeader.contentType, isFinalFrame })
+ const contentString = messageAADContentString({
+ contentType: messageHeader.contentType,
+ isFinalFrame,
+ })
const messageAdditionalData = messageAAD(
messageId,
contentString,
@@ -129,7 +154,10 @@ export async function encrypt (
(sequenceNumber - 1) * frameLength,
isFinalFrame ? finalFrameLength : frameLength
)
- const cipherBufferAndAuthTag = await getSubtleEncrypt(frameIv, messageAdditionalData)(framePlaintext)
+ const cipherBufferAndAuthTag = await getSubtleEncrypt(
+ frameIv,
+ messageAdditionalData
+ )(framePlaintext)
bodyContent.push(frameHeader, cipherBufferAndAuthTag)
}
@@ -145,7 +173,10 @@ export async function encrypt (
if (typeof subtleSign === 'function') {
const signatureArrayBuffer = await subtleSign(result)
- const derSignature = raw2der(new Uint8Array(signatureArrayBuffer), material.suite)
+ const derSignature = raw2der(
+ new Uint8Array(signatureArrayBuffer),
+ material.suite
+ )
const signatureInfo = serializeSignatureInfo(derSignature)
return { result: concatBuffers(result, signatureInfo), messageHeader }
} else {
diff --git a/modules/encrypt-node/package.json b/modules/encrypt-node/package.json
index f81fc0563..8fe7501b4 100644
--- a/modules/encrypt-node/package.json
+++ b/modules/encrypt-node/package.json
@@ -3,7 +3,9 @@
"version": "1.0.4",
"scripts": {
"prepublishOnly": "tsc -p tsconfig.json && tsc -p tsconfig.module.json",
- "lint": "standard src/*.ts test/**/*.ts",
+ "lint": "run-s lint-*",
+ "lint-eslint": "npx eslint modules/**/src/*.ts modules/**/test/**/*.ts",
+ "lint-prettier": "prettier -c modules/**/src/*.ts modules/**/test/**/*.ts",
"mocha": "mocha --require ts-node/register test/**/*test.ts",
"test": "npm run lint && npm run coverage",
"coverage": "nyc -e .ts npm run mocha"
diff --git a/modules/encrypt-node/src/encrypt.ts b/modules/encrypt-node/src/encrypt.ts
index 70bb1396f..35e050516 100644
--- a/modules/encrypt-node/src/encrypt.ts
+++ b/modules/encrypt-node/src/encrypt.ts
@@ -1,16 +1,13 @@
import {
- KeyringNode, // eslint-disable-line no-unused-vars
- NodeMaterialsManager // eslint-disable-line no-unused-vars
+ KeyringNode,
+ NodeMaterialsManager,
} from '@aws-crypto/material-management-node'
-import {
- encryptStream,
- EncryptStreamInput // eslint-disable-line no-unused-vars
-} from './encrypt_stream'
+import { encryptStream, EncryptStreamInput } from './encrypt_stream'
// @ts-ignore
import { finished } from 'readable-stream'
-import { Readable, Duplex } from 'stream' // eslint-disable-line no-unused-vars
-import { MessageHeader } from '@aws-crypto/serialize' // eslint-disable-line no-unused-vars
+import { Readable, Duplex } from 'stream'
+import { MessageHeader } from '@aws-crypto/serialize'
interface EncryptInput extends EncryptStreamInput {
encoding?: BufferEncoding
@@ -21,9 +18,9 @@ export interface EncryptOutput {
messageHeader: MessageHeader
}
-export async function encrypt (
- cmm: KeyringNode|NodeMaterialsManager,
- plaintext: Buffer|Uint8Array|Readable|string|NodeJS.ReadableStream,
+export async function encrypt(
+ cmm: KeyringNode | NodeMaterialsManager,
+ plaintext: Buffer | Uint8Array | Readable | string | NodeJS.ReadableStream,
op: EncryptInput = {}
): Promise {
const { encoding } = op
@@ -36,9 +33,11 @@ export async function encrypt (
const stream = encryptStream(cmm, op)
const result: Buffer[] = []
- let messageHeader: MessageHeader|false = false
+ let messageHeader: MessageHeader | false = false
stream
- .once('MessageHeader', header => { messageHeader = header })
+ .once('MessageHeader', (header) => {
+ messageHeader = header
+ })
.on('data', (chunk: Buffer) => result.push(chunk))
// This will check both Uint8Array|Buffer
@@ -55,12 +54,12 @@ export async function encrypt (
return {
result: Buffer.concat(result),
- messageHeader
+ messageHeader,
}
}
-function finishedAsync (stream: Duplex) {
+async function finishedAsync(stream: Duplex) {
return new Promise((resolve, reject) => {
- finished(stream, (err: Error) => err ? reject(err) : resolve())
+ finished(stream, (err: Error) => (err ? reject(err) : resolve()))
})
}
diff --git a/modules/encrypt-node/src/encrypt_stream.ts b/modules/encrypt-node/src/encrypt_stream.ts
index c0716f883..18e7aeff5 100644
--- a/modules/encrypt-node/src/encrypt_stream.ts
+++ b/modules/encrypt-node/src/encrypt_stream.ts
@@ -2,26 +2,35 @@
// SPDX-License-Identifier: Apache-2.0
import {
- NodeDefaultCryptographicMaterialsManager, NodeAlgorithmSuite, AlgorithmSuiteIdentifier, // eslint-disable-line no-unused-vars
- KeyringNode, NodeEncryptionMaterial, getEncryptHelper, EncryptionContext, // eslint-disable-line no-unused-vars
- NodeMaterialsManager, // eslint-disable-line no-unused-vars
- needs
+ NodeDefaultCryptographicMaterialsManager,
+ NodeAlgorithmSuite,
+ AlgorithmSuiteIdentifier,
+ KeyringNode,
+ NodeEncryptionMaterial,
+ getEncryptHelper,
+ EncryptionContext,
+ NodeMaterialsManager,
+ needs,
} from '@aws-crypto/material-management-node'
import { getFramedEncryptStream } from './framed_encrypt_stream'
import { SignatureStream } from './signature_stream'
import Duplexify from 'duplexify'
import { randomBytes } from 'crypto'
import {
- MessageHeader, // eslint-disable-line no-unused-vars
- serializeFactory, kdfInfo, ContentType, SerializationVersion, ObjectType,
+ MessageHeader,
+ serializeFactory,
+ kdfInfo,
+ ContentType,
+ SerializationVersion,
+ ObjectType,
FRAME_LENGTH,
MESSAGE_ID_LENGTH,
- Maximum
+ Maximum,
} from '@aws-crypto/serialize'
// @ts-ignore
import { pipeline } from 'readable-stream'
-import { Duplex } from 'stream' // eslint-disable-line no-unused-vars
+import { Duplex } from 'stream'
const fromUtf8 = (input: string) => Buffer.from(input, 'utf8')
const { serializeMessageHeader, headerAuthIv } = serializeFactory(fromUtf8)
@@ -40,50 +49,71 @@ export interface EncryptStreamInput {
* @param cmm NodeMaterialsManager|KeyringNode
* @param op EncryptStreamInput
*/
-export function encryptStream (
- cmm: KeyringNode|NodeMaterialsManager,
+export function encryptStream(
+ cmm: KeyringNode | NodeMaterialsManager,
op: EncryptStreamInput = {}
): Duplex {
- const { suiteId, encryptionContext = {}, frameLength = FRAME_LENGTH, plaintextLength } = op
+ const {
+ suiteId,
+ encryptionContext = {},
+ frameLength = FRAME_LENGTH,
+ plaintextLength,
+ } = op
/* Precondition: The frameLength must be less than the maximum frame size Node.js stream. */
- needs(frameLength > 0 && Maximum.FRAME_SIZE >= frameLength, `frameLength out of bounds: 0 > frameLength >= ${Maximum.FRAME_SIZE}`)
+ needs(
+ frameLength > 0 && Maximum.FRAME_SIZE >= frameLength,
+ `frameLength out of bounds: 0 > frameLength >= ${Maximum.FRAME_SIZE}`
+ )
/* If the cmm is a Keyring, wrap it with NodeDefaultCryptographicMaterialsManager. */
- cmm = cmm instanceof KeyringNode
- ? new NodeDefaultCryptographicMaterialsManager(cmm)
- : cmm
+ cmm =
+ cmm instanceof KeyringNode
+ ? new NodeDefaultCryptographicMaterialsManager(cmm)
+ : cmm
const suite = suiteId && new NodeAlgorithmSuite(suiteId)
const wrappingStream = new Duplexify()
- cmm.getEncryptionMaterials({ suite, encryptionContext, plaintextLength })
+ cmm
+ .getEncryptionMaterials({ suite, encryptionContext, plaintextLength })
.then(async (material) => {
const { dispose, getSigner } = getEncryptHelper(material)
- const { getCipher, messageHeader, rawHeader } = getEncryptionInfo(material, frameLength)
+ const { getCipher, messageHeader, rawHeader } = getEncryptionInfo(
+ material,
+ frameLength
+ )
wrappingStream.emit('MessageHeader', messageHeader)
- const encryptStream = getFramedEncryptStream(getCipher, messageHeader, dispose, plaintextLength)
+ const encryptStream = getFramedEncryptStream(
+ getCipher,
+ messageHeader,
+ dispose,
+ plaintextLength
+ )
const signatureStream = new SignatureStream(getSigner)
pipeline(encryptStream, signatureStream)
wrappingStream.setReadable(signatureStream)
// Flush the rawHeader through the signatureStream
- rawHeader.forEach(buff => signatureStream.write(buff))
+ rawHeader.forEach((buff) => signatureStream.write(buff))
// @ts-ignore until readable-stream exports v3 types...
wrappingStream.setWritable(encryptStream)
})
- .catch(err => wrappingStream.emit('error', err))
+ .catch((err) => wrappingStream.emit('error', err))
return wrappingStream
}
-export function getEncryptionInfo (material : NodeEncryptionMaterial, frameLength: number) {
+export function getEncryptionInfo(
+ material: NodeEncryptionMaterial,
+ frameLength: number
+) {
const { kdfGetCipher } = getEncryptHelper(material)
const { encryptionContext } = material
@@ -98,10 +128,12 @@ export function getEncryptionInfo (material : NodeEncryptionMaterial, frameLengt
encryptedDataKeys: Object.freeze(material.encryptedDataKeys), // freeze me please
contentType: ContentType.FRAMED_DATA,
headerIvLength: ivLength,
- frameLength
+ frameLength,
})
- const { buffer, byteOffset, byteLength } = serializeMessageHeader(messageHeader)
+ const { buffer, byteOffset, byteLength } = serializeMessageHeader(
+ messageHeader
+ )
const headerBuffer = Buffer.from(buffer, byteOffset, byteLength)
const info = kdfInfo(messageHeader.suiteId, messageHeader.messageId)
const getCipher = kdfGetCipher(info)
@@ -115,6 +147,6 @@ export function getEncryptionInfo (material : NodeEncryptionMaterial, frameLengt
return {
getCipher,
messageHeader,
- rawHeader: [headerBuffer, headerIv, headerAuth]
+ rawHeader: [headerBuffer, headerIv, headerAuth],
}
}
diff --git a/modules/encrypt-node/src/framed_encrypt_stream.ts b/modules/encrypt-node/src/framed_encrypt_stream.ts
index ddc906bb4..f7d60acfb 100644
--- a/modules/encrypt-node/src/framed_encrypt_stream.ts
+++ b/modules/encrypt-node/src/framed_encrypt_stream.ts
@@ -2,17 +2,18 @@
// SPDX-License-Identifier: Apache-2.0
import {
- serializeFactory, aadFactory,
- MessageHeader, // eslint-disable-line no-unused-vars
- Maximum
+ serializeFactory,
+ aadFactory,
+ MessageHeader,
+ Maximum,
} from '@aws-crypto/serialize'
// @ts-ignore
import { Transform as PortableTransform } from 'readable-stream'
-import { Transform } from 'stream' // eslint-disable-line no-unused-vars
+import { Transform } from 'stream'
import {
- GetCipher, // eslint-disable-line no-unused-vars
- AwsEsdkJsCipherGCM, // eslint-disable-line no-unused-vars
- needs
+ GetCipher,
+ AwsEsdkJsCipherGCM,
+ needs,
} from '@aws-crypto/material-management-node'
const fromUtf8 = (input: string) => Buffer.from(input, 'utf8')
@@ -30,16 +31,28 @@ interface EncryptFrame {
content: Buffer[]
bodyHeader: Buffer
headerSent?: boolean
- cipher: AwsEsdkJsCipherGCM,
+ cipher: AwsEsdkJsCipherGCM
isFinalFrame: boolean
}
+const PortableTransformWithType = PortableTransform as new (
+ ...args: any[]
+) => Transform
-const ioTick = () => new Promise(resolve => setImmediate(resolve))
-const noop = () => {}
+const ioTick = async () => new Promise((resolve) => setImmediate(resolve))
+const noop = () => {} // eslint-disable-line @typescript-eslint/no-empty-function
type ErrBack = (err?: Error) => void
-export function getFramedEncryptStream (getCipher: GetCipher, messageHeader: MessageHeader, dispose: Function, plaintextLength?: number) {
- let accumulatingFrame: AccumulatingFrame = { contentLength: 0, content: [], sequenceNumber: 1 }
+export function getFramedEncryptStream(
+ getCipher: GetCipher,
+ messageHeader: MessageHeader,
+ dispose: Function,
+ plaintextLength?: number
+) {
+ let accumulatingFrame: AccumulatingFrame = {
+ contentLength: 0,
+ content: [],
+ sequenceNumber: 1,
+ }
let pathologicalDrain: Function = noop
const { frameLength } = messageHeader
@@ -47,21 +60,28 @@ export function getFramedEncryptStream (getCipher: GetCipher, messageHeader: Mes
* The Maximum.BYTES_PER_MESSAGE is set to be within Number.MAX_SAFE_INTEGER
* See serialize/identifiers.ts enum Maximum for more details.
*/
- needs(!plaintextLength || (plaintextLength >= 0 && Maximum.BYTES_PER_MESSAGE >= plaintextLength), 'plaintextLength out of bounds.')
+ needs(
+ !plaintextLength ||
+ (plaintextLength >= 0 && Maximum.BYTES_PER_MESSAGE >= plaintextLength),
+ 'plaintextLength out of bounds.'
+ )
/* Keeping the messageHeader, accumulatingFrame and pathologicalDrain private is the intention here.
* It is already unlikely that these values could be touched in the current composition of streams,
* but a different composition may change this.
* Since we are handling the plain text here, it seems prudent to take extra measures.
*/
- return new (class FramedEncryptStream extends ( Transform>PortableTransform) {
- _transform (chunk: Buffer, encoding: string, callback: ErrBack) {
+ return new (class FramedEncryptStream extends PortableTransformWithType {
+ _transform(chunk: Buffer, encoding: string, callback: ErrBack) {
const contentLeft = frameLength - accumulatingFrame.contentLength
/* Precondition: Must not process more than plaintextLength.
* The plaintextLength is the MAXIMUM value that can be encrypted.
*/
- needs(!plaintextLength || (plaintextLength -= chunk.length) >= 0, 'Encrypted data exceeded plaintextLength.')
+ needs(
+ !plaintextLength || (plaintextLength -= chunk.length) >= 0,
+ 'Encrypted data exceeded plaintextLength.'
+ )
/* Check for early return (Postcondition): Have not accumulated a frame. */
if (contentLeft > chunk.length) {
@@ -81,7 +101,7 @@ export function getFramedEncryptStream (getCipher: GetCipher, messageHeader: Mes
pendingFrame: accumulatingFrame,
messageHeader,
getCipher,
- isFinalFrame: false
+ isFinalFrame: false,
})
// Reset frame state for next frame
@@ -89,7 +109,7 @@ export function getFramedEncryptStream (getCipher: GetCipher, messageHeader: Mes
accumulatingFrame = {
contentLength: 0,
content: [],
- sequenceNumber: sequenceNumber + 1
+ sequenceNumber: sequenceNumber + 1,
}
this._flushEncryptFrame(encryptFrame)
@@ -97,12 +117,12 @@ export function getFramedEncryptStream (getCipher: GetCipher, messageHeader: Mes
.catch(callback)
}
- _flush (callback: ErrBack) {
+ _flush(callback: ErrBack) {
const encryptFrame = getEncryptFrame({
pendingFrame: accumulatingFrame,
messageHeader,
getCipher,
- isFinalFrame: true
+ isFinalFrame: true,
})
this._flushEncryptFrame(encryptFrame)
@@ -110,11 +130,11 @@ export function getFramedEncryptStream (getCipher: GetCipher, messageHeader: Mes
.catch(callback)
}
- _destroy () {
+ _destroy() {
dispose()
}
- _read (size: number) {
+ _read(size: number) {
super._read(size)
/* The _flushEncryptFrame encrypts and pushes the frame.
* If this.push returns false then this stream
@@ -131,7 +151,7 @@ export function getFramedEncryptStream (getCipher: GetCipher, messageHeader: Mes
pathologicalDrain = noop
}
- async _flushEncryptFrame (encryptingFrame: EncryptFrame) {
+ async _flushEncryptFrame(encryptingFrame: EncryptFrame) {
const { content, cipher, bodyHeader, isFinalFrame } = encryptingFrame
this.push(bodyHeader)
@@ -152,14 +172,19 @@ export function getFramedEncryptStream (getCipher: GetCipher, messageHeader: Mes
/* Push the authTag onto the end. Yes, I am abusing the name. */
cipherContent.push(cipher.getAuthTag())
- needs(frameSize === frameLength || (isFinalFrame && frameLength >= frameSize), 'Malformed frame')
+ needs(
+ frameSize === frameLength || (isFinalFrame && frameLength >= frameSize),
+ 'Malformed frame'
+ )
for (const cipherText of cipherContent) {
if (!this.push(cipherText)) {
/* back pressure: if push returns false, wait until _read
* has been called.
*/
- await new Promise(resolve => { pathologicalDrain = resolve })
+ await new Promise((resolve) => {
+ pathologicalDrain = resolve
+ })
}
}
@@ -169,13 +194,13 @@ export function getFramedEncryptStream (getCipher: GetCipher, messageHeader: Mes
}
type EncryptFrameInput = {
- pendingFrame: AccumulatingFrame,
- messageHeader: MessageHeader,
- getCipher: GetCipher,
+ pendingFrame: AccumulatingFrame
+ messageHeader: MessageHeader
+ getCipher: GetCipher
isFinalFrame: boolean
}
-export function getEncryptFrame (input: EncryptFrameInput): EncryptFrame {
+export function getEncryptFrame(input: EncryptFrameInput): EncryptFrame {
const { pendingFrame, messageHeader, getCipher, isFinalFrame } = input
const { sequenceNumber, contentLength, content } = pendingFrame
const { frameLength, contentType, messageId, headerIvLength } = messageHeader
@@ -185,13 +210,31 @@ export function getEncryptFrame (input: EncryptFrameInput): EncryptFrame {
* In the case of the final frame,
* it MUST NOT be larger than the frame length.
*/
- needs(frameLength === contentLength || (isFinalFrame && frameLength >= contentLength), `Malformed frame length and content length: ${JSON.stringify({ frameLength, contentLength, isFinalFrame })}`)
+ needs(
+ frameLength === contentLength ||
+ (isFinalFrame && frameLength >= contentLength),
+ `Malformed frame length and content length: ${JSON.stringify({
+ frameLength,
+ contentLength,
+ isFinalFrame,
+ })}`
+ )
const frameIv = serialize.frameIv(headerIvLength, sequenceNumber)
- const bodyHeader = Buffer.from(isFinalFrame
- ? finalFrameHeader(sequenceNumber, frameIv, contentLength)
- : frameHeader(sequenceNumber, frameIv))
- const contentString = aadUtility.messageAADContentString({ contentType, isFinalFrame })
- const { buffer, byteOffset, byteLength } = aadUtility.messageAAD(messageId, contentString, sequenceNumber, contentLength)
+ const bodyHeader = Buffer.from(
+ isFinalFrame
+ ? finalFrameHeader(sequenceNumber, frameIv, contentLength)
+ : frameHeader(sequenceNumber, frameIv)
+ )
+ const contentString = aadUtility.messageAADContentString({
+ contentType,
+ isFinalFrame,
+ })
+ const { buffer, byteOffset, byteLength } = aadUtility.messageAAD(
+ messageId,
+ contentString,
+ sequenceNumber,
+ contentLength
+ )
const cipher = getCipher(frameIv)
cipher.setAAD(Buffer.from(buffer, byteOffset, byteLength))
diff --git a/modules/encrypt-node/src/signature_stream.ts b/modules/encrypt-node/src/signature_stream.ts
index 548260402..796e5d9d0 100644
--- a/modules/encrypt-node/src/signature_stream.ts
+++ b/modules/encrypt-node/src/signature_stream.ts
@@ -2,27 +2,27 @@
// SPDX-License-Identifier: Apache-2.0
import { Transform } from 'stream'
-import { GetSigner } from '@aws-crypto/material-management-node' // eslint-disable-line no-unused-vars
+import { GetSigner } from '@aws-crypto/material-management-node'
import { serializeSignatureInfo } from '@aws-crypto/serialize'
type AWSSigner = ReturnType
export class SignatureStream extends Transform {
- private _signer!: AWSSigner|undefined
- constructor (getSigner?: GetSigner) {
+ private _signer!: AWSSigner | undefined
+ constructor(getSigner?: GetSigner) {
super()
const value = getSigner && getSigner()
Object.defineProperty(this, '_signer', { value, enumerable: true })
}
- _transform (chunk: any, _encoding: string, callback: Function) {
+ _transform(chunk: any, _encoding: string, callback: Function) {
// If we have a signer, push the data to it
this._signer && this._signer.update(chunk)
// forward the data on
callback(null, chunk)
}
- _flush (callback: Function) {
+ _flush(callback: Function) {
if (this._signer) {
const signature = this._signer.awsCryptoSign()
this.push(serializeSignatureInfo(signature))
diff --git a/modules/example-browser/package.json b/modules/example-browser/package.json
index 6de83adf8..19b531068 100644
--- a/modules/example-browser/package.json
+++ b/modules/example-browser/package.json
@@ -4,7 +4,9 @@
"scripts": {
"prepublishOnly": "npm run build",
"build": "tsc -b tsconfig.json && tsc -b tsconfig.module.json",
- "lint": "standard src/*.ts test/**/*.ts",
+ "lint": "run-s lint-*",
+ "lint-eslint": "npx eslint modules/**/src/*.ts modules/**/test/**/*.ts",
+ "lint-prettier": "prettier -c modules/**/src/*.ts modules/**/test/**/*.ts",
"karma": "karma start karma.conf.js",
"test": "npm run lint && npm run coverage",
"coverage": "npm run karma && nyc report --exclude-after-remap false -t .karma_output --check-coverage",
diff --git a/modules/example-browser/src/aes_simple.ts b/modules/example-browser/src/aes_simple.ts
index 5b78f69d3..62ca939f7 100644
--- a/modules/example-browser/src/aes_simple.ts
+++ b/modules/example-browser/src/aes_simple.ts
@@ -11,12 +11,12 @@ import {
RawAesKeyringWebCrypto,
encrypt,
decrypt,
- synchronousRandomValues
+ synchronousRandomValues,
} from '@aws-crypto/client-browser'
import { toBase64 } from '@aws-sdk/util-base64-browser'
/* This is done to facilitate testing. */
-export async function testAES () {
+export async function testAES() {
/* You need to specify a name
* and a namespace for raw encryption key providers.
* The name and namespace that you use in the decryption keyring *must* be an exact,
@@ -26,16 +26,25 @@ export async function testAES () {
const keyNamespace = 'aes-namespace'
/* The wrapping suite defines the AES-GCM algorithm suite to use. */
- const wrappingSuite = RawAesWrappingSuiteIdentifier.AES256_GCM_IV12_TAG16_NO_PADDING
+ const wrappingSuite =
+ RawAesWrappingSuiteIdentifier.AES256_GCM_IV12_TAG16_NO_PADDING
// Get your plaintext master key from wherever you store it.
const unencryptedMasterKey = synchronousRandomValues(32)
/* Import the plaintext master key into a WebCrypto CryptoKey. */
- const masterKey = await RawAesKeyringWebCrypto.importCryptoKey(unencryptedMasterKey, wrappingSuite)
+ const masterKey = await RawAesKeyringWebCrypto.importCryptoKey(
+ unencryptedMasterKey,
+ wrappingSuite
+ )
/* Configure the Raw AES keyring. */
- const keyring = new RawAesKeyringWebCrypto({ keyName, keyNamespace, wrappingSuite, masterKey })
+ const keyring = new RawAesKeyringWebCrypto({
+ keyName,
+ keyNamespace,
+ wrappingSuite,
+ masterKey,
+ })
/* Encryption context is a *very* powerful tool for controlling and managing access.
* It is ***not*** secret!
@@ -49,14 +58,16 @@ export async function testAES () {
const context = {
stage: 'demo',
purpose: 'simple demonstration app',
- origin: 'us-west-2'
+ origin: 'us-west-2',
}
/* Find data to encrypt. */
const plainText = new Uint8Array([1, 2, 3, 4, 5])
/* Encrypt the data. */
- const { result } = await encrypt(keyring, plainText, { encryptionContext: context })
+ const { result } = await encrypt(keyring, plainText, {
+ encryptionContext: context,
+ })
/* Log the plain text
* only for testing and to show that it works.
@@ -83,11 +94,10 @@ export async function testAES () {
* do not add a test that requires that all key-value pairs match.
* Instead, verify that the key-value pairs you expect match.
*/
- Object
- .entries(context)
- .forEach(([key, value]) => {
- if (encryptionContext[key] !== value) throw new Error('Encryption Context does not match expected values')
- })
+ Object.entries(context).forEach(([key, value]) => {
+ if (encryptionContext[key] !== value)
+ throw new Error('Encryption Context does not match expected values')
+ })
/* Log the clear message
* only for testing and to show that it works.
diff --git a/modules/example-browser/src/caching_cmm.ts b/modules/example-browser/src/caching_cmm.ts
index 577c7e809..06f539f6f 100644
--- a/modules/example-browser/src/caching_cmm.ts
+++ b/modules/example-browser/src/caching_cmm.ts
@@ -12,7 +12,7 @@ import {
encrypt,
decrypt,
WebCryptoCachingMaterialsManager,
- getLocalCryptographicMaterialsCache
+ getLocalCryptographicMaterialsCache,
} from '@aws-crypto/client-browser'
import { toBase64 } from '@aws-sdk/util-base64-browser'
@@ -22,14 +22,19 @@ import { toBase64 } from '@aws-sdk/util-base64-browser'
* Use any method you like to get credentials into the browser.
* See kms.webpack.config
*/
-declare const credentials: {accessKeyId: string, secretAccessKey:string, sessionToken:string }
+declare const credentials: {
+ accessKeyId: string
+ secretAccessKey: string
+ sessionToken: string
+}
/* This is done to facilitate testing. */
-export async function testCachingCMMExample () {
+export async function testCachingCMMExample() {
/* This example uses a KMS keyring. The generator key in a KMS keyring generates and encrypts the data key.
* The caller needs kms:GenerateDataKey permission on the CMK in generatorKeyId.
*/
- const generatorKeyId = 'arn:aws:kms:us-west-2:658956600833:alias/EncryptDecrypt'
+ const generatorKeyId =
+ 'arn:aws:kms:us-west-2:658956600833:alias/EncryptDecrypt'
/* Adding additional KMS keys that can decrypt.
* The caller must have kms:Encrypt permission for every CMK in keyIds.
@@ -43,7 +48,9 @@ export async function testCachingCMMExample () {
* or omit the `keyIds` parameter.
* This is *only* to demonstrate how the CMK ARNs are configured.
*/
- const keyIds = ['arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f']
+ const keyIds = [
+ 'arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f',
+ ]
/* Need a client provider that will inject correct credentials.
* The credentials here are injected by webpack from your environment bundle is created
@@ -63,12 +70,16 @@ export async function testCachingCMMExample () {
credentials: {
accessKeyId,
secretAccessKey,
- sessionToken
- }
+ sessionToken,
+ },
})
/* You must configure the KMS keyring with your KMS CMKs */
- const keyring = new KmsKeyringBrowser({ clientProvider, generatorKeyId, keyIds })
+ const keyring = new KmsKeyringBrowser({
+ clientProvider,
+ generatorKeyId,
+ keyIds,
+ })
/* Create a cache to hold the data keys (and related cryptographic material).
* This example uses the local cache provided by the Encryption SDK.
@@ -116,7 +127,7 @@ export async function testCachingCMMExample () {
partition,
maxAge,
maxBytesEncrypted,
- maxMessagesEncrypted
+ maxMessagesEncrypted,
})
/* Encryption context is a *very* powerful tool for controlling
@@ -140,7 +151,7 @@ export async function testCachingCMMExample () {
const encryptionContext = {
stage: 'demo',
purpose: 'simple demonstration app',
- origin: 'us-west-2'
+ origin: 'us-west-2',
}
/* Find data to encrypt. */
@@ -186,11 +197,10 @@ export async function testCachingCMMExample () {
* do not include a test that requires that all key-value pairs match.
* Instead, verify that the key-value pairs that you supplied to the `encrypt` function are included in the encryption context that the `decrypt` function returns.
*/
- Object
- .entries(encryptionContext)
- .forEach(([key, value]) => {
- if (decryptedContext[key] !== value) throw new Error('Encryption Context does not match expected values')
- })
+ Object.entries(encryptionContext).forEach(([key, value]) => {
+ if (decryptedContext[key] !== value)
+ throw new Error('Encryption Context does not match expected values')
+ })
/* Log the clear message
* only for testing and to show that it works.
diff --git a/modules/example-browser/src/fallback.ts b/modules/example-browser/src/fallback.ts
index f976655e9..b06b4afde 100644
--- a/modules/example-browser/src/fallback.ts
+++ b/modules/example-browser/src/fallback.ts
@@ -13,7 +13,7 @@ import {
decrypt,
synchronousRandomValues,
configureFallback,
- AlgorithmSuiteIdentifier
+ AlgorithmSuiteIdentifier,
} from '@aws-crypto/client-browser'
import { toBase64 } from '@aws-sdk/util-base64-browser'
@@ -30,7 +30,7 @@ import { subtle } from './msrcrypto'
configureFallback(subtle)
/* This is done to facilitate testing. */
-export async function testFallback () {
+export async function testFallback() {
/* You need to specify a name
* and a namespace for raw encryption key providers.
* The name and namespace that you use in the decryption keyring *must* be an exact,
@@ -40,16 +40,25 @@ export async function testFallback () {
const keyNamespace = 'aes-namespace'
/* The wrapping suite defines the AES-GCM algorithm suite to use. */
- const wrappingSuite = RawAesWrappingSuiteIdentifier.AES256_GCM_IV12_TAG16_NO_PADDING
+ const wrappingSuite =
+ RawAesWrappingSuiteIdentifier.AES256_GCM_IV12_TAG16_NO_PADDING
// Get your plaintext master key from wherever you store it.
const unencryptedMasterKey = synchronousRandomValues(32)
/* Import the plaintext master key into a WebCrypto CryptoKey. */
- const masterKey = await RawAesKeyringWebCrypto.importCryptoKey(unencryptedMasterKey, wrappingSuite)
+ const masterKey = await RawAesKeyringWebCrypto.importCryptoKey(
+ unencryptedMasterKey,
+ wrappingSuite
+ )
/* Configure the Raw AES keyring. */
- const keyring = new RawAesKeyringWebCrypto({ keyName, keyNamespace, wrappingSuite, masterKey })
+ const keyring = new RawAesKeyringWebCrypto({
+ keyName,
+ keyNamespace,
+ wrappingSuite,
+ masterKey,
+ })
/* Encryption context is a *very* powerful tool for controlling and managing access.
* It is ***not*** secret!
@@ -63,20 +72,26 @@ export async function testFallback () {
const context = {
stage: 'demo',
purpose: 'simple demonstration app',
- origin: 'us-west-2'
+ origin: 'us-west-2',
}
/* Find data to encrypt. */
const plainText = new Uint8Array([1, 2, 3, 4, 5])
/* Encrypt the data. */
- const { result } = await encrypt(keyring, plainText, { encryptionContext: context, suiteId: AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16 })
+ const { result } = await encrypt(keyring, plainText, {
+ encryptionContext: context,
+ suiteId: AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16,
+ })
/* Log the plain text
* only for testing and to show that it works.
*/
console.log('plainText:', plainText)
- document.body.insertAdjacentHTML('beforeend', `plainText:
${plainText}
`)
+ document.body.insertAdjacentHTML(
+ 'beforeend',
+ `plainText:
${plainText}
`
+ )
/* Log the base64-encoded result
* so that you can try decrypting it with another AWS Encryption SDK implementation.
@@ -97,17 +112,19 @@ export async function testFallback () {
* do not add a test that requires that all key-value pairs match.
* Instead, verify that the key-value pairs you expect match.
*/
- Object
- .entries(context)
- .forEach(([key, value]) => {
- if (encryptionContext[key] !== value) throw new Error('Encryption Context does not match expected values')
- })
+ Object.entries(context).forEach(([key, value]) => {
+ if (encryptionContext[key] !== value)
+ throw new Error('Encryption Context does not match expected values')
+ })
/* Log the clear message
* only for testing and to show that it works.
*/
console.log(plaintext)
- document.body.insertAdjacentHTML('beforeend', `plainText:
${plaintext}
`)
+ document.body.insertAdjacentHTML(
+ 'beforeend',
+ `plainText:
${plaintext}
`
+ )
/* Return the values to make testing easy. */
return { plainText, plaintext }
diff --git a/modules/example-browser/src/index.ts b/modules/example-browser/src/index.ts
index 66a57fbfd..924cf6717 100644
--- a/modules/example-browser/src/index.ts
+++ b/modules/example-browser/src/index.ts
@@ -2,6 +2,6 @@
// SPDX-License-Identifier: Apache-2.0
/*
- * This library has no exported implementation.
- * It is intended to be used as a reference.
- */
+ * This library has no exported implementation.
+ * It is intended to be used as a reference.
+ */
diff --git a/modules/example-browser/src/kms_simple.ts b/modules/example-browser/src/kms_simple.ts
index 52e972fff..039732575 100644
--- a/modules/example-browser/src/kms_simple.ts
+++ b/modules/example-browser/src/kms_simple.ts
@@ -10,7 +10,7 @@ import {
KMS,
getClient,
encrypt,
- decrypt
+ decrypt,
} from '@aws-crypto/client-browser'
import { toBase64 } from '@aws-sdk/util-base64-browser'
@@ -20,14 +20,19 @@ import { toBase64 } from '@aws-sdk/util-base64-browser'
* Use any method you like to get credentials into the browser.
* See kms.webpack.config
*/
-declare const credentials: {accessKeyId: string, secretAccessKey:string, sessionToken:string }
+declare const credentials: {
+ accessKeyId: string
+ secretAccessKey: string
+ sessionToken: string
+}
/* This is done to facilitate testing. */
-export async function testKmsSimpleExample () {
+export async function testKmsSimpleExample() {
/* A KMS CMK is required to generate the data key.
* You need kms:GenerateDataKey permission on the CMK in generatorKeyId.
*/
- const generatorKeyId = 'arn:aws:kms:us-west-2:658956600833:alias/EncryptDecrypt'
+ const generatorKeyId =
+ 'arn:aws:kms:us-west-2:658956600833:alias/EncryptDecrypt'
/* Adding alternate KMS keys that can decrypt.
* Access to kms:Encrypt is required for every CMK in keyIds.
@@ -36,7 +41,9 @@ export async function testKmsSimpleExample () {
* In this example, I am using the same CMK.
* This is *only* to demonstrate how the CMK ARNs are configured.
*/
- const keyIds = ['arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f']
+ const keyIds = [
+ 'arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f',
+ ]
/* Need a client provider that will inject correct credentials.
* The credentials here are injected by webpack from your environment bundle is created
@@ -56,12 +63,16 @@ export async function testKmsSimpleExample () {
credentials: {
accessKeyId,
secretAccessKey,
- sessionToken
- }
+ sessionToken,
+ },
})
/* The KMS keyring must be configured with the desired CMKs */
- const keyring = new KmsKeyringBrowser({ clientProvider, generatorKeyId, keyIds })
+ const keyring = new KmsKeyringBrowser({
+ clientProvider,
+ generatorKeyId,
+ keyIds,
+ })
/* Encryption context is a *very* powerful tool for controlling and managing access.
* It is ***not*** secret!
@@ -75,14 +86,16 @@ export async function testKmsSimpleExample () {
const context = {
stage: 'demo',
purpose: 'simple demonstration app',
- origin: 'us-west-2'
+ origin: 'us-west-2',
}
/* Find data to encrypt. */
const plainText = new Uint8Array([1, 2, 3, 4, 5])
/* Encrypt the data. */
- const { result } = await encrypt(keyring, plainText, { encryptionContext: context })
+ const { result } = await encrypt(keyring, plainText, {
+ encryptionContext: context,
+ })
/* Log the plain text
* only for testing and to show that it works.
@@ -109,11 +122,10 @@ export async function testKmsSimpleExample () {
* do not add a test that requires that all key-value pairs match.
* Instead, verify that the key-value pairs you expect match.
*/
- Object
- .entries(context)
- .forEach(([key, value]) => {
- if (encryptionContext[key] !== value) throw new Error('Encryption Context does not match expected values')
- })
+ Object.entries(context).forEach(([key, value]) => {
+ if (encryptionContext[key] !== value)
+ throw new Error('Encryption Context does not match expected values')
+ })
/* Log the clear message
* only for testing and to show that it works.
diff --git a/modules/example-browser/src/multi_keyring.ts b/modules/example-browser/src/multi_keyring.ts
index b0ebc7d9f..0aec820eb 100644
--- a/modules/example-browser/src/multi_keyring.ts
+++ b/modules/example-browser/src/multi_keyring.ts
@@ -15,7 +15,7 @@ import {
MultiKeyringWebCrypto,
encrypt,
decrypt,
- synchronousRandomValues
+ synchronousRandomValues,
} from '@aws-crypto/client-browser'
import { toBase64 } from '@aws-sdk/util-base64-browser'
@@ -25,14 +25,19 @@ import { toBase64 } from '@aws-sdk/util-base64-browser'
* Use any method you like to get credentials into the browser.
* See kms.webpack.config
*/
-declare const credentials: {accessKeyId: string, secretAccessKey:string, sessionToken:string }
+declare const credentials: {
+ accessKeyId: string
+ secretAccessKey: string
+ sessionToken: string
+}
/* This is done to facilitate testing. */
-export async function testMultiKeyringExample () {
+export async function testMultiKeyringExample() {
/* A KMS CMK is required to generate the data key.
* You need kms:GenerateDataKey permission on the CMK in generatorKeyId.
*/
- const generatorKeyId = 'arn:aws:kms:us-west-2:658956600833:alias/EncryptDecrypt'
+ const generatorKeyId =
+ 'arn:aws:kms:us-west-2:658956600833:alias/EncryptDecrypt'
/* Adding alternate KMS keys that can decrypt.
* Access to kms:Encrypt is required for every CMK in keyIds.
@@ -41,7 +46,9 @@ export async function testMultiKeyringExample () {
* In this example, I am using the same CMK.
* This is *only* to demonstrate how the CMK ARNs are configured.
*/
- const keyIds = ['arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f']
+ const keyIds = [
+ 'arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f',
+ ]
/* Need a client provider that will inject correct credentials.
* The credentials here are injected by webpack
@@ -63,12 +70,16 @@ export async function testMultiKeyringExample () {
credentials: {
accessKeyId,
secretAccessKey,
- sessionToken
- }
+ sessionToken,
+ },
})
/* The KMS keyring must be configured with the desired CMKs */
- const kmsKeyring = new KmsKeyringBrowser({ clientProvider, generatorKeyId, keyIds })
+ const kmsKeyring = new KmsKeyringBrowser({
+ clientProvider,
+ generatorKeyId,
+ keyIds,
+ })
/* You need to specify a name
* and a namespace for raw encryption key providers.
@@ -79,19 +90,31 @@ export async function testMultiKeyringExample () {
const keyNamespace = 'aes-namespace'
/* The wrapping suite defines the AES-GCM algorithm suite to use. */
- const wrappingSuite = RawAesWrappingSuiteIdentifier.AES256_GCM_IV12_TAG16_NO_PADDING
+ const wrappingSuite =
+ RawAesWrappingSuiteIdentifier.AES256_GCM_IV12_TAG16_NO_PADDING
// Get your plaintext master key from its storage location.
const unencryptedMasterKey = synchronousRandomValues(32)
/* The plaintext master key must be imported into a WebCrypto CryptoKey. */
- const masterKey = await RawAesKeyringWebCrypto.importCryptoKey(unencryptedMasterKey, wrappingSuite)
+ const masterKey = await RawAesKeyringWebCrypto.importCryptoKey(
+ unencryptedMasterKey,
+ wrappingSuite
+ )
/* Configure the Raw AES keyring. */
- const aesKeyring = new RawAesKeyringWebCrypto({ keyName, keyNamespace, wrappingSuite, masterKey })
+ const aesKeyring = new RawAesKeyringWebCrypto({
+ keyName,
+ keyNamespace,
+ wrappingSuite,
+ masterKey,
+ })
/* Combine the two keyrings into a multi-keyring. */
- const keyring = new MultiKeyringWebCrypto({ generator: kmsKeyring, children: [ aesKeyring ] })
+ const keyring = new MultiKeyringWebCrypto({
+ generator: kmsKeyring,
+ children: [aesKeyring],
+ })
/* Encryption context is a *very* powerful tool for controlling and managing access.
* It is ***not*** secret!
@@ -105,14 +128,16 @@ export async function testMultiKeyringExample () {
const context = {
stage: 'demo',
purpose: 'simple demonstration app',
- origin: 'us-west-2'
+ origin: 'us-west-2',
}
/* Find data to encrypt. */
const plainText = new Uint8Array([1, 2, 3, 4, 5])
/* Encrypt the data. */
- const { result } = await encrypt(keyring, plainText, { encryptionContext: context })
+ const { result } = await encrypt(keyring, plainText, {
+ encryptionContext: context,
+ })
/* Log the plain text
* only for testing and to show that it works.
@@ -146,11 +171,10 @@ export async function testMultiKeyringExample () {
* do not add a test that requires that all key-value pairs match.
* Instead, verify that the key-value pairs you expect match.
*/
- Object
- .entries(context)
- .forEach(([key, value]) => {
- if (encryptionContext[key] !== value) throw new Error('Encryption Context does not match expected values')
- })
+ Object.entries(context).forEach(([key, value]) => {
+ if (encryptionContext[key] !== value)
+ throw new Error('Encryption Context does not match expected values')
+ })
/* Log the clear message
* only for testing and to show that it works.
diff --git a/modules/example-browser/src/rsa_simple.ts b/modules/example-browser/src/rsa_simple.ts
index e39d3cf10..ba0ea85ee 100644
--- a/modules/example-browser/src/rsa_simple.ts
+++ b/modules/example-browser/src/rsa_simple.ts
@@ -7,26 +7,58 @@
*/
import {
- RsaImportableKey, // eslint-disable-line no-unused-vars
+ RsaImportableKey,
RawRsaKeyringWebCrypto,
encrypt,
- decrypt
+ decrypt,
} from '@aws-crypto/client-browser'
import { toBase64 } from '@aws-sdk/util-base64-browser'
/* This is done to facilitate testing. */
-export async function testRSA () {
+export async function testRSA() {
/* JWK for the RSA Keys to use.
* These keys are *Public*!
* *DO NOT USE*
*/
- const privateRsaJwkKey: RsaImportableKey = { 'alg': 'RSA-OAEP-256', 'd': 'XcAlS3OYtZ5F3BFGRQH5B8soiqstUk9JkH6_sUhBUfM7yjFpn3MQACtGgOKsFIO01KWCVl7Cn6E3c-MuuT3QqNQrUx8n-WrJU8qNpDOGJ5CVpG9-xTSQVNzRV92gj8g7-BIgehtzMmirXXNsb1XeTg9zsm3iptt9VyhplGqcgOdmm72sT1Z8ZmkagaElHSg0dR1ZNGgzSfTtRg_J1tTh7cmFb1LVz069o6cRaa5ueOPNKxmEslBdVWsDo9naxd_keLiqOOMIQp-KlLuQ-Zhn5fZyqxkRPGjTKZZHitgurzfWG4ERjjrYCbZsOjEt9Tj8FXXUB8bd3qRPy5UkN-XLEQ', 'dp': 'V8QYdWm4OqWpfF_NPdCGr5eqztfHiQQn1NLmkvNO8c9dc2yNizZ4GxtNNEARYjgnLK0ROCoiK5yamtVDyjZ_zzZUvE0CG8iNRg1qvaOM8n_7B2YgmUs9rJ-QKK3HVEsi_M0x-hHeRl3ocAkNfby3__yt6s43FvyrccQh89WcAr0', 'dq': 'NT5lrYlvkOwXIHl8P9AQm1nNL0RkHSrWahYlagRkyU3ELySlWr2laDxXzPnngpuBvyA98iq6Z2JTn8ArtXXvTqQk6BF6np6qqg1QNQxsQeU4Aj3xOMV9EGh57Zpa8Rs0jVydxBdlRW03Fr0UChHKxmT2kS0622gdlGQAs3YxMck', 'e': 'AQAB', 'ext': true, 'key_ops': ['unwrapKey'], 'kty': 'RSA', 'n': '6k_jrxg7mpz7CzgAr6eRqJr1VlvjJ9uQY71hadkDZkLLZHiMl7hz73lqq3w2MfHCa3Pf3BVo5TCXGYuxKOlPb7bH0WWpMeAzOKR_X27UqfA8MBVGb4YO5HXqw0jup8-I-Zi3CQAmP87uE6GDuh7xzeAcwpGD5xE0N74-uWq3YS92PFHCavtryx-ad9VGTgfAbkV3k1-RSxIiZjzbAt3exBAn5EjMfF6FMI70_HYqO-5xGv_aAPSa1OMc_buK5QACN7gmFwqHBzw98v93iyGUc4_XJNL-jPzKNP4AT1zMc6p6RxF3SYytNq7iXIjUmm-oY8fvCSmT1F13XKdzv7DLOw', 'p': '9dGuBwEDeOHFwJ_AQXHBWu53bv_L1_9lh2X-NEBO1B7YMhYWu2nMqXEvLpwvPqyBXwWnuPdfGqu6BHv22RDAF7Lu_oUshq-9dzSwFxaC5PQ2NwtHnz0-zwhEzCE3Qw9t63_OXX87gjp5vy6c5bvb3B9EbZU33Xf9nqVEJhzFreU', 'q': '9AQ0oYhctBbFuIu4jt1HBmqQGGAECbhQAMw324MX8pVUg6GOtF0X822iEsq7aIfY8u5nTWu1kKl6s84US1yII0sJmW2Jj722r5VYDIrxk5x_mLQ6jXmfuH2kl-Lvzo6aHIVkDLIK-IaPt5teSwG71QfAPDgR6drIAuSFnJZ2Ap8', 'qi': 'mfoT9tmXPhLBanX5Mg76pO21NAXR1aAQ76tS1_hJZYxP8iZtmlEdvvAMIdSibvIt7Gfi60rBPnxqmmKuitJfzIVCd4sVLjIVEjT_njjLAzU-NTQdGugPCWWo8jB8NyeFy6nrZa_Hy52ijBn-Xt5G8pzvz5lF5gRfCe09y14oNeQ' }
- const publicRsaJwkKey: RsaImportableKey = { 'alg': 'RSA-OAEP-256', 'e': 'AQAB', 'ext': true, 'key_ops': ['wrapKey'], 'kty': 'RSA', 'n': '6k_jrxg7mpz7CzgAr6eRqJr1VlvjJ9uQY71hadkDZkLLZHiMl7hz73lqq3w2MfHCa3Pf3BVo5TCXGYuxKOlPb7bH0WWpMeAzOKR_X27UqfA8MBVGb4YO5HXqw0jup8-I-Zi3CQAmP87uE6GDuh7xzeAcwpGD5xE0N74-uWq3YS92PFHCavtryx-ad9VGTgfAbkV3k1-RSxIiZjzbAt3exBAn5EjMfF6FMI70_HYqO-5xGv_aAPSa1OMc_buK5QACN7gmFwqHBzw98v93iyGUc4_XJNL-jPzKNP4AT1zMc6p6RxF3SYytNq7iXIjUmm-oY8fvCSmT1F13XKdzv7DLOw' }
+ const privateRsaJwkKey: RsaImportableKey = {
+ alg: 'RSA-OAEP-256',
+ d:
+ 'XcAlS3OYtZ5F3BFGRQH5B8soiqstUk9JkH6_sUhBUfM7yjFpn3MQACtGgOKsFIO01KWCVl7Cn6E3c-MuuT3QqNQrUx8n-WrJU8qNpDOGJ5CVpG9-xTSQVNzRV92gj8g7-BIgehtzMmirXXNsb1XeTg9zsm3iptt9VyhplGqcgOdmm72sT1Z8ZmkagaElHSg0dR1ZNGgzSfTtRg_J1tTh7cmFb1LVz069o6cRaa5ueOPNKxmEslBdVWsDo9naxd_keLiqOOMIQp-KlLuQ-Zhn5fZyqxkRPGjTKZZHitgurzfWG4ERjjrYCbZsOjEt9Tj8FXXUB8bd3qRPy5UkN-XLEQ',
+ dp:
+ 'V8QYdWm4OqWpfF_NPdCGr5eqztfHiQQn1NLmkvNO8c9dc2yNizZ4GxtNNEARYjgnLK0ROCoiK5yamtVDyjZ_zzZUvE0CG8iNRg1qvaOM8n_7B2YgmUs9rJ-QKK3HVEsi_M0x-hHeRl3ocAkNfby3__yt6s43FvyrccQh89WcAr0',
+ dq:
+ 'NT5lrYlvkOwXIHl8P9AQm1nNL0RkHSrWahYlagRkyU3ELySlWr2laDxXzPnngpuBvyA98iq6Z2JTn8ArtXXvTqQk6BF6np6qqg1QNQxsQeU4Aj3xOMV9EGh57Zpa8Rs0jVydxBdlRW03Fr0UChHKxmT2kS0622gdlGQAs3YxMck',
+ e: 'AQAB',
+ ext: true,
+ key_ops: ['unwrapKey'], // eslint-disable-line @typescript-eslint/camelcase
+ kty: 'RSA',
+ n:
+ '6k_jrxg7mpz7CzgAr6eRqJr1VlvjJ9uQY71hadkDZkLLZHiMl7hz73lqq3w2MfHCa3Pf3BVo5TCXGYuxKOlPb7bH0WWpMeAzOKR_X27UqfA8MBVGb4YO5HXqw0jup8-I-Zi3CQAmP87uE6GDuh7xzeAcwpGD5xE0N74-uWq3YS92PFHCavtryx-ad9VGTgfAbkV3k1-RSxIiZjzbAt3exBAn5EjMfF6FMI70_HYqO-5xGv_aAPSa1OMc_buK5QACN7gmFwqHBzw98v93iyGUc4_XJNL-jPzKNP4AT1zMc6p6RxF3SYytNq7iXIjUmm-oY8fvCSmT1F13XKdzv7DLOw',
+ p:
+ '9dGuBwEDeOHFwJ_AQXHBWu53bv_L1_9lh2X-NEBO1B7YMhYWu2nMqXEvLpwvPqyBXwWnuPdfGqu6BHv22RDAF7Lu_oUshq-9dzSwFxaC5PQ2NwtHnz0-zwhEzCE3Qw9t63_OXX87gjp5vy6c5bvb3B9EbZU33Xf9nqVEJhzFreU',
+ q:
+ '9AQ0oYhctBbFuIu4jt1HBmqQGGAECbhQAMw324MX8pVUg6GOtF0X822iEsq7aIfY8u5nTWu1kKl6s84US1yII0sJmW2Jj722r5VYDIrxk5x_mLQ6jXmfuH2kl-Lvzo6aHIVkDLIK-IaPt5teSwG71QfAPDgR6drIAuSFnJZ2Ap8',
+ qi:
+ 'mfoT9tmXPhLBanX5Mg76pO21NAXR1aAQ76tS1_hJZYxP8iZtmlEdvvAMIdSibvIt7Gfi60rBPnxqmmKuitJfzIVCd4sVLjIVEjT_njjLAzU-NTQdGugPCWWo8jB8NyeFy6nrZa_Hy52ijBn-Xt5G8pzvz5lF5gRfCe09y14oNeQ',
+ }
+ const publicRsaJwkKey: RsaImportableKey = {
+ alg: 'RSA-OAEP-256',
+ e: 'AQAB',
+ ext: true,
+ key_ops: ['wrapKey'], // eslint-disable-line @typescript-eslint/camelcase
+ kty: 'RSA',
+ n:
+ '6k_jrxg7mpz7CzgAr6eRqJr1VlvjJ9uQY71hadkDZkLLZHiMl7hz73lqq3w2MfHCa3Pf3BVo5TCXGYuxKOlPb7bH0WWpMeAzOKR_X27UqfA8MBVGb4YO5HXqw0jup8-I-Zi3CQAmP87uE6GDuh7xzeAcwpGD5xE0N74-uWq3YS92PFHCavtryx-ad9VGTgfAbkV3k1-RSxIiZjzbAt3exBAn5EjMfF6FMI70_HYqO-5xGv_aAPSa1OMc_buK5QACN7gmFwqHBzw98v93iyGUc4_XJNL-jPzKNP4AT1zMc6p6RxF3SYytNq7iXIjUmm-oY8fvCSmT1F13XKdzv7DLOw',
+ }
/* The RSA private key needs to be imported to a CryptoKey. */
- const privateKey = await RawRsaKeyringWebCrypto.importPrivateKey(privateRsaJwkKey)
+ const privateKey = await RawRsaKeyringWebCrypto.importPrivateKey(
+ privateRsaJwkKey
+ )
/* The RSA public key needs to be imported to a CryptoKey. */
- const publicKey = await RawRsaKeyringWebCrypto.importPublicKey(publicRsaJwkKey)
+ const publicKey = await RawRsaKeyringWebCrypto.importPublicKey(
+ publicRsaJwkKey
+ )
/* You need to specify a name
* and a namespace for raw encryption key providers.
@@ -37,7 +69,12 @@ export async function testRSA () {
const keyNamespace = 'Example RSA Provider'
/* The Raw RSA Keyring must be configured with the desired CryptoKeys. */
- const keyring = new RawRsaKeyringWebCrypto({ keyName, keyNamespace, publicKey, privateKey })
+ const keyring = new RawRsaKeyringWebCrypto({
+ keyName,
+ keyNamespace,
+ publicKey,
+ privateKey,
+ })
/* Encryption context is a *very* powerful tool for controlling and managing access.
* It is ***not*** secret!
@@ -51,14 +88,16 @@ export async function testRSA () {
const context = {
stage: 'demo',
purpose: 'simple demonstration app',
- origin: 'us-west-2'
+ origin: 'us-west-2',
}
/* Find data to encrypt. */
const plainText = new Uint8Array([1, 2, 3, 4, 5])
/* Encrypt the data. */
- const { result } = await encrypt(keyring, plainText, { encryptionContext: context })
+ const { result } = await encrypt(keyring, plainText, {
+ encryptionContext: context,
+ })
/* Log the plain text
* only for testing and to show that it works.
@@ -85,11 +124,10 @@ export async function testRSA () {
* do not add a test that requires that all key-value pairs match.
* Instead, verify that the key-value pairs you expect match.
*/
- Object
- .entries(context)
- .forEach(([key, value]) => {
- if (encryptionContext[key] !== value) throw new Error('Encryption Context does not match expected values')
- })
+ Object.entries(context).forEach(([key, value]) => {
+ if (encryptionContext[key] !== value)
+ throw new Error('Encryption Context does not match expected values')
+ })
/* Log the clear message
* only for testing and to show that it works.
diff --git a/modules/example-node/package.json b/modules/example-node/package.json
index 0fd5c9519..a4a90540b 100644
--- a/modules/example-node/package.json
+++ b/modules/example-node/package.json
@@ -4,7 +4,9 @@
"scripts": {
"prepublishOnly": "npm run build",
"build": "tsc -b tsconfig.json && tsc -b tsconfig.module.json",
- "lint": "standard src/*.ts test/**/*.ts",
+ "lint": "run-s lint-*",
+ "lint-eslint": "npx eslint modules/**/src/*.ts modules/**/test/**/*.ts",
+ "lint-prettier": "prettier -c modules/**/src/*.ts modules/**/test/**/*.ts",
"mocha": "mocha --require ts-node/register test/**/*test.ts",
"test": "npm run lint && npm run coverage",
"coverage": "nyc -e .ts npm run mocha"
diff --git a/modules/example-node/src/aes_simple.ts b/modules/example-node/src/aes_simple.ts
index 884685a84..f35346cd4 100644
--- a/modules/example-node/src/aes_simple.ts
+++ b/modules/example-node/src/aes_simple.ts
@@ -1,14 +1,19 @@
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
-import { RawAesKeyringNode, encrypt, decrypt, RawAesWrappingSuiteIdentifier } from '@aws-crypto/client-node'
+import {
+ RawAesKeyringNode,
+ encrypt,
+ decrypt,
+ RawAesWrappingSuiteIdentifier,
+} from '@aws-crypto/client-node'
import { randomBytes } from 'crypto'
/**
* This function is an example of using the RawAesKeyringNode
* to encrypt and decrypt a simple string
*/
-export async function aesTest () {
+export async function aesTest() {
/* You need to specify a name
* and a namespace for raw encryption key providers.
* The name and namespace that you use in the decryption keyring *must* be an exact,
@@ -18,13 +23,19 @@ export async function aesTest () {
const keyNamespace = 'aes-namespace'
/* The wrapping suite defines the AES-GCM algorithm suite to use. */
- const wrappingSuite = RawAesWrappingSuiteIdentifier.AES256_GCM_IV12_TAG16_NO_PADDING
+ const wrappingSuite =
+ RawAesWrappingSuiteIdentifier.AES256_GCM_IV12_TAG16_NO_PADDING
// Get your plaintext master key from wherever you store it.
const unencryptedMasterKey = randomBytes(32)
/* Configure the Raw AES keyring. */
- const keyring = new RawAesKeyringNode({ keyName, keyNamespace, unencryptedMasterKey, wrappingSuite })
+ const keyring = new RawAesKeyringNode({
+ keyName,
+ keyNamespace,
+ unencryptedMasterKey,
+ wrappingSuite,
+ })
/* Encryption context is a *very* powerful tool for controlling and managing access.
* It is ***not*** secret!
@@ -38,14 +49,16 @@ export async function aesTest () {
const context = {
stage: 'demo',
purpose: 'simple demonstration app',
- origin: 'us-west-2'
+ origin: 'us-west-2',
}
/* Find data to encrypt. A simple string. */
const cleartext = 'asdf'
/* Encrypt the data. */
- const { result } = await encrypt(keyring, cleartext, { encryptionContext: context })
+ const { result } = await encrypt(keyring, cleartext, {
+ encryptionContext: context,
+ })
/* Decrypt the data. */
const { plaintext, messageHeader } = await decrypt(keyring, result)
@@ -59,11 +72,10 @@ export async function aesTest () {
* do not add a test that requires that all key-value pairs match.
* Instead, verify that the key-value pairs you expect match.
*/
- Object
- .entries(context)
- .forEach(([key, value]) => {
- if (encryptionContext[key] !== value) throw new Error('Encryption Context does not match expected values')
- })
+ Object.entries(context).forEach(([key, value]) => {
+ if (encryptionContext[key] !== value)
+ throw new Error('Encryption Context does not match expected values')
+ })
/* Return the values so the code can be tested. */
return { plaintext, result, cleartext }
diff --git a/modules/example-node/src/caching_cmm.ts b/modules/example-node/src/caching_cmm.ts
index ee0a14b4d..a73e3dbd3 100644
--- a/modules/example-node/src/caching_cmm.ts
+++ b/modules/example-node/src/caching_cmm.ts
@@ -1,13 +1,20 @@
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
-import { KmsKeyringNode, encrypt, decrypt, NodeCachingMaterialsManager, getLocalCryptographicMaterialsCache } from '@aws-crypto/client-node'
-
-export async function cachingCMMNodeSimpleTest () {
+import {
+ KmsKeyringNode,
+ encrypt,
+ decrypt,
+ NodeCachingMaterialsManager,
+ getLocalCryptographicMaterialsCache,
+} from '@aws-crypto/client-node'
+
+export async function cachingCMMNodeSimpleTest() {
/* A KMS CMK is required to generate the data key.
* You need kms:GenerateDataKey permission on the CMK in generatorKeyId.
*/
- const generatorKeyId = 'arn:aws:kms:us-west-2:658956600833:alias/EncryptDecrypt'
+ const generatorKeyId =
+ 'arn:aws:kms:us-west-2:658956600833:alias/EncryptDecrypt'
/* Adding alternate KMS keys that can decrypt.
* Access to kms:Encrypt is required for every CMK in keyIds.
@@ -21,7 +28,9 @@ export async function cachingCMMNodeSimpleTest () {
* or omit the `keyIds` parameter.
* This is *only* to demonstrate how the CMK ARNs are configured.
*/
- const keyIds = ['arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f']
+ const keyIds = [
+ 'arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f',
+ ]
/* The KMS keyring must be configured with the desired CMKs
* This example passes the keyring to the caching CMM
@@ -75,7 +84,7 @@ export async function cachingCMMNodeSimpleTest () {
partition,
maxAge,
maxBytesEncrypted,
- maxMessagesEncrypted
+ maxMessagesEncrypted,
})
/* Encryption context is a *very* powerful tool for controlling
@@ -99,7 +108,7 @@ export async function cachingCMMNodeSimpleTest () {
const encryptionContext = {
stage: 'demo',
purpose: 'simple demonstration app',
- origin: 'us-west-2'
+ origin: 'us-west-2',
}
/* Find data to encrypt. A simple string. */
@@ -119,7 +128,10 @@ export async function cachingCMMNodeSimpleTest () {
* the AWS Encryption SDK uses the actual plaintext length
* instead of any length you provide.
*/
- const { result } = await encrypt(cachingCMM, cleartext, { encryptionContext, plaintextLength: 4 })
+ const { result } = await encrypt(cachingCMM, cleartext, {
+ encryptionContext,
+ plaintextLength: 4,
+ })
/* Decrypt the data.
* NOTE: This decrypt request will not use the data key
@@ -138,11 +150,10 @@ export async function cachingCMMNodeSimpleTest () {
* do not include a test that requires that all key-value pairs match.
* Instead, verify that the key-value pairs that you supplied to the `encrypt` function are included in the encryption context that the `decrypt` function returns.
*/
- Object
- .entries(encryptionContext)
- .forEach(([key, value]) => {
- if (decryptedContext[key] !== value) throw new Error('Encryption Context does not match expected values')
- })
+ Object.entries(encryptionContext).forEach(([key, value]) => {
+ if (decryptedContext[key] !== value)
+ throw new Error('Encryption Context does not match expected values')
+ })
/* Return the values so the code can be tested. */
return { plaintext, result, cleartext, messageHeader }
diff --git a/modules/example-node/src/kms_regional_discovery.ts b/modules/example-node/src/kms_regional_discovery.ts
index 33dc83783..cb5134487 100644
--- a/modules/example-node/src/kms_regional_discovery.ts
+++ b/modules/example-node/src/kms_regional_discovery.ts
@@ -1,9 +1,17 @@
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
-import { KmsKeyringNode, limitRegions, excludeRegions, getKmsClient, decrypt } from '@aws-crypto/client-node'
+import {
+ KmsKeyringNode,
+ limitRegions,
+ excludeRegions,
+ getKmsClient,
+ decrypt,
+} from '@aws-crypto/client-node'
-export async function kmsRegionalDiscoveryLimitTest (ciphertext: string|Buffer) {
+export async function kmsRegionalDiscoveryLimitTest(
+ ciphertext: string | Buffer
+) {
const discovery = true
// This provider will *only* decrypt for keys in the us-east-1 region.
const clientProvider = limitRegions(['us-east-1'], getKmsClient)
@@ -14,7 +22,9 @@ export async function kmsRegionalDiscoveryLimitTest (ciphertext: string|Buffer)
return { ciphertext, cleartext }
}
-export async function kmsRegionalDiscoveryExcludeTest (ciphertext: string|Buffer) {
+export async function kmsRegionalDiscoveryExcludeTest(
+ ciphertext: string | Buffer
+) {
const discovery = true
// This provider will decrypt for keys in any region except us-east-1.
const clientProvider = excludeRegions(['us-east-1'], getKmsClient)
diff --git a/modules/example-node/src/kms_simple.ts b/modules/example-node/src/kms_simple.ts
index 3a1499ebf..3b5d7310a 100644
--- a/modules/example-node/src/kms_simple.ts
+++ b/modules/example-node/src/kms_simple.ts
@@ -3,11 +3,12 @@
import { KmsKeyringNode, encrypt, decrypt } from '@aws-crypto/client-node'
-export async function kmsSimpleTest () {
+export async function kmsSimpleTest() {
/* A KMS CMK is required to generate the data key.
* You need kms:GenerateDataKey permission on the CMK in generatorKeyId.
*/
- const generatorKeyId = 'arn:aws:kms:us-west-2:658956600833:alias/EncryptDecrypt'
+ const generatorKeyId =
+ 'arn:aws:kms:us-west-2:658956600833:alias/EncryptDecrypt'
/* Adding alternate KMS keys that can decrypt.
* Access to kms:Encrypt is required for every CMK in keyIds.
@@ -16,7 +17,9 @@ export async function kmsSimpleTest () {
* In this example, I am using the same CMK.
* This is *only* to demonstrate how the CMK ARNs are configured.
*/
- const keyIds = ['arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f']
+ const keyIds = [
+ 'arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f',
+ ]
/* The KMS keyring must be configured with the desired CMKs */
const keyring = new KmsKeyringNode({ generatorKeyId, keyIds })
@@ -33,14 +36,16 @@ export async function kmsSimpleTest () {
const context = {
stage: 'demo',
purpose: 'simple demonstration app',
- origin: 'us-west-2'
+ origin: 'us-west-2',
}
/* Find data to encrypt. A simple string. */
const cleartext = 'asdf'
/* Encrypt the data. */
- const { result } = await encrypt(keyring, cleartext, { encryptionContext: context })
+ const { result } = await encrypt(keyring, cleartext, {
+ encryptionContext: context,
+ })
/* Decrypt the data. */
const { plaintext, messageHeader } = await decrypt(keyring, result)
@@ -55,11 +60,10 @@ export async function kmsSimpleTest () {
* do not add a test that requires that all key-value pairs match.
* Instead, verify that the key-value pairs you expect match.
*/
- Object
- .entries(context)
- .forEach(([key, value]) => {
- if (encryptionContext[key] !== value) throw new Error('Encryption Context does not match expected values')
- })
+ Object.entries(context).forEach(([key, value]) => {
+ if (encryptionContext[key] !== value)
+ throw new Error('Encryption Context does not match expected values')
+ })
/* Return the values so the code can be tested. */
return { plaintext, result, cleartext, messageHeader }
diff --git a/modules/example-node/src/kms_stream.ts b/modules/example-node/src/kms_stream.ts
index 8047472f1..140306eee 100644
--- a/modules/example-node/src/kms_stream.ts
+++ b/modules/example-node/src/kms_stream.ts
@@ -5,7 +5,7 @@ import {
KmsKeyringNode,
decryptStream,
encryptStream,
- MessageHeader // eslint-disable-line no-unused-vars
+ MessageHeader,
} from '@aws-crypto/client-node'
import { finished } from 'stream'
@@ -13,11 +13,12 @@ import { createReadStream } from 'fs'
import { promisify } from 'util'
const finishedAsync = promisify(finished)
-export async function kmsStreamTest (filename: string) {
+export async function kmsStreamTest(filename: string) {
/* A KMS CMK is required to generate the data key.
* You need kms:GenerateDataKey permission on the CMK in generatorKeyId.
*/
- const generatorKeyId = 'arn:aws:kms:us-west-2:658956600833:alias/EncryptDecrypt'
+ const generatorKeyId =
+ 'arn:aws:kms:us-west-2:658956600833:alias/EncryptDecrypt'
/* The KMS keyring must be configured with the desired CMKs */
const keyring = new KmsKeyringNode({ generatorKeyId })
@@ -34,7 +35,7 @@ export async function kmsStreamTest (filename: string) {
const context = {
stage: 'demo',
purpose: 'simple demonstration app',
- origin: 'us-west-2'
+ origin: 'us-west-2',
}
/* Create a simple pipeline to encrypt the package.json for this project. */
@@ -43,17 +44,16 @@ export async function kmsStreamTest (filename: string) {
.pipe(decryptStream(new KmsKeyringNode({ discovery: true })))
.on('MessageHeader', ({ encryptionContext }: MessageHeader) => {
/* Verify the encryption context.
- * Depending on the Algorithm Suite, the `encryptionContext` _may_ contain additional values.
- * In Signing Algorithm Suites the public verification key is serialized into the `encryptionContext`.
- * Because the encryption context might contain additional key-value pairs,
- * do not add a test that requires that all key-value pairs match.
- * Instead, verify that the key-value pairs you expect match.
- */
- Object
- .entries(context)
- .forEach(([key, value]) => {
- if (encryptionContext[key] !== value) throw new Error('Encryption Context does not match expected values')
- })
+ * Depending on the Algorithm Suite, the `encryptionContext` _may_ contain additional values.
+ * In Signing Algorithm Suites the public verification key is serialized into the `encryptionContext`.
+ * Because the encryption context might contain additional key-value pairs,
+ * do not add a test that requires that all key-value pairs match.
+ * Instead, verify that the key-value pairs you expect match.
+ */
+ Object.entries(context).forEach(([key, value]) => {
+ if (encryptionContext[key] !== value)
+ throw new Error('Encryption Context does not match expected values')
+ })
})
/* This is not strictly speaking part of the example.
diff --git a/modules/example-node/src/multi_keyring.ts b/modules/example-node/src/multi_keyring.ts
index a2d39d94e..4a0ca084a 100644
--- a/modules/example-node/src/multi_keyring.ts
+++ b/modules/example-node/src/multi_keyring.ts
@@ -6,14 +6,22 @@
* to encrypt and decrypt using the AWS Encryption SDK for Javascript in Node.js.
*/
-import { MultiKeyringNode, KmsKeyringNode, RawAesKeyringNode, RawAesWrappingSuiteIdentifier, encrypt, decrypt } from '@aws-crypto/client-node'
+import {
+ MultiKeyringNode,
+ KmsKeyringNode,
+ RawAesKeyringNode,
+ RawAesWrappingSuiteIdentifier,
+ encrypt,
+ decrypt,
+} from '@aws-crypto/client-node'
import { randomBytes } from 'crypto'
-export async function multiKeyringTest () {
+export async function multiKeyringTest() {
/* A KMS CMK is required to generate the data key.
* You need kms:GenerateDataKey permission on the CMK in generatorKeyId.
*/
- const generatorKeyId = 'arn:aws:kms:us-west-2:658956600833:alias/EncryptDecrypt'
+ const generatorKeyId =
+ 'arn:aws:kms:us-west-2:658956600833:alias/EncryptDecrypt'
/* Adding alternate KMS keys that can decrypt.
* Access to kms:Encrypt is required for every CMK in keyIds.
@@ -22,7 +30,9 @@ export async function multiKeyringTest () {
* In this example, I am using the same CMK.
* This is *only* to demonstrate how the CMK ARNs are configured.
*/
- const keyIds = ['arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f']
+ const keyIds = [
+ 'arn:aws:kms:us-west-2:658956600833:key/b3537ef1-d8dc-4780-9f5a-55776cbb2f7f',
+ ]
/* The KMS keyring must be configured with the desired CMKs */
const kmsKeyring = new KmsKeyringNode({ generatorKeyId, keyIds })
@@ -35,15 +45,24 @@ export async function multiKeyringTest () {
const keyName = 'aes-name'
const keyNamespace = 'aes-namespace'
/* The wrapping suite defines the AES-GCM algorithm suite to use. */
- const wrappingSuite = RawAesWrappingSuiteIdentifier.AES256_GCM_IV12_TAG16_NO_PADDING
+ const wrappingSuite =
+ RawAesWrappingSuiteIdentifier.AES256_GCM_IV12_TAG16_NO_PADDING
// Get your plaintext master key from wherever you store it.
const unencryptedMasterKey = randomBytes(32)
/* Configure the Raw AES Keyring. */
- const aesKeyring = new RawAesKeyringNode({ keyName, keyNamespace, unencryptedMasterKey, wrappingSuite })
+ const aesKeyring = new RawAesKeyringNode({
+ keyName,
+ keyNamespace,
+ unencryptedMasterKey,
+ wrappingSuite,
+ })
/* Combine the two keyrings with a MultiKeyring. */
- const keyring = new MultiKeyringNode({ generator: kmsKeyring, children: [ aesKeyring ] })
+ const keyring = new MultiKeyringNode({
+ generator: kmsKeyring,
+ children: [aesKeyring],
+ })
/* Encryption context is a *very* powerful tool for controlling and managing access.
* It is ***not*** secret!
@@ -57,14 +76,16 @@ export async function multiKeyringTest () {
const context = {
stage: 'demo',
purpose: 'simple demonstration app',
- origin: 'us-west-2'
+ origin: 'us-west-2',
}
/* Find data to encrypt. A simple string. */
const cleartext = 'asdf'
/* Encrypt the data. */
- const { result } = await encrypt(keyring, cleartext, { encryptionContext: context })
+ const { result } = await encrypt(keyring, cleartext, {
+ encryptionContext: context,
+ })
/* Decrypt the data.
* This decrypt call could be done with **any** of the 3 keyrings.
@@ -85,11 +106,10 @@ export async function multiKeyringTest () {
* do not add a test that requires that all key-value pairs match.
* Instead, verify that the key-value pairs you expect match.
*/
- Object
- .entries(context)
- .forEach(([key, value]) => {
- if (encryptionContext[key] !== value) throw new Error('Encryption Context does not match expected values')
- })
+ Object.entries(context).forEach(([key, value]) => {
+ if (encryptionContext[key] !== value)
+ throw new Error('Encryption Context does not match expected values')
+ })
/* Return the values so the code can be tested. */
return { plaintext, result, cleartext, messageHeader }
diff --git a/modules/example-node/src/rsa_simple.ts b/modules/example-node/src/rsa_simple.ts
index 7a65820a3..1684c20c3 100644
--- a/modules/example-node/src/rsa_simple.ts
+++ b/modules/example-node/src/rsa_simple.ts
@@ -11,7 +11,7 @@ const generateKeyPairAsync = promisify(generateKeyPair)
* This function is an example of using the RsaKeyringNode
* to encrypt and decrypt a simple string
*/
-export async function rsaTest () {
+export async function rsaTest() {
/* You need to specify a name
* and a namespace for raw encryption key providers.
* The name and namespace that you use in the decryption keyring *must* be an exact,
@@ -40,14 +40,16 @@ export async function rsaTest () {
const context = {
stage: 'demo',
purpose: 'simple demonstration app',
- origin: 'us-west-2'
+ origin: 'us-west-2',
}
/* Find data to encrypt. A simple string. */
const cleartext = 'asdf'
/* Encrypt the data. */
- const { result } = await encrypt(keyring, cleartext, { encryptionContext: context })
+ const { result } = await encrypt(keyring, cleartext, {
+ encryptionContext: context,
+ })
/* Decrypt the data. */
const { plaintext, messageHeader } = await decrypt(keyring, result)
@@ -61,11 +63,10 @@ export async function rsaTest () {
* do not add a test that requires that all key-value pairs match.
* Instead, verify that the key-value pairs you expect match.
*/
- Object
- .entries(context)
- .forEach(([key, value]) => {
- if (encryptionContext[key] !== value) throw new Error('Encryption Context does not match expected values')
- })
+ Object.entries(context).forEach(([key, value]) => {
+ if (encryptionContext[key] !== value)
+ throw new Error('Encryption Context does not match expected values')
+ })
/* Return the values so the code can be tested. */
return { plaintext, result, cleartext }
@@ -74,7 +75,7 @@ export async function rsaTest () {
/**
* This is a helper function to generate an RSA key pair for testing purposes only.
*/
-async function generateRsaKeys () {
+async function generateRsaKeys() {
const modulusLength = 3072
const publicKeyEncoding = { type: 'pkcs1', format: 'pem' }
const privateKeyEncoding = { type: 'pkcs1', format: 'pem' }
@@ -82,6 +83,6 @@ async function generateRsaKeys () {
return generateKeyPairAsync('rsa', {
modulusLength,
publicKeyEncoding,
- privateKeyEncoding
+ privateKeyEncoding,
})
}
diff --git a/modules/hkdf-node/package.json b/modules/hkdf-node/package.json
index 014f3469c..c5177a81d 100644
--- a/modules/hkdf-node/package.json
+++ b/modules/hkdf-node/package.json
@@ -5,7 +5,9 @@
"scripts": {
"prepublishOnly": "npm run build",
"build": "tsc -b tsconfig.json && tsc -b tsconfig.module.json",
- "lint": "standard src/*.ts test/**/*.ts",
+ "lint": "run-s lint-*",
+ "lint-eslint": "npx eslint modules/**/src/*.ts modules/**/test/**/*.ts",
+ "lint-prettier": "prettier -c modules/**/src/*.ts modules/**/test/**/*.ts",
"mocha": "mocha --require ts-node/register test/**/*test.ts",
"test": "npm run lint && npm run coverage",
"coverage": "nyc -e .ts npm run mocha"
diff --git a/modules/hkdf-node/src/errors.ts b/modules/hkdf-node/src/errors.ts
index 96aa4a10d..0b7d7f927 100644
--- a/modules/hkdf-node/src/errors.ts
+++ b/modules/hkdf-node/src/errors.ts
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: Apache-2.0
export class HKDFError extends Error {
- constructor (message?: string) {
+ constructor(message?: string) {
super(message)
Object.setPrototypeOf(this, HKDFError.prototype)
}
@@ -10,15 +10,20 @@ export class HKDFError extends Error {
export class KeyLengthError extends HKDFError {
public name = 'KeyLengthError'
- constructor (maxLength: number, algorithm: string) {
- super('Can not derive keys larger than ' + maxLength + ' for algorithm:' + algorithm)
+ constructor(maxLength: number, algorithm: string) {
+ super(
+ 'Can not derive keys larger than ' +
+ maxLength +
+ ' for algorithm:' +
+ algorithm
+ )
Object.setPrototypeOf(this, KeyLengthError.prototype)
}
}
export class UnsupportedAlgorithm extends HKDFError {
public name = 'UnsupportedAlgorithm'
- constructor (algorithm: string) {
+ constructor(algorithm: string) {
super('Hash algorithm: ' + algorithm + ' is not an implemented algorithm')
Object.setPrototypeOf(this, UnsupportedAlgorithm.prototype)
}
diff --git a/modules/hkdf-node/src/hkdf.ts b/modules/hkdf-node/src/hkdf.ts
index a9d558c4c..f93f4f900 100644
--- a/modules/hkdf-node/src/hkdf.ts
+++ b/modules/hkdf-node/src/hkdf.ts
@@ -10,13 +10,15 @@ import { UnsupportedAlgorithm, KeyLengthError } from './errors'
* @param algorithm [String] The name of the hash algorithm to use
* @return [Function] The extract function decorated with expand and verify functions
*/
-export function HKDF (algorithm: string = 'sha256'): HKDFOutput {
+export function HKDF(algorithm = 'sha256'): HKDFOutput {
// Check the length and support
- try {
- var hashLength = createHash(algorithm).digest().length
- } catch (ex) {
- throw new UnsupportedAlgorithm(algorithm)
- }
+ const hashLength = (function () {
+ try {
+ return createHash(algorithm).digest().length
+ } catch (ex) {
+ throw new UnsupportedAlgorithm(algorithm)
+ }
+ })()
// (<= 255*HashLen) from https://tools.ietf.org/html/rfc5869
const maxLength = 255 * hashLength
@@ -36,9 +38,12 @@ export function HKDF (algorithm: string = 'sha256'): HKDFOutput {
* @param salt [String|Buffer] Optional salt for the extraction
* @return [Function] expand function with the extracted key curried onto it
*/
- function extractExpand (ikm: string|Uint8Array, salt?: string|Uint8Array|false) {
+ function extractExpand(
+ ikm: string | Uint8Array,
+ salt?: string | Uint8Array | false
+ ) {
const prk = extract(ikm, salt)
- return (length:number, info?:Uint8Array) => expand(prk, length, info)
+ return (length: number, info?: Uint8Array) => expand(prk, length, info)
}
/**
@@ -48,8 +53,11 @@ export function HKDF (algorithm: string = 'sha256'): HKDFOutput {
* @param salt [String|Buffer] Optional salt for the extraction
* @return [Buffer] the expanded key
*/
- function extract (ikm: string|Uint8Array, salt?: string|Uint8Array|false) {
- var _salt = salt || Buffer.alloc(hashLength, 0).toString()
+ function extract(
+ ikm: string | Uint8Array,
+ salt?: string | Uint8Array | false
+ ) {
+ const _salt = salt || Buffer.alloc(hashLength, 0).toString()
return createHmac(algorithm, _salt).update(ikm).digest()
}
@@ -61,21 +69,21 @@ export function HKDF (algorithm: string = 'sha256'): HKDFOutput {
* @param info [Buffer] Data to bind the expanded key to application/context specific information
* @return [Buffer] the expanded
*/
- function expand (prk:Uint8Array, length:number, info?:Uint8Array) {
+ function expand(prk: Uint8Array, length: number, info?: Uint8Array) {
if (length > maxLength) {
throw new KeyLengthError(maxLength, algorithm)
}
info = info || Buffer.alloc(0)
- var N = Math.ceil(length / hashLength)
- var memo: Buffer[] = []
+ const N = Math.ceil(length / hashLength)
+ const memo: Buffer[] = []
/* L/length octets are returned from T(1)...T(N), and T(0) is definitionally empty/zero length.
* Elide T(0) into the Buffer.alloc(0) case and then return L octets of T indexed 0...L-1.
*/
- for (var i = 0; i < N; i++) {
+ for (let i = 0; i < N; i++) {
memo[i] = createHmac(algorithm, prk)
- .update((memo[i - 1] || Buffer.alloc(0)))
+ .update(memo[i - 1] || Buffer.alloc(0))
.update(info)
.update(Buffer.alloc(1, i + 1))
.digest()
@@ -85,11 +93,11 @@ export function HKDF (algorithm: string = 'sha256'): HKDFOutput {
}
export interface Extract {
- (ikm: string|Uint8Array, salt?: string|Uint8Array|false): Buffer
+ (ikm: string | Uint8Array, salt?: string | Uint8Array | false): Buffer
}
export interface Expand {
- (prk:Uint8Array, length:number, info?:Uint8Array): Buffer
+ (prk: Uint8Array, length: number, info?: Uint8Array): Buffer
}
export interface HKDFOutput {
@@ -98,4 +106,9 @@ export interface HKDFOutput {
expand: Expand
}
-type Curry = ((...args: T) => void) extends (head: any, ...tail: infer U) => any ? U : never
+type Curry = ((...args: T) => void) extends (
+ head: any,
+ ...tail: infer U
+) => any
+ ? U
+ : never
diff --git a/modules/integration-browser/package.json b/modules/integration-browser/package.json
index fe858cdae..c9283330c 100644
--- a/modules/integration-browser/package.json
+++ b/modules/integration-browser/package.json
@@ -3,7 +3,9 @@
"version": "1.2.0",
"scripts": {
"build": "tsc -b tsconfig.json",
- "lint": "standard src/*.ts test/**/*.ts",
+ "lint": "run-s lint-*",
+ "lint-eslint": "npx eslint modules/**/src/*.ts modules/**/test/**/*.ts",
+ "lint-prettier": "prettier -c modules/**/src/*.ts modules/**/test/**/*.ts",
"karma": "karma start karma.conf.js",
"build_fixtures": "npx .",
"test": "npm run lint && npm run karma"
diff --git a/modules/integration-browser/src/build_decrypt_fixtures.ts b/modules/integration-browser/src/build_decrypt_fixtures.ts
index 1f448b07f..9f3bb2249 100644
--- a/modules/integration-browser/src/build_decrypt_fixtures.ts
+++ b/modules/integration-browser/src/build_decrypt_fixtures.ts
@@ -2,16 +2,12 @@
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
-import {
- open,
- Entry, // eslint-disable-line no-unused-vars
- ZipFile // eslint-disable-line no-unused-vars
-} from 'yauzl'
+import { open, Entry, ZipFile } from 'yauzl'
import streamToPromise from 'stream-to-promise'
import { writeFileSync } from 'fs'
-import { Readable } from 'stream' // eslint-disable-line no-unused-vars
+import { Readable } from 'stream'
-import { DecryptManifestList } from './types' // eslint-disable-line no-unused-vars
+import { DecryptManifestList } from './types'
/* This function interacts with manifest information
* and produces the fixtures in the `fixtures`
@@ -20,8 +16,15 @@ import { DecryptManifestList } from './types' // eslint-disable-line no-unused-v
* 1. The code is not tied to a specific copy of the manifest information
* 2. The tests can be run on a subset of tests for debugging.
*/
-export async function buildDecryptFixtures (fixtures: string, vectorFile: string, testName?: string, slice?: string) {
- const [start = 0, end = 9999] = (slice || '').split(':').map(n => parseInt(n, 10))
+export async function buildDecryptFixtures(
+ fixtures: string,
+ vectorFile: string,
+ testName?: string,
+ slice?: string
+) {
+ const [start = 0, end = 9999] = (slice || '')
+ .split(':')
+ .map((n) => parseInt(n, 10))
const filesMap = await centralDirectory(vectorFile)
@@ -39,7 +42,9 @@ export async function buildDecryptFixtures (fixtures: string, vectorFile: string
})()
const manifestBuffer = await readUriOnce('file://manifest.json')
- const { keys: keysFile, tests }: DecryptManifestList = JSON.parse(manifestBuffer.toString('utf8'))
+ const { keys: keysFile, tests }: DecryptManifestList = JSON.parse(
+ manifestBuffer.toString('utf8')
+ )
const keysBuffer = await readUriOnce(keysFile)
const { keys } = JSON.parse(keysBuffer.toString('utf8'))
const testNames = []
@@ -59,14 +64,19 @@ export async function buildDecryptFixtures (fixtures: string, vectorFile: string
testNames.push(name)
- const { plaintext: plaintextFile, ciphertext, 'master-keys': masterKeys } = testInfo
+ const {
+ plaintext: plaintextFile,
+ ciphertext,
+ 'master-keys': masterKeys,
+ } = testInfo
const plainTextInfo = filesMap.get(plaintextFile)
const cipherInfo = filesMap.get(ciphertext)
- if (!cipherInfo || !plainTextInfo) throw new Error(`no file for ${name}: ${ciphertext} | ${plaintextFile}`)
+ if (!cipherInfo || !plainTextInfo)
+ throw new Error(`no file for ${name}: ${ciphertext} | ${plaintextFile}`)
const cipherText = await streamToPromise(await cipherInfo.stream())
const plainText = await readUriOnce(`file://${plainTextInfo.fileName}`)
- const keysInfo = masterKeys.map(keyInfo => {
+ const keysInfo = masterKeys.map((keyInfo) => {
const key = keys[keyInfo.key]
if (!key) throw new Error(`no key for ${name}`)
return [keyInfo, key]
@@ -77,7 +87,7 @@ export async function buildDecryptFixtures (fixtures: string, vectorFile: string
keysInfo,
cipherFile: cipherInfo.fileName,
cipherText: cipherText.toString('base64'),
- plainText: plainText.toString('base64')
+ plainText: plainText.toString('base64'),
})
writeFileSync(`${fixtures}/${name}.json`, test)
@@ -90,29 +100,35 @@ interface StreamEntry extends Entry {
stream: () => Promise
}
-function centralDirectory (vectorFile: string): Promise