diff --git a/modules/encrypt-node/LICENSE b/modules/encrypt-node/LICENSE new file mode 100644 index 000000000..d64569567 --- /dev/null +++ b/modules/encrypt-node/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/modules/encrypt-node/NOTICE b/modules/encrypt-node/NOTICE new file mode 100644 index 000000000..88f7bea1e --- /dev/null +++ b/modules/encrypt-node/NOTICE @@ -0,0 +1,2 @@ +AWS Encryption SDK for Javascript +Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. diff --git a/modules/encrypt-node/package.json b/modules/encrypt-node/package.json new file mode 100644 index 000000000..57c9d4175 --- /dev/null +++ b/modules/encrypt-node/package.json @@ -0,0 +1,50 @@ +{ + "name": "@aws-crypto/encrypt-node", + "private": true, + "version": "0.0.1", + "scripts": { + "prepublishOnly": "tsc -p tsconfig.json && tsc -p tsconfig.module.json", + "lint": "standard src/*.ts 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" + }, + "author": { + "name": "AWS Crypto Tools Team", + "email": "aws-cryptools@amazon.com", + "url": "https://github.com/awslabs/aws-encryption-sdk-javascript" + }, + "license": "Apache-2.0", + "dependencies": { + "@aws-crypto/material-management-node": "^0.0.1", + "@aws-crypto/serialize": "^0.0.1", + "@types/duplexify": "^3.6.0", + "duplexify": "^4.0.0", + "readable-stream": "^3.2.0", + "tslib": "^1.9.3" + }, + "devDependencies": { + "@types/chai": "^4.1.4", + "@types/mocha": "^5.2.5", + "@types/node": "^11.11.4", + "@typescript-eslint/eslint-plugin": "^1.4.2", + "@typescript-eslint/parser": "^1.4.2", + "chai": "^4.1.2", + "mocha": "^5.2.0", + "nyc": "^12.0.2", + "standard": "^12.0.1", + "ts-node": "^7.0.1", + "typescript": "^3.2.0" + }, + "sideEffects": false, + "main": "./build/main/index.js", + "module": "./build/module/index.js", + "types": "./build/main/index.d.ts", + "files": ["./build/**/*"], + "standard": { + "parser": "@typescript-eslint/parser", + "plugins": [ + "@typescript-eslint" + ] + } +} diff --git a/modules/encrypt-node/src/encrypt.ts b/modules/encrypt-node/src/encrypt.ts new file mode 100644 index 000000000..2cef7bde5 --- /dev/null +++ b/modules/encrypt-node/src/encrypt.ts @@ -0,0 +1,61 @@ +import { + NodeCryptographicMaterialsManager // eslint-disable-line no-unused-vars +} from '@aws-crypto/material-management-node' +import { + encryptStream, + EncryptStreamInput // eslint-disable-line no-unused-vars +} 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 + +interface EncryptInput extends EncryptStreamInput { + encoding?: string +} + +export interface EncryptOutput { + ciphertext: Buffer + messageHeader: MessageHeader +} + +export async function encrypt ( + cmm: NodeCryptographicMaterialsManager, + plaintext: Buffer|Uint8Array|Readable|string, + op: EncryptInput = {} +): Promise { + const stream = encryptStream(cmm, op) + const { encoding } = op + + const ciphertext: Buffer[] = [] + let messageHeader: MessageHeader|false = false + stream + .once('MessageHeader', header => { messageHeader = header }) + .on('data', (chunk: Buffer) => ciphertext.push(chunk)) + + // This will check both Uint8Array|Buffer + if (plaintext instanceof Uint8Array) { + stream.end(plaintext) + } else if (typeof plaintext === 'string') { + stream.end(Buffer.from(plaintext, encoding)) + } else if (plaintext.readable) { + plaintext.pipe(stream) + } else { + throw new Error('Unsupported plaintext') + } + + await finishedAsync(stream) + if (!messageHeader) throw new Error('Unknown format') + + return { + ciphertext: Buffer.concat(ciphertext), + messageHeader + } +} + +function finishedAsync (stream: Duplex) { + return new Promise((resolve, reject) => { + 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 new file mode 100644 index 000000000..24df8831b --- /dev/null +++ b/modules/encrypt-node/src/encrypt_stream.ts @@ -0,0 +1,126 @@ +/* + * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). You may not use + * this file except in compliance with the License. A copy of the License is + * located at + * + * http://aws.amazon.com/apache2.0/ + * + * or in the "license" file accompanying this file. This file is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + * implied. See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + NodeCryptographicMaterialsManager, NodeAlgorithmSuite, AlgorithmSuiteIdentifier, // eslint-disable-line no-unused-vars + KeyringNode, NodeEncryptionMaterial, getEncryptHelper, EncryptionContext // eslint-disable-line no-unused-vars +} 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 +} from '@aws-crypto/serialize' + +// @ts-ignore +import { pipeline } from 'readable-stream' +import { Duplex } from 'stream' // eslint-disable-line no-unused-vars + +const fromUtf8 = (input: string) => Buffer.from(input, 'utf8') +const { serializeMessageHeader, headerAuthIv } = serializeFactory(fromUtf8) + +export interface EncryptStreamInput { + suiteId?: AlgorithmSuiteIdentifier + context?: EncryptionContext + frameLength?: number + plaintextLength?: number +} + +/** + * Takes a NodeCryptographicMaterialsManager or a KeyringNode that will + * be wrapped in a NodeCryptographicMaterialsManager and returns a stream. + * + * @param cmm NodeCryptographicMaterialsManager|KeyringNode + * @param op EncryptStreamInput + */ +export function encryptStream ( + cmm: NodeCryptographicMaterialsManager|KeyringNode, + op: EncryptStreamInput = {} +): Duplex { + const { suiteId, context, frameLength = 10 } = op + + /* If the cmm is not a MaterialsManager, wrap in one. + * I am expecting the NodeCryptographicMaterialsManager to + * handle non-keyring parameters. + */ + cmm = cmm instanceof NodeCryptographicMaterialsManager + ? cmm + : new NodeCryptographicMaterialsManager(cmm) + + const suite = suiteId && new NodeAlgorithmSuite(suiteId) + + const wrappingStream = new Duplexify() + + cmm.getEncryptionMaterials({ suite, encryptionContext: context, frameLength }) + .then(async ({ material, context }) => { + const { dispose, getSigner } = getEncryptHelper(material) + + const { getCipher, messageHeader, rawHeader } = getEncryptionInfo(material, frameLength, context) + + wrappingStream.emit('MessageHeader', messageHeader) + + const encryptStream = getFramedEncryptStream(getCipher, messageHeader, dispose) + const signatureStream = new SignatureStream(getSigner) + + pipeline(encryptStream, signatureStream) + + wrappingStream.setReadable(signatureStream) + // Flush the rawHeader through the signatureStream + rawHeader.forEach(buff => signatureStream.push(buff)) + + // @ts-ignore until readable-stream exports v3 types... + wrappingStream.setWritable(encryptStream) + }) + .catch(err => wrappingStream.emit('error', err)) + + return wrappingStream +} + +export function getEncryptionInfo (material : NodeEncryptionMaterial, frameLength: number, context: EncryptionContext) { + const { kdfGetCipher } = getEncryptHelper(material) + + const messageId = randomBytes(16) + const { id, ivLength } = material.suite + const messageHeader: MessageHeader = Object.freeze({ + version: SerializationVersion.V1, + type: ObjectType.CUSTOMER_AE_DATA, + suiteId: id, + messageId, + encryptionContext: context, + encryptedDataKeys: Object.freeze(material.encryptedDataKeys), // freeze me please + contentType: ContentType.FRAMED_DATA, + headerIvLength: ivLength, + frameLength + }) + + const { buffer, byteOffset, byteLength } = serializeMessageHeader(messageHeader) + const headerBuffer = Buffer.from(buffer, byteOffset, byteLength) + const info = kdfInfo(messageHeader.suiteId, messageHeader.messageId) + const getCipher = kdfGetCipher(info) + const headerIv = headerAuthIv(ivLength) + const validateHeader = getCipher(headerIv) + validateHeader.setAAD(headerBuffer) + validateHeader.update(Buffer.alloc(0)) + validateHeader.final() + const headerAuth = validateHeader.getAuthTag() + + return { + getCipher, + messageHeader, + rawHeader: [headerBuffer, headerIv, headerAuth] + } +} diff --git a/modules/encrypt-node/src/framed_encrypt_stream.ts b/modules/encrypt-node/src/framed_encrypt_stream.ts new file mode 100644 index 000000000..d16e79f2d --- /dev/null +++ b/modules/encrypt-node/src/framed_encrypt_stream.ts @@ -0,0 +1,191 @@ +/* + * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). You may not use + * this file except in compliance with the License. A copy of the License is + * located at + * + * http://aws.amazon.com/apache2.0/ + * + * or in the "license" file accompanying this file. This file is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + * implied. See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + serializeFactory, aadFactory, + MessageHeader // eslint-disable-line no-unused-vars +} from '@aws-crypto/serialize' +// @ts-ignore +import { Transform as PortableTransform } from 'readable-stream' +import { CipherGCM } from 'crypto' // eslint-disable-line no-unused-vars +import { Transform } from 'stream' // eslint-disable-line no-unused-vars +import { needs } from '@aws-crypto/material-management-node' + +const fromUtf8 = (input: string) => Buffer.from(input, 'utf8') +const serialize = serializeFactory(fromUtf8) +const { finalFrameHeader, frameHeader } = serialize +const aadUtility = aadFactory(fromUtf8) + +interface AccumulatingFrame { + contentLength: number + content: Buffer[] + sequenceNumber: number +} + +interface EncryptFrame { + content: Buffer[] + bodyHeader: Buffer + headerSent?: boolean + cipher: CipherGCM, + isFinalFrame: boolean +} + +const ioTick = () => new Promise(resolve => setImmediate(resolve)) +const noop = () => {} +type ErrBack = (err?: Error) => void + +export function getFramedEncryptStream (getCipher: GetCipher, messageHeader: MessageHeader, dispose: Function) { + let accumulatingFrame: AccumulatingFrame = { contentLength: 0, content: [], sequenceNumber: 1 } + let pathologicalDrain: Function = noop + const { frameLength } = messageHeader + + /* 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) { + const contentLeft = frameLength - accumulatingFrame.contentLength + + /* Check for early return (Postcondition): Have not accumulated a frame. */ + if (contentLeft > chunk.length) { + // eat more + accumulatingFrame.contentLength += chunk.length + accumulatingFrame.content.push(chunk) + return callback() + } + + accumulatingFrame.contentLength += contentLeft + accumulatingFrame.content.push(chunk.slice(0, contentLeft)) + + // grab the tail + const tail = chunk.slice(contentLeft) + + const encryptFrame = getEncryptFrame({ + pendingFrame: accumulatingFrame, + messageHeader, + getCipher, + isFinalFrame: false + }) + + // Reset frame state for next frame + const { sequenceNumber } = accumulatingFrame + accumulatingFrame = { + contentLength: 0, + content: [], + sequenceNumber: sequenceNumber + 1 + } + + this._flushEncryptFrame(encryptFrame) + .then(() => this._transform(tail, encoding, callback)) + .catch(callback) + } + + _flush (callback: ErrBack) { + const encryptFrame = getEncryptFrame({ + pendingFrame: accumulatingFrame, + messageHeader, + getCipher, + isFinalFrame: true + }) + + this._flushEncryptFrame(encryptFrame) + .then(() => callback()) + .catch(callback) + } + + _destroy () { + dispose() + } + + _read (size: number) { + super._read(size) + /* The _flushEncryptFrame encrypts and pushes the frame. + * If this.push returns false then this stream + * should wait until the destination stream calls read. + * This means that _flushEncryptFrame needs to wait for some + * indeterminate time. I create a closure around + * the resolution function for a promise that + * is created in _flushEncryptFrame. This way + * here in _read (the implementation of read) + * if a frame is being pushed, we can release + * it. + */ + pathologicalDrain() + pathologicalDrain = noop + } + + async _flushEncryptFrame (encryptingFrame: EncryptFrame) { + const { content, cipher, bodyHeader, isFinalFrame } = encryptingFrame + + this.push(bodyHeader) + + let frameSize = 0 + const cipherContent: Buffer[] = [] + for (const clearChunk of content) { + const cipherText = cipher.update(clearChunk) + frameSize += cipherText.length + cipherContent.push(cipherText) + await ioTick() + } + + /* Finalize the cipher and handle any tail. */ + const tail = cipher.final() + frameSize += tail.length + cipherContent.push(tail) + /* Push the authTag onto the end. Yes, I am abusing the name. */ + cipherContent.push(cipher.getAuthTag()) + + needs(frameSize === frameLength || isFinalFrame, '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 }) + } + } + + if (isFinalFrame) this.push(null) + } + })() +} + +type GetCipher = (iv: Uint8Array) => CipherGCM + +type EncryptFrameInput = { + pendingFrame: AccumulatingFrame, + messageHeader: MessageHeader, + getCipher: GetCipher, + isFinalFrame: boolean +} + +export function getEncryptFrame (input: EncryptFrameInput): EncryptFrame { + const { pendingFrame, messageHeader, getCipher, isFinalFrame } = input + const { sequenceNumber, contentLength, content } = pendingFrame + const frameIv = serialize.frameIv(messageHeader.headerIvLength, sequenceNumber) + const bodyHeader = Buffer.from(isFinalFrame + ? finalFrameHeader(sequenceNumber, frameIv, contentLength) + : frameHeader(sequenceNumber, frameIv)) + const { contentType, messageId } = messageHeader + 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)) + + return { content, cipher, bodyHeader, isFinalFrame } +} diff --git a/modules/encrypt-node/src/index.ts b/modules/encrypt-node/src/index.ts new file mode 100644 index 000000000..f398b68c1 --- /dev/null +++ b/modules/encrypt-node/src/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). You may not use + * this file except in compliance with the License. A copy of the License is + * located at + * + * http://aws.amazon.com/apache2.0/ + * + * or in the "license" file accompanying this file. This file is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + * implied. See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { encryptStream } from './encrypt_stream' +export { encrypt } from './encrypt' diff --git a/modules/encrypt-node/src/signature_stream.ts b/modules/encrypt-node/src/signature_stream.ts new file mode 100644 index 000000000..2f7bf947a --- /dev/null +++ b/modules/encrypt-node/src/signature_stream.ts @@ -0,0 +1,40 @@ +/* + * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). You may not use + * this file except in compliance with the License. A copy of the License is + * located at + * + * http://aws.amazon.com/apache2.0/ + * + * or in the "license" file accompanying this file. This file is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + * implied. See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Transform } from 'stream' +import { GetSigner } from '@aws-crypto/material-management-node' // eslint-disable-line no-unused-vars + +type AWSSigner = ReturnType + +export class SignatureStream extends Transform { + 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) { + // 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) { + this._signer && this.push(this._signer.awsCryptoSign()) + callback() + } +} diff --git a/modules/encrypt-node/test/encrypt.test.ts b/modules/encrypt-node/test/encrypt.test.ts new file mode 100644 index 000000000..6da1ed960 --- /dev/null +++ b/modules/encrypt-node/test/encrypt.test.ts @@ -0,0 +1,34 @@ +/* + * Copyright 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"). You may not use + * this file except in compliance with the License. A copy of the License is + * located at + * + * http://aws.amazon.com/apache2.0/ + * + * or in the "license" file accompanying this file. This file is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + * implied. See the License for the specific language governing permissions and + * limitations under the License. + */ + +/* eslint-env mocha */ + +// import { expect } from 'chai' +import 'mocha' +import { + NodeDecryptionMaterial, // eslint-disable-line no-unused-vars + NodeAlgorithmSuite, NodeEncryptionMaterial, NodeCryptographicMaterialsManager, KeyringNode, EncryptedDataKey, + KeyringTraceFlag, AlgorithmSuiteIdentifier +} from '@aws-crypto/material-management-node' + +import * as fs from 'fs' + +import { encryptStream, getEncryptionInfo } from '../src/encrypt_stream' + +import { getFramedEncryptStream } from '../src/framed_encrypt_stream' +import { SignatureStream } from '../src/signature_stream' +import { encrypt } from '../src/encrypt' + +const never = () => { throw new Error('never') } diff --git a/modules/encrypt-node/tsconfig.json b/modules/encrypt-node/tsconfig.json new file mode 100644 index 000000000..542835b87 --- /dev/null +++ b/modules/encrypt-node/tsconfig.json @@ -0,0 +1,13 @@ +{ + "extends": "../tsconfig.settings.json", + "compilerOptions": { + "outDir": "build/main", + "rootDir": "./src" + }, + "include": ["src/**/*.ts"], + "exclude": ["node_modules/**"], + "references": [ + { "path": "../material-management-node" }, + { "path": "../serialize" } + ] +} \ No newline at end of file diff --git a/modules/encrypt-node/tsconfig.module.json b/modules/encrypt-node/tsconfig.module.json new file mode 100644 index 000000000..50bf04db4 --- /dev/null +++ b/modules/encrypt-node/tsconfig.module.json @@ -0,0 +1,12 @@ +{ + "extends": "./tsconfig", + "compilerOptions": { + "target": "esnext", + "outDir": "build/module", + "module": "esnext", + "allowSyntheticDefaultImports": true + }, + "exclude": [ + "node_modules/**" + ] +} \ No newline at end of file diff --git a/modules/tsconfig.settings.json b/modules/tsconfig.settings.json index 0923458ef..179848215 100644 --- a/modules/tsconfig.settings.json +++ b/modules/tsconfig.settings.json @@ -22,9 +22,6 @@ "lib": ["es2017", "dom"], - "typeRoots": [ - "node_modules/@types" - ], "composite": true } } \ No newline at end of file