Backend half

This commit is contained in:
2025-07-11 19:56:28 +02:00
parent fa868e7c1d
commit 8600fa7c1d
19426 changed files with 3750448 additions and 8108 deletions
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2018-2022 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.
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.
@@ -0,0 +1,7 @@
# @aws-sdk/middleware-flexible-checksums
[![NPM version](https://img.shields.io/npm/v/@aws-sdk/middleware-flexible-checksums/latest.svg)](https://www.npmjs.com/package/@aws-sdk/middleware-flexible-checksums)
[![NPM downloads](https://img.shields.io/npm/dm/@aws-sdk/middleware-flexible-checksums.svg)](https://www.npmjs.com/package/@aws-sdk/middleware-flexible-checksums)
This package provides AWS SDK for JavaScript middleware that applies a checksum
of the request body as a header.
@@ -0,0 +1,6 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCrc32ChecksumAlgorithmFunction = void 0;
const crc32_1 = require("@aws-crypto/crc32");
const getCrc32ChecksumAlgorithmFunction = () => crc32_1.AwsCrc32;
exports.getCrc32ChecksumAlgorithmFunction = getCrc32ChecksumAlgorithmFunction;
@@ -0,0 +1,26 @@
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.getCrc32ChecksumAlgorithmFunction = void 0;
const tslib_1 = require("tslib");
const crc32_1 = require("@aws-crypto/crc32");
const util_1 = require("@aws-crypto/util");
const zlib = tslib_1.__importStar(require("zlib"));
class NodeCrc32 {
checksum = 0;
update(data) {
this.checksum = zlib.crc32(data, this.checksum);
}
async digest() {
return (0, util_1.numToUint8)(this.checksum);
}
reset() {
this.checksum = 0;
}
}
const getCrc32ChecksumAlgorithmFunction = () => {
if (typeof zlib.crc32 === "undefined") {
return crc32_1.AwsCrc32;
}
return NodeCrc32;
};
exports.getCrc32ChecksumAlgorithmFunction = getCrc32ChecksumAlgorithmFunction;
@@ -0,0 +1,525 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var index_exports = {};
__export(index_exports, {
CONFIG_REQUEST_CHECKSUM_CALCULATION: () => CONFIG_REQUEST_CHECKSUM_CALCULATION,
CONFIG_RESPONSE_CHECKSUM_VALIDATION: () => CONFIG_RESPONSE_CHECKSUM_VALIDATION,
ChecksumAlgorithm: () => ChecksumAlgorithm,
ChecksumLocation: () => ChecksumLocation,
DEFAULT_CHECKSUM_ALGORITHM: () => DEFAULT_CHECKSUM_ALGORITHM,
DEFAULT_REQUEST_CHECKSUM_CALCULATION: () => DEFAULT_REQUEST_CHECKSUM_CALCULATION,
DEFAULT_RESPONSE_CHECKSUM_VALIDATION: () => DEFAULT_RESPONSE_CHECKSUM_VALIDATION,
ENV_REQUEST_CHECKSUM_CALCULATION: () => ENV_REQUEST_CHECKSUM_CALCULATION,
ENV_RESPONSE_CHECKSUM_VALIDATION: () => ENV_RESPONSE_CHECKSUM_VALIDATION,
NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS: () => NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS,
NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS: () => NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS,
RequestChecksumCalculation: () => RequestChecksumCalculation,
ResponseChecksumValidation: () => ResponseChecksumValidation,
crc64NvmeCrtContainer: () => crc64NvmeCrtContainer,
flexibleChecksumsMiddleware: () => flexibleChecksumsMiddleware,
flexibleChecksumsMiddlewareOptions: () => flexibleChecksumsMiddlewareOptions,
getFlexibleChecksumsPlugin: () => getFlexibleChecksumsPlugin,
resolveFlexibleChecksumsConfig: () => resolveFlexibleChecksumsConfig
});
module.exports = __toCommonJS(index_exports);
// src/constants.ts
var RequestChecksumCalculation = {
/**
* When set, a checksum will be calculated for all request payloads of operations
* modeled with the {@link httpChecksum} trait where `requestChecksumRequired` is `true`
* AND/OR a `requestAlgorithmMember` is modeled.
* {@link https://smithy.io/2.0/aws/aws-core.html#aws-protocols-httpchecksum-trait httpChecksum}
*/
WHEN_SUPPORTED: "WHEN_SUPPORTED",
/**
* When set, a checksum will only be calculated for request payloads of operations
* modeled with the {@link httpChecksum} trait where `requestChecksumRequired` is `true`
* OR where a `requestAlgorithmMember` is modeled and the user sets it.
* {@link https://smithy.io/2.0/aws/aws-core.html#aws-protocols-httpchecksum-trait httpChecksum}
*/
WHEN_REQUIRED: "WHEN_REQUIRED"
};
var DEFAULT_REQUEST_CHECKSUM_CALCULATION = RequestChecksumCalculation.WHEN_SUPPORTED;
var ResponseChecksumValidation = {
/**
* When set, checksum validation MUST be performed on all response payloads of operations
* modeled with the {@link httpChecksum} trait where `responseAlgorithms` is modeled,
* except when no modeled checksum algorithms are supported by an SDK.
* {@link https://smithy.io/2.0/aws/aws-core.html#aws-protocols-httpchecksum-trait httpChecksum}
*/
WHEN_SUPPORTED: "WHEN_SUPPORTED",
/**
* When set, checksum validation MUST NOT be performed on response payloads of operations UNLESS
* the SDK supports the modeled checksum algorithms AND the user has set the `requestValidationModeMember` to `ENABLED`.
* It is currently impossible to model an operation as requiring a response checksum,
* but this setting leaves the door open for future updates.
*/
WHEN_REQUIRED: "WHEN_REQUIRED"
};
var DEFAULT_RESPONSE_CHECKSUM_VALIDATION = RequestChecksumCalculation.WHEN_SUPPORTED;
var ChecksumAlgorithm = /* @__PURE__ */ ((ChecksumAlgorithm3) => {
ChecksumAlgorithm3["MD5"] = "MD5";
ChecksumAlgorithm3["CRC32"] = "CRC32";
ChecksumAlgorithm3["CRC32C"] = "CRC32C";
ChecksumAlgorithm3["CRC64NVME"] = "CRC64NVME";
ChecksumAlgorithm3["SHA1"] = "SHA1";
ChecksumAlgorithm3["SHA256"] = "SHA256";
return ChecksumAlgorithm3;
})(ChecksumAlgorithm || {});
var ChecksumLocation = /* @__PURE__ */ ((ChecksumLocation2) => {
ChecksumLocation2["HEADER"] = "header";
ChecksumLocation2["TRAILER"] = "trailer";
return ChecksumLocation2;
})(ChecksumLocation || {});
var DEFAULT_CHECKSUM_ALGORITHM = "CRC32" /* CRC32 */;
// src/stringUnionSelector.ts
var stringUnionSelector = /* @__PURE__ */ __name((obj, key, union, type) => {
if (!(key in obj)) return void 0;
const value = obj[key].toUpperCase();
if (!Object.values(union).includes(value)) {
throw new TypeError(`Cannot load ${type} '${key}'. Expected one of ${Object.values(union)}, got '${obj[key]}'.`);
}
return value;
}, "stringUnionSelector");
// src/NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS.ts
var ENV_REQUEST_CHECKSUM_CALCULATION = "AWS_REQUEST_CHECKSUM_CALCULATION";
var CONFIG_REQUEST_CHECKSUM_CALCULATION = "request_checksum_calculation";
var NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS = {
environmentVariableSelector: /* @__PURE__ */ __name((env) => stringUnionSelector(env, ENV_REQUEST_CHECKSUM_CALCULATION, RequestChecksumCalculation, "env" /* ENV */), "environmentVariableSelector"),
configFileSelector: /* @__PURE__ */ __name((profile) => stringUnionSelector(profile, CONFIG_REQUEST_CHECKSUM_CALCULATION, RequestChecksumCalculation, "shared config entry" /* CONFIG */), "configFileSelector"),
default: DEFAULT_REQUEST_CHECKSUM_CALCULATION
};
// src/NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS.ts
var ENV_RESPONSE_CHECKSUM_VALIDATION = "AWS_RESPONSE_CHECKSUM_VALIDATION";
var CONFIG_RESPONSE_CHECKSUM_VALIDATION = "response_checksum_validation";
var NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS = {
environmentVariableSelector: /* @__PURE__ */ __name((env) => stringUnionSelector(env, ENV_RESPONSE_CHECKSUM_VALIDATION, ResponseChecksumValidation, "env" /* ENV */), "environmentVariableSelector"),
configFileSelector: /* @__PURE__ */ __name((profile) => stringUnionSelector(profile, CONFIG_RESPONSE_CHECKSUM_VALIDATION, ResponseChecksumValidation, "shared config entry" /* CONFIG */), "configFileSelector"),
default: DEFAULT_RESPONSE_CHECKSUM_VALIDATION
};
// src/crc64-nvme-crt-container.ts
var crc64NvmeCrtContainer = {
CrtCrc64Nvme: null
};
// src/flexibleChecksumsMiddleware.ts
var import_core = require("@aws-sdk/core");
var import_protocol_http = require("@smithy/protocol-http");
var import_util_stream = require("@smithy/util-stream");
// src/types.ts
var CLIENT_SUPPORTED_ALGORITHMS = [
"CRC32" /* CRC32 */,
"CRC32C" /* CRC32C */,
"CRC64NVME" /* CRC64NVME */,
"SHA1" /* SHA1 */,
"SHA256" /* SHA256 */
];
var PRIORITY_ORDER_ALGORITHMS = [
"SHA256" /* SHA256 */,
"SHA1" /* SHA1 */,
"CRC32" /* CRC32 */,
"CRC32C" /* CRC32C */,
"CRC64NVME" /* CRC64NVME */
];
// src/getChecksumAlgorithmForRequest.ts
var getChecksumAlgorithmForRequest = /* @__PURE__ */ __name((input, { requestChecksumRequired, requestAlgorithmMember, requestChecksumCalculation }) => {
if (!requestAlgorithmMember) {
return requestChecksumCalculation === RequestChecksumCalculation.WHEN_SUPPORTED || requestChecksumRequired ? DEFAULT_CHECKSUM_ALGORITHM : void 0;
}
if (!input[requestAlgorithmMember]) {
return void 0;
}
const checksumAlgorithm = input[requestAlgorithmMember];
if (!CLIENT_SUPPORTED_ALGORITHMS.includes(checksumAlgorithm)) {
throw new Error(
`The checksum algorithm "${checksumAlgorithm}" is not supported by the client. Select one of ${CLIENT_SUPPORTED_ALGORITHMS}.`
);
}
return checksumAlgorithm;
}, "getChecksumAlgorithmForRequest");
// src/getChecksumLocationName.ts
var getChecksumLocationName = /* @__PURE__ */ __name((algorithm) => algorithm === "MD5" /* MD5 */ ? "content-md5" : `x-amz-checksum-${algorithm.toLowerCase()}`, "getChecksumLocationName");
// src/hasHeader.ts
var hasHeader = /* @__PURE__ */ __name((header, headers) => {
const soughtHeader = header.toLowerCase();
for (const headerName of Object.keys(headers)) {
if (soughtHeader === headerName.toLowerCase()) {
return true;
}
}
return false;
}, "hasHeader");
// src/hasHeaderWithPrefix.ts
var hasHeaderWithPrefix = /* @__PURE__ */ __name((headerPrefix, headers) => {
const soughtHeaderPrefix = headerPrefix.toLowerCase();
for (const headerName of Object.keys(headers)) {
if (headerName.toLowerCase().startsWith(soughtHeaderPrefix)) {
return true;
}
}
return false;
}, "hasHeaderWithPrefix");
// src/isStreaming.ts
var import_is_array_buffer = require("@smithy/is-array-buffer");
var isStreaming = /* @__PURE__ */ __name((body) => body !== void 0 && typeof body !== "string" && !ArrayBuffer.isView(body) && !(0, import_is_array_buffer.isArrayBuffer)(body), "isStreaming");
// src/selectChecksumAlgorithmFunction.ts
var import_crc32c = require("@aws-crypto/crc32c");
var import_getCrc32ChecksumAlgorithmFunction = require("././getCrc32ChecksumAlgorithmFunction");
var selectChecksumAlgorithmFunction = /* @__PURE__ */ __name((checksumAlgorithm, config) => {
switch (checksumAlgorithm) {
case "MD5" /* MD5 */:
return config.md5;
case "CRC32" /* CRC32 */:
return (0, import_getCrc32ChecksumAlgorithmFunction.getCrc32ChecksumAlgorithmFunction)();
case "CRC32C" /* CRC32C */:
return import_crc32c.AwsCrc32c;
case "CRC64NVME" /* CRC64NVME */:
if (typeof crc64NvmeCrtContainer.CrtCrc64Nvme !== "function") {
throw new Error(
`Please check whether you have installed the "@aws-sdk/crc64-nvme-crt" package explicitly.
You must also register the package by calling [require("@aws-sdk/crc64-nvme-crt");] or an ESM equivalent such as [import "@aws-sdk/crc64-nvme-crt";].
For more information please go to https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt`
);
}
return crc64NvmeCrtContainer.CrtCrc64Nvme;
case "SHA1" /* SHA1 */:
return config.sha1;
case "SHA256" /* SHA256 */:
return config.sha256;
default:
throw new Error(`Unsupported checksum algorithm: ${checksumAlgorithm}`);
}
}, "selectChecksumAlgorithmFunction");
// src/stringHasher.ts
var import_util_utf8 = require("@smithy/util-utf8");
var stringHasher = /* @__PURE__ */ __name((checksumAlgorithmFn, body) => {
const hash = new checksumAlgorithmFn();
hash.update((0, import_util_utf8.toUint8Array)(body || ""));
return hash.digest();
}, "stringHasher");
// src/flexibleChecksumsMiddleware.ts
var flexibleChecksumsMiddlewareOptions = {
name: "flexibleChecksumsMiddleware",
step: "build",
tags: ["BODY_CHECKSUM"],
override: true
};
var flexibleChecksumsMiddleware = /* @__PURE__ */ __name((config, middlewareConfig) => (next, context) => async (args) => {
if (!import_protocol_http.HttpRequest.isInstance(args.request)) {
return next(args);
}
if (hasHeaderWithPrefix("x-amz-checksum-", args.request.headers)) {
return next(args);
}
const { request, input } = args;
const { body: requestBody, headers } = request;
const { base64Encoder, streamHasher } = config;
const { requestChecksumRequired, requestAlgorithmMember } = middlewareConfig;
const requestChecksumCalculation = await config.requestChecksumCalculation();
const requestAlgorithmMemberName = requestAlgorithmMember?.name;
const requestAlgorithmMemberHttpHeader = requestAlgorithmMember?.httpHeader;
if (requestAlgorithmMemberName && !input[requestAlgorithmMemberName]) {
if (requestChecksumCalculation === RequestChecksumCalculation.WHEN_SUPPORTED || requestChecksumRequired) {
input[requestAlgorithmMemberName] = DEFAULT_CHECKSUM_ALGORITHM;
if (requestAlgorithmMemberHttpHeader) {
headers[requestAlgorithmMemberHttpHeader] = DEFAULT_CHECKSUM_ALGORITHM;
}
}
}
const checksumAlgorithm = getChecksumAlgorithmForRequest(input, {
requestChecksumRequired,
requestAlgorithmMember: requestAlgorithmMember?.name,
requestChecksumCalculation
});
let updatedBody = requestBody;
let updatedHeaders = headers;
if (checksumAlgorithm) {
switch (checksumAlgorithm) {
case "CRC32" /* CRC32 */:
(0, import_core.setFeature)(context, "FLEXIBLE_CHECKSUMS_REQ_CRC32", "U");
break;
case "CRC32C" /* CRC32C */:
(0, import_core.setFeature)(context, "FLEXIBLE_CHECKSUMS_REQ_CRC32C", "V");
break;
case "CRC64NVME" /* CRC64NVME */:
(0, import_core.setFeature)(context, "FLEXIBLE_CHECKSUMS_REQ_CRC64", "W");
break;
case "SHA1" /* SHA1 */:
(0, import_core.setFeature)(context, "FLEXIBLE_CHECKSUMS_REQ_SHA1", "X");
break;
case "SHA256" /* SHA256 */:
(0, import_core.setFeature)(context, "FLEXIBLE_CHECKSUMS_REQ_SHA256", "Y");
break;
}
const checksumLocationName = getChecksumLocationName(checksumAlgorithm);
const checksumAlgorithmFn = selectChecksumAlgorithmFunction(checksumAlgorithm, config);
if (isStreaming(requestBody)) {
const { getAwsChunkedEncodingStream, bodyLengthChecker } = config;
updatedBody = getAwsChunkedEncodingStream(
typeof config.requestStreamBufferSize === "number" && config.requestStreamBufferSize >= 8 * 1024 ? (0, import_util_stream.createBufferedReadable)(requestBody, config.requestStreamBufferSize, context.logger) : requestBody,
{
base64Encoder,
bodyLengthChecker,
checksumLocationName,
checksumAlgorithmFn,
streamHasher
}
);
updatedHeaders = {
...headers,
"content-encoding": headers["content-encoding"] ? `${headers["content-encoding"]},aws-chunked` : "aws-chunked",
"transfer-encoding": "chunked",
"x-amz-decoded-content-length": headers["content-length"],
"x-amz-content-sha256": "STREAMING-UNSIGNED-PAYLOAD-TRAILER",
"x-amz-trailer": checksumLocationName
};
delete updatedHeaders["content-length"];
} else if (!hasHeader(checksumLocationName, headers)) {
const rawChecksum = await stringHasher(checksumAlgorithmFn, requestBody);
updatedHeaders = {
...headers,
[checksumLocationName]: base64Encoder(rawChecksum)
};
}
}
const result = await next({
...args,
request: {
...request,
headers: updatedHeaders,
body: updatedBody
}
});
return result;
}, "flexibleChecksumsMiddleware");
// src/flexibleChecksumsInputMiddleware.ts
var flexibleChecksumsInputMiddlewareOptions = {
name: "flexibleChecksumsInputMiddleware",
toMiddleware: "serializerMiddleware",
relation: "before",
tags: ["BODY_CHECKSUM"],
override: true
};
var flexibleChecksumsInputMiddleware = /* @__PURE__ */ __name((config, middlewareConfig) => (next, context) => async (args) => {
const input = args.input;
const { requestValidationModeMember } = middlewareConfig;
const requestChecksumCalculation = await config.requestChecksumCalculation();
const responseChecksumValidation = await config.responseChecksumValidation();
switch (requestChecksumCalculation) {
case RequestChecksumCalculation.WHEN_REQUIRED:
(0, import_core.setFeature)(context, "FLEXIBLE_CHECKSUMS_REQ_WHEN_REQUIRED", "a");
break;
case RequestChecksumCalculation.WHEN_SUPPORTED:
(0, import_core.setFeature)(context, "FLEXIBLE_CHECKSUMS_REQ_WHEN_SUPPORTED", "Z");
break;
}
switch (responseChecksumValidation) {
case ResponseChecksumValidation.WHEN_REQUIRED:
(0, import_core.setFeature)(context, "FLEXIBLE_CHECKSUMS_RES_WHEN_REQUIRED", "c");
break;
case ResponseChecksumValidation.WHEN_SUPPORTED:
(0, import_core.setFeature)(context, "FLEXIBLE_CHECKSUMS_RES_WHEN_SUPPORTED", "b");
break;
}
if (requestValidationModeMember && !input[requestValidationModeMember]) {
if (responseChecksumValidation === ResponseChecksumValidation.WHEN_SUPPORTED) {
input[requestValidationModeMember] = "ENABLED";
}
}
return next(args);
}, "flexibleChecksumsInputMiddleware");
// src/flexibleChecksumsResponseMiddleware.ts
// src/getChecksumAlgorithmListForResponse.ts
var getChecksumAlgorithmListForResponse = /* @__PURE__ */ __name((responseAlgorithms = []) => {
const validChecksumAlgorithms = [];
for (const algorithm of PRIORITY_ORDER_ALGORITHMS) {
if (!responseAlgorithms.includes(algorithm) || !CLIENT_SUPPORTED_ALGORITHMS.includes(algorithm)) {
continue;
}
validChecksumAlgorithms.push(algorithm);
}
return validChecksumAlgorithms;
}, "getChecksumAlgorithmListForResponse");
// src/isChecksumWithPartNumber.ts
var isChecksumWithPartNumber = /* @__PURE__ */ __name((checksum) => {
const lastHyphenIndex = checksum.lastIndexOf("-");
if (lastHyphenIndex !== -1) {
const numberPart = checksum.slice(lastHyphenIndex + 1);
if (!numberPart.startsWith("0")) {
const number = parseInt(numberPart, 10);
if (!isNaN(number) && number >= 1 && number <= 1e4) {
return true;
}
}
}
return false;
}, "isChecksumWithPartNumber");
// src/validateChecksumFromResponse.ts
// src/getChecksum.ts
var getChecksum = /* @__PURE__ */ __name(async (body, { checksumAlgorithmFn, base64Encoder }) => base64Encoder(await stringHasher(checksumAlgorithmFn, body)), "getChecksum");
// src/validateChecksumFromResponse.ts
var validateChecksumFromResponse = /* @__PURE__ */ __name(async (response, { config, responseAlgorithms, logger }) => {
const checksumAlgorithms = getChecksumAlgorithmListForResponse(responseAlgorithms);
const { body: responseBody, headers: responseHeaders } = response;
for (const algorithm of checksumAlgorithms) {
const responseHeader = getChecksumLocationName(algorithm);
const checksumFromResponse = responseHeaders[responseHeader];
if (checksumFromResponse) {
let checksumAlgorithmFn;
try {
checksumAlgorithmFn = selectChecksumAlgorithmFunction(algorithm, config);
} catch (error) {
if (algorithm === "CRC64NVME" /* CRC64NVME */) {
logger?.warn(`Skipping ${"CRC64NVME" /* CRC64NVME */} checksum validation: ${error.message}`);
continue;
}
throw error;
}
const { base64Encoder } = config;
if (isStreaming(responseBody)) {
response.body = (0, import_util_stream.createChecksumStream)({
expectedChecksum: checksumFromResponse,
checksumSourceLocation: responseHeader,
checksum: new checksumAlgorithmFn(),
source: responseBody,
base64Encoder
});
return;
}
const checksum = await getChecksum(responseBody, { checksumAlgorithmFn, base64Encoder });
if (checksum === checksumFromResponse) {
break;
}
throw new Error(
`Checksum mismatch: expected "${checksum}" but received "${checksumFromResponse}" in response header "${responseHeader}".`
);
}
}
}, "validateChecksumFromResponse");
// src/flexibleChecksumsResponseMiddleware.ts
var flexibleChecksumsResponseMiddlewareOptions = {
name: "flexibleChecksumsResponseMiddleware",
toMiddleware: "deserializerMiddleware",
relation: "after",
tags: ["BODY_CHECKSUM"],
override: true
};
var flexibleChecksumsResponseMiddleware = /* @__PURE__ */ __name((config, middlewareConfig) => (next, context) => async (args) => {
if (!import_protocol_http.HttpRequest.isInstance(args.request)) {
return next(args);
}
const input = args.input;
const result = await next(args);
const response = result.response;
const { requestValidationModeMember, responseAlgorithms } = middlewareConfig;
if (requestValidationModeMember && input[requestValidationModeMember] === "ENABLED") {
const { clientName, commandName } = context;
const isS3WholeObjectMultipartGetResponseChecksum = clientName === "S3Client" && commandName === "GetObjectCommand" && getChecksumAlgorithmListForResponse(responseAlgorithms).every((algorithm) => {
const responseHeader = getChecksumLocationName(algorithm);
const checksumFromResponse = response.headers[responseHeader];
return !checksumFromResponse || isChecksumWithPartNumber(checksumFromResponse);
});
if (isS3WholeObjectMultipartGetResponseChecksum) {
return result;
}
await validateChecksumFromResponse(response, {
config,
responseAlgorithms,
logger: context.logger
});
}
return result;
}, "flexibleChecksumsResponseMiddleware");
// src/getFlexibleChecksumsPlugin.ts
var getFlexibleChecksumsPlugin = /* @__PURE__ */ __name((config, middlewareConfig) => ({
applyToStack: /* @__PURE__ */ __name((clientStack) => {
clientStack.add(flexibleChecksumsMiddleware(config, middlewareConfig), flexibleChecksumsMiddlewareOptions);
clientStack.addRelativeTo(
flexibleChecksumsInputMiddleware(config, middlewareConfig),
flexibleChecksumsInputMiddlewareOptions
);
clientStack.addRelativeTo(
flexibleChecksumsResponseMiddleware(config, middlewareConfig),
flexibleChecksumsResponseMiddlewareOptions
);
}, "applyToStack")
}), "getFlexibleChecksumsPlugin");
// src/resolveFlexibleChecksumsConfig.ts
var import_util_middleware = require("@smithy/util-middleware");
var resolveFlexibleChecksumsConfig = /* @__PURE__ */ __name((input) => {
const { requestChecksumCalculation, responseChecksumValidation, requestStreamBufferSize } = input;
return Object.assign(input, {
requestChecksumCalculation: (0, import_util_middleware.normalizeProvider)(requestChecksumCalculation ?? DEFAULT_REQUEST_CHECKSUM_CALCULATION),
responseChecksumValidation: (0, import_util_middleware.normalizeProvider)(responseChecksumValidation ?? DEFAULT_RESPONSE_CHECKSUM_VALIDATION),
requestStreamBufferSize: Number(requestStreamBufferSize ?? 0)
});
}, "resolveFlexibleChecksumsConfig");
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
ENV_REQUEST_CHECKSUM_CALCULATION,
CONFIG_REQUEST_CHECKSUM_CALCULATION,
NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS,
ENV_RESPONSE_CHECKSUM_VALIDATION,
CONFIG_RESPONSE_CHECKSUM_VALIDATION,
NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS,
RequestChecksumCalculation,
DEFAULT_REQUEST_CHECKSUM_CALCULATION,
ResponseChecksumValidation,
DEFAULT_RESPONSE_CHECKSUM_VALIDATION,
ChecksumAlgorithm,
ChecksumLocation,
DEFAULT_CHECKSUM_ALGORITHM,
crc64NvmeCrtContainer,
flexibleChecksumsMiddlewareOptions,
flexibleChecksumsMiddleware,
getFlexibleChecksumsPlugin,
resolveFlexibleChecksumsConfig
});
@@ -0,0 +1,9 @@
import { DEFAULT_REQUEST_CHECKSUM_CALCULATION, RequestChecksumCalculation } from "./constants";
import { SelectorType, stringUnionSelector } from "./stringUnionSelector";
export const ENV_REQUEST_CHECKSUM_CALCULATION = "AWS_REQUEST_CHECKSUM_CALCULATION";
export const CONFIG_REQUEST_CHECKSUM_CALCULATION = "request_checksum_calculation";
export const NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS = {
environmentVariableSelector: (env) => stringUnionSelector(env, ENV_REQUEST_CHECKSUM_CALCULATION, RequestChecksumCalculation, SelectorType.ENV),
configFileSelector: (profile) => stringUnionSelector(profile, CONFIG_REQUEST_CHECKSUM_CALCULATION, RequestChecksumCalculation, SelectorType.CONFIG),
default: DEFAULT_REQUEST_CHECKSUM_CALCULATION,
};
@@ -0,0 +1,9 @@
import { DEFAULT_RESPONSE_CHECKSUM_VALIDATION, ResponseChecksumValidation } from "./constants";
import { SelectorType, stringUnionSelector } from "./stringUnionSelector";
export const ENV_RESPONSE_CHECKSUM_VALIDATION = "AWS_RESPONSE_CHECKSUM_VALIDATION";
export const CONFIG_RESPONSE_CHECKSUM_VALIDATION = "response_checksum_validation";
export const NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS = {
environmentVariableSelector: (env) => stringUnionSelector(env, ENV_RESPONSE_CHECKSUM_VALIDATION, ResponseChecksumValidation, SelectorType.ENV),
configFileSelector: (profile) => stringUnionSelector(profile, CONFIG_RESPONSE_CHECKSUM_VALIDATION, ResponseChecksumValidation, SelectorType.CONFIG),
default: DEFAULT_RESPONSE_CHECKSUM_VALIDATION,
};
@@ -0,0 +1 @@
export {};
@@ -0,0 +1,25 @@
export const RequestChecksumCalculation = {
WHEN_SUPPORTED: "WHEN_SUPPORTED",
WHEN_REQUIRED: "WHEN_REQUIRED",
};
export const DEFAULT_REQUEST_CHECKSUM_CALCULATION = RequestChecksumCalculation.WHEN_SUPPORTED;
export const ResponseChecksumValidation = {
WHEN_SUPPORTED: "WHEN_SUPPORTED",
WHEN_REQUIRED: "WHEN_REQUIRED",
};
export const DEFAULT_RESPONSE_CHECKSUM_VALIDATION = RequestChecksumCalculation.WHEN_SUPPORTED;
export var ChecksumAlgorithm;
(function (ChecksumAlgorithm) {
ChecksumAlgorithm["MD5"] = "MD5";
ChecksumAlgorithm["CRC32"] = "CRC32";
ChecksumAlgorithm["CRC32C"] = "CRC32C";
ChecksumAlgorithm["CRC64NVME"] = "CRC64NVME";
ChecksumAlgorithm["SHA1"] = "SHA1";
ChecksumAlgorithm["SHA256"] = "SHA256";
})(ChecksumAlgorithm || (ChecksumAlgorithm = {}));
export var ChecksumLocation;
(function (ChecksumLocation) {
ChecksumLocation["HEADER"] = "header";
ChecksumLocation["TRAILER"] = "trailer";
})(ChecksumLocation || (ChecksumLocation = {}));
export const DEFAULT_CHECKSUM_ALGORITHM = ChecksumAlgorithm.CRC32;
@@ -0,0 +1,3 @@
export const crc64NvmeCrtContainer = {
CrtCrc64Nvme: null,
};
@@ -0,0 +1,37 @@
import { setFeature } from "@aws-sdk/core";
import { RequestChecksumCalculation, ResponseChecksumValidation } from "./constants";
export const flexibleChecksumsInputMiddlewareOptions = {
name: "flexibleChecksumsInputMiddleware",
toMiddleware: "serializerMiddleware",
relation: "before",
tags: ["BODY_CHECKSUM"],
override: true,
};
export const flexibleChecksumsInputMiddleware = (config, middlewareConfig) => (next, context) => async (args) => {
const input = args.input;
const { requestValidationModeMember } = middlewareConfig;
const requestChecksumCalculation = await config.requestChecksumCalculation();
const responseChecksumValidation = await config.responseChecksumValidation();
switch (requestChecksumCalculation) {
case RequestChecksumCalculation.WHEN_REQUIRED:
setFeature(context, "FLEXIBLE_CHECKSUMS_REQ_WHEN_REQUIRED", "a");
break;
case RequestChecksumCalculation.WHEN_SUPPORTED:
setFeature(context, "FLEXIBLE_CHECKSUMS_REQ_WHEN_SUPPORTED", "Z");
break;
}
switch (responseChecksumValidation) {
case ResponseChecksumValidation.WHEN_REQUIRED:
setFeature(context, "FLEXIBLE_CHECKSUMS_RES_WHEN_REQUIRED", "c");
break;
case ResponseChecksumValidation.WHEN_SUPPORTED:
setFeature(context, "FLEXIBLE_CHECKSUMS_RES_WHEN_SUPPORTED", "b");
break;
}
if (requestValidationModeMember && !input[requestValidationModeMember]) {
if (responseChecksumValidation === ResponseChecksumValidation.WHEN_SUPPORTED) {
input[requestValidationModeMember] = "ENABLED";
}
}
return next(args);
};
@@ -0,0 +1,107 @@
import { setFeature } from "@aws-sdk/core";
import { HttpRequest } from "@smithy/protocol-http";
import { createBufferedReadable } from "@smithy/util-stream";
import { ChecksumAlgorithm, DEFAULT_CHECKSUM_ALGORITHM, RequestChecksumCalculation } from "./constants";
import { getChecksumAlgorithmForRequest } from "./getChecksumAlgorithmForRequest";
import { getChecksumLocationName } from "./getChecksumLocationName";
import { hasHeader } from "./hasHeader";
import { hasHeaderWithPrefix } from "./hasHeaderWithPrefix";
import { isStreaming } from "./isStreaming";
import { selectChecksumAlgorithmFunction } from "./selectChecksumAlgorithmFunction";
import { stringHasher } from "./stringHasher";
export const flexibleChecksumsMiddlewareOptions = {
name: "flexibleChecksumsMiddleware",
step: "build",
tags: ["BODY_CHECKSUM"],
override: true,
};
export const flexibleChecksumsMiddleware = (config, middlewareConfig) => (next, context) => async (args) => {
if (!HttpRequest.isInstance(args.request)) {
return next(args);
}
if (hasHeaderWithPrefix("x-amz-checksum-", args.request.headers)) {
return next(args);
}
const { request, input } = args;
const { body: requestBody, headers } = request;
const { base64Encoder, streamHasher } = config;
const { requestChecksumRequired, requestAlgorithmMember } = middlewareConfig;
const requestChecksumCalculation = await config.requestChecksumCalculation();
const requestAlgorithmMemberName = requestAlgorithmMember?.name;
const requestAlgorithmMemberHttpHeader = requestAlgorithmMember?.httpHeader;
if (requestAlgorithmMemberName && !input[requestAlgorithmMemberName]) {
if (requestChecksumCalculation === RequestChecksumCalculation.WHEN_SUPPORTED || requestChecksumRequired) {
input[requestAlgorithmMemberName] = DEFAULT_CHECKSUM_ALGORITHM;
if (requestAlgorithmMemberHttpHeader) {
headers[requestAlgorithmMemberHttpHeader] = DEFAULT_CHECKSUM_ALGORITHM;
}
}
}
const checksumAlgorithm = getChecksumAlgorithmForRequest(input, {
requestChecksumRequired,
requestAlgorithmMember: requestAlgorithmMember?.name,
requestChecksumCalculation,
});
let updatedBody = requestBody;
let updatedHeaders = headers;
if (checksumAlgorithm) {
switch (checksumAlgorithm) {
case ChecksumAlgorithm.CRC32:
setFeature(context, "FLEXIBLE_CHECKSUMS_REQ_CRC32", "U");
break;
case ChecksumAlgorithm.CRC32C:
setFeature(context, "FLEXIBLE_CHECKSUMS_REQ_CRC32C", "V");
break;
case ChecksumAlgorithm.CRC64NVME:
setFeature(context, "FLEXIBLE_CHECKSUMS_REQ_CRC64", "W");
break;
case ChecksumAlgorithm.SHA1:
setFeature(context, "FLEXIBLE_CHECKSUMS_REQ_SHA1", "X");
break;
case ChecksumAlgorithm.SHA256:
setFeature(context, "FLEXIBLE_CHECKSUMS_REQ_SHA256", "Y");
break;
}
const checksumLocationName = getChecksumLocationName(checksumAlgorithm);
const checksumAlgorithmFn = selectChecksumAlgorithmFunction(checksumAlgorithm, config);
if (isStreaming(requestBody)) {
const { getAwsChunkedEncodingStream, bodyLengthChecker } = config;
updatedBody = getAwsChunkedEncodingStream(typeof config.requestStreamBufferSize === "number" && config.requestStreamBufferSize >= 8 * 1024
? createBufferedReadable(requestBody, config.requestStreamBufferSize, context.logger)
: requestBody, {
base64Encoder,
bodyLengthChecker,
checksumLocationName,
checksumAlgorithmFn,
streamHasher,
});
updatedHeaders = {
...headers,
"content-encoding": headers["content-encoding"]
? `${headers["content-encoding"]},aws-chunked`
: "aws-chunked",
"transfer-encoding": "chunked",
"x-amz-decoded-content-length": headers["content-length"],
"x-amz-content-sha256": "STREAMING-UNSIGNED-PAYLOAD-TRAILER",
"x-amz-trailer": checksumLocationName,
};
delete updatedHeaders["content-length"];
}
else if (!hasHeader(checksumLocationName, headers)) {
const rawChecksum = await stringHasher(checksumAlgorithmFn, requestBody);
updatedHeaders = {
...headers,
[checksumLocationName]: base64Encoder(rawChecksum),
};
}
}
const result = await next({
...args,
request: {
...request,
headers: updatedHeaders,
body: updatedBody,
},
});
return result;
};
@@ -0,0 +1,40 @@
import { HttpRequest } from "@smithy/protocol-http";
import { getChecksumAlgorithmListForResponse } from "./getChecksumAlgorithmListForResponse";
import { getChecksumLocationName } from "./getChecksumLocationName";
import { isChecksumWithPartNumber } from "./isChecksumWithPartNumber";
import { validateChecksumFromResponse } from "./validateChecksumFromResponse";
export const flexibleChecksumsResponseMiddlewareOptions = {
name: "flexibleChecksumsResponseMiddleware",
toMiddleware: "deserializerMiddleware",
relation: "after",
tags: ["BODY_CHECKSUM"],
override: true,
};
export const flexibleChecksumsResponseMiddleware = (config, middlewareConfig) => (next, context) => async (args) => {
if (!HttpRequest.isInstance(args.request)) {
return next(args);
}
const input = args.input;
const result = await next(args);
const response = result.response;
const { requestValidationModeMember, responseAlgorithms } = middlewareConfig;
if (requestValidationModeMember && input[requestValidationModeMember] === "ENABLED") {
const { clientName, commandName } = context;
const isS3WholeObjectMultipartGetResponseChecksum = clientName === "S3Client" &&
commandName === "GetObjectCommand" &&
getChecksumAlgorithmListForResponse(responseAlgorithms).every((algorithm) => {
const responseHeader = getChecksumLocationName(algorithm);
const checksumFromResponse = response.headers[responseHeader];
return !checksumFromResponse || isChecksumWithPartNumber(checksumFromResponse);
});
if (isS3WholeObjectMultipartGetResponseChecksum) {
return result;
}
await validateChecksumFromResponse(response, {
config,
responseAlgorithms,
logger: context.logger,
});
}
return result;
};
@@ -0,0 +1,2 @@
import { stringHasher } from "./stringHasher";
export const getChecksum = async (body, { checksumAlgorithmFn, base64Encoder }) => base64Encoder(await stringHasher(checksumAlgorithmFn, body));
@@ -0,0 +1,18 @@
import { DEFAULT_CHECKSUM_ALGORITHM, RequestChecksumCalculation } from "./constants";
import { CLIENT_SUPPORTED_ALGORITHMS } from "./types";
export const getChecksumAlgorithmForRequest = (input, { requestChecksumRequired, requestAlgorithmMember, requestChecksumCalculation }) => {
if (!requestAlgorithmMember) {
return requestChecksumCalculation === RequestChecksumCalculation.WHEN_SUPPORTED || requestChecksumRequired
? DEFAULT_CHECKSUM_ALGORITHM
: undefined;
}
if (!input[requestAlgorithmMember]) {
return undefined;
}
const checksumAlgorithm = input[requestAlgorithmMember];
if (!CLIENT_SUPPORTED_ALGORITHMS.includes(checksumAlgorithm)) {
throw new Error(`The checksum algorithm "${checksumAlgorithm}" is not supported by the client.` +
` Select one of ${CLIENT_SUPPORTED_ALGORITHMS}.`);
}
return checksumAlgorithm;
};
@@ -0,0 +1,11 @@
import { CLIENT_SUPPORTED_ALGORITHMS, PRIORITY_ORDER_ALGORITHMS } from "./types";
export const getChecksumAlgorithmListForResponse = (responseAlgorithms = []) => {
const validChecksumAlgorithms = [];
for (const algorithm of PRIORITY_ORDER_ALGORITHMS) {
if (!responseAlgorithms.includes(algorithm) || !CLIENT_SUPPORTED_ALGORITHMS.includes(algorithm)) {
continue;
}
validChecksumAlgorithms.push(algorithm);
}
return validChecksumAlgorithms;
};
@@ -0,0 +1,2 @@
import { ChecksumAlgorithm } from "./constants";
export const getChecksumLocationName = (algorithm) => algorithm === ChecksumAlgorithm.MD5 ? "content-md5" : `x-amz-checksum-${algorithm.toLowerCase()}`;
@@ -0,0 +1,2 @@
import { AwsCrc32 } from "@aws-crypto/crc32";
export const getCrc32ChecksumAlgorithmFunction = () => AwsCrc32;
@@ -0,0 +1,21 @@
import { AwsCrc32 } from "@aws-crypto/crc32";
import { numToUint8 } from "@aws-crypto/util";
import * as zlib from "zlib";
class NodeCrc32 {
checksum = 0;
update(data) {
this.checksum = zlib.crc32(data, this.checksum);
}
async digest() {
return numToUint8(this.checksum);
}
reset() {
this.checksum = 0;
}
}
export const getCrc32ChecksumAlgorithmFunction = () => {
if (typeof zlib.crc32 === "undefined") {
return AwsCrc32;
}
return NodeCrc32;
};
@@ -0,0 +1,10 @@
import { flexibleChecksumsInputMiddleware, flexibleChecksumsInputMiddlewareOptions, } from "./flexibleChecksumsInputMiddleware";
import { flexibleChecksumsMiddleware, flexibleChecksumsMiddlewareOptions, } from "./flexibleChecksumsMiddleware";
import { flexibleChecksumsResponseMiddleware, flexibleChecksumsResponseMiddlewareOptions, } from "./flexibleChecksumsResponseMiddleware";
export const getFlexibleChecksumsPlugin = (config, middlewareConfig) => ({
applyToStack: (clientStack) => {
clientStack.add(flexibleChecksumsMiddleware(config, middlewareConfig), flexibleChecksumsMiddlewareOptions);
clientStack.addRelativeTo(flexibleChecksumsInputMiddleware(config, middlewareConfig), flexibleChecksumsInputMiddlewareOptions);
clientStack.addRelativeTo(flexibleChecksumsResponseMiddleware(config, middlewareConfig), flexibleChecksumsResponseMiddlewareOptions);
},
});
@@ -0,0 +1,9 @@
export const hasHeader = (header, headers) => {
const soughtHeader = header.toLowerCase();
for (const headerName of Object.keys(headers)) {
if (soughtHeader === headerName.toLowerCase()) {
return true;
}
}
return false;
};
@@ -0,0 +1,9 @@
export const hasHeaderWithPrefix = (headerPrefix, headers) => {
const soughtHeaderPrefix = headerPrefix.toLowerCase();
for (const headerName of Object.keys(headers)) {
if (headerName.toLowerCase().startsWith(soughtHeaderPrefix)) {
return true;
}
}
return false;
};
@@ -0,0 +1,7 @@
export * from "./NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS";
export * from "./NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS";
export * from "./constants";
export * from "./crc64-nvme-crt-container";
export * from "./flexibleChecksumsMiddleware";
export * from "./getFlexibleChecksumsPlugin";
export * from "./resolveFlexibleChecksumsConfig";
@@ -0,0 +1,13 @@
export const isChecksumWithPartNumber = (checksum) => {
const lastHyphenIndex = checksum.lastIndexOf("-");
if (lastHyphenIndex !== -1) {
const numberPart = checksum.slice(lastHyphenIndex + 1);
if (!numberPart.startsWith("0")) {
const number = parseInt(numberPart, 10);
if (!isNaN(number) && number >= 1 && number <= 10000) {
return true;
}
}
}
return false;
};
@@ -0,0 +1,2 @@
import { isArrayBuffer } from "@smithy/is-array-buffer";
export const isStreaming = (body) => body !== undefined && typeof body !== "string" && !ArrayBuffer.isView(body) && !isArrayBuffer(body);
@@ -0,0 +1,10 @@
import { normalizeProvider } from "@smithy/util-middleware";
import { DEFAULT_REQUEST_CHECKSUM_CALCULATION, DEFAULT_RESPONSE_CHECKSUM_VALIDATION, } from "./constants";
export const resolveFlexibleChecksumsConfig = (input) => {
const { requestChecksumCalculation, responseChecksumValidation, requestStreamBufferSize } = input;
return Object.assign(input, {
requestChecksumCalculation: normalizeProvider(requestChecksumCalculation ?? DEFAULT_REQUEST_CHECKSUM_CALCULATION),
responseChecksumValidation: normalizeProvider(responseChecksumValidation ?? DEFAULT_RESPONSE_CHECKSUM_VALIDATION),
requestStreamBufferSize: Number(requestStreamBufferSize ?? 0),
});
};
@@ -0,0 +1,29 @@
import { AwsCrc32c } from "@aws-crypto/crc32c";
import { ChecksumAlgorithm } from "./constants";
import { crc64NvmeCrtContainer } from "./crc64-nvme-crt-container";
import { getCrc32ChecksumAlgorithmFunction } from "./getCrc32ChecksumAlgorithmFunction";
export const selectChecksumAlgorithmFunction = (checksumAlgorithm, config) => {
switch (checksumAlgorithm) {
case ChecksumAlgorithm.MD5:
return config.md5;
case ChecksumAlgorithm.CRC32:
return getCrc32ChecksumAlgorithmFunction();
case ChecksumAlgorithm.CRC32C:
return AwsCrc32c;
case ChecksumAlgorithm.CRC64NVME:
if (typeof crc64NvmeCrtContainer.CrtCrc64Nvme !== "function") {
throw new Error(`Please check whether you have installed the "@aws-sdk/crc64-nvme-crt" package explicitly. \n` +
`You must also register the package by calling [require("@aws-sdk/crc64-nvme-crt");] ` +
`or an ESM equivalent such as [import "@aws-sdk/crc64-nvme-crt";]. \n` +
"For more information please go to " +
"https://github.com/aws/aws-sdk-js-v3#functionality-requiring-aws-common-runtime-crt");
}
return crc64NvmeCrtContainer.CrtCrc64Nvme;
case ChecksumAlgorithm.SHA1:
return config.sha1;
case ChecksumAlgorithm.SHA256:
return config.sha256;
default:
throw new Error(`Unsupported checksum algorithm: ${checksumAlgorithm}`);
}
};
@@ -0,0 +1,6 @@
import { toUint8Array } from "@smithy/util-utf8";
export const stringHasher = (checksumAlgorithmFn, body) => {
const hash = new checksumAlgorithmFn();
hash.update(toUint8Array(body || ""));
return hash.digest();
};
@@ -0,0 +1,14 @@
export var SelectorType;
(function (SelectorType) {
SelectorType["ENV"] = "env";
SelectorType["CONFIG"] = "shared config entry";
})(SelectorType || (SelectorType = {}));
export const stringUnionSelector = (obj, key, union, type) => {
if (!(key in obj))
return undefined;
const value = obj[key].toUpperCase();
if (!Object.values(union).includes(value)) {
throw new TypeError(`Cannot load ${type} '${key}'. Expected one of ${Object.values(union)}, got '${obj[key]}'.`);
}
return value;
};
@@ -0,0 +1,15 @@
import { ChecksumAlgorithm } from "./constants";
export const CLIENT_SUPPORTED_ALGORITHMS = [
ChecksumAlgorithm.CRC32,
ChecksumAlgorithm.CRC32C,
ChecksumAlgorithm.CRC64NVME,
ChecksumAlgorithm.SHA1,
ChecksumAlgorithm.SHA256,
];
export const PRIORITY_ORDER_ALGORITHMS = [
ChecksumAlgorithm.SHA256,
ChecksumAlgorithm.SHA1,
ChecksumAlgorithm.CRC32,
ChecksumAlgorithm.CRC32C,
ChecksumAlgorithm.CRC64NVME,
];
@@ -0,0 +1,45 @@
import { createChecksumStream } from "@smithy/util-stream";
import { ChecksumAlgorithm } from "./constants";
import { getChecksum } from "./getChecksum";
import { getChecksumAlgorithmListForResponse } from "./getChecksumAlgorithmListForResponse";
import { getChecksumLocationName } from "./getChecksumLocationName";
import { isStreaming } from "./isStreaming";
import { selectChecksumAlgorithmFunction } from "./selectChecksumAlgorithmFunction";
export const validateChecksumFromResponse = async (response, { config, responseAlgorithms, logger }) => {
const checksumAlgorithms = getChecksumAlgorithmListForResponse(responseAlgorithms);
const { body: responseBody, headers: responseHeaders } = response;
for (const algorithm of checksumAlgorithms) {
const responseHeader = getChecksumLocationName(algorithm);
const checksumFromResponse = responseHeaders[responseHeader];
if (checksumFromResponse) {
let checksumAlgorithmFn;
try {
checksumAlgorithmFn = selectChecksumAlgorithmFunction(algorithm, config);
}
catch (error) {
if (algorithm === ChecksumAlgorithm.CRC64NVME) {
logger?.warn(`Skipping ${ChecksumAlgorithm.CRC64NVME} checksum validation: ${error.message}`);
continue;
}
throw error;
}
const { base64Encoder } = config;
if (isStreaming(responseBody)) {
response.body = createChecksumStream({
expectedChecksum: checksumFromResponse,
checksumSourceLocation: responseHeader,
checksum: new checksumAlgorithmFn(),
source: responseBody,
base64Encoder,
});
return;
}
const checksum = await getChecksum(responseBody, { checksumAlgorithmFn, base64Encoder });
if (checksum === checksumFromResponse) {
break;
}
throw new Error(`Checksum mismatch: expected "${checksum}" but received "${checksumFromResponse}"` +
` in response header "${responseHeader}".`);
}
}
};
@@ -0,0 +1,14 @@
import { LoadedConfigSelectors } from "@smithy/node-config-provider";
import { RequestChecksumCalculation } from "./constants";
/**
* @internal
*/
export declare const ENV_REQUEST_CHECKSUM_CALCULATION = "AWS_REQUEST_CHECKSUM_CALCULATION";
/**
* @internal
*/
export declare const CONFIG_REQUEST_CHECKSUM_CALCULATION = "request_checksum_calculation";
/**
* @internal
*/
export declare const NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS: LoadedConfigSelectors<RequestChecksumCalculation>;
@@ -0,0 +1,14 @@
import { LoadedConfigSelectors } from "@smithy/node-config-provider";
import { ResponseChecksumValidation } from "./constants";
/**
* @internal
*/
export declare const ENV_RESPONSE_CHECKSUM_VALIDATION = "AWS_RESPONSE_CHECKSUM_VALIDATION";
/**
* @internal
*/
export declare const CONFIG_RESPONSE_CHECKSUM_VALIDATION = "response_checksum_validation";
/**
* @internal
*/
export declare const NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS: LoadedConfigSelectors<ResponseChecksumValidation>;
@@ -0,0 +1,56 @@
import { BodyLengthCalculator, ChecksumConstructor, Encoder, GetAwsChunkedEncodingStream, HashConstructor, Provider, StreamCollector, StreamHasher } from "@smithy/types";
import { RequestChecksumCalculation, ResponseChecksumValidation } from "./constants";
/**
* @internal
*/
export interface PreviouslyResolved {
/**
* The function that will be used to convert binary data to a base64-encoded string.
* @internal
*/
base64Encoder: Encoder;
/**
* A function that can calculate the length of a body.
*/
bodyLengthChecker: BodyLengthCalculator;
/**
* A function that returns Readable Stream which follows aws-chunked encoding stream.
*/
getAwsChunkedEncodingStream: GetAwsChunkedEncodingStream;
/**
* A constructor for a class implementing the {@link Hash} interface that computes MD5 hashes.
* @internal
*/
md5: ChecksumConstructor | HashConstructor;
/**
* Determines when a checksum will be calculated for request payloads
*/
requestChecksumCalculation: Provider<RequestChecksumCalculation>;
/**
* Determines when a checksum will be calculated for response payloads
*/
responseChecksumValidation: Provider<ResponseChecksumValidation>;
/**
* A constructor for a class implementing the {@link Hash} interface that computes SHA1 hashes.
* @internal
*/
sha1: ChecksumConstructor | HashConstructor;
/**
* A constructor for a class implementing the {@link Hash} interface that computes SHA256 hashes.
* @internal
*/
sha256: ChecksumConstructor | HashConstructor;
/**
* A function that, given a hash constructor and a stream, calculates the hash of the streamed value.
* @internal
*/
streamHasher: StreamHasher<any>;
/**
* Collects streams into buffers.
*/
streamCollector: StreamCollector;
/**
* Minimum bytes from a stream to buffer into a chunk before passing to chunked encoding.
*/
requestStreamBufferSize: number;
}
@@ -0,0 +1,83 @@
/**
* Determines when a checksum will be calculated for request payloads.
* @public
*/
export declare const RequestChecksumCalculation: {
/**
* When set, a checksum will be calculated for all request payloads of operations
* modeled with the {@link httpChecksum} trait where `requestChecksumRequired` is `true`
* AND/OR a `requestAlgorithmMember` is modeled.
* {@link https://smithy.io/2.0/aws/aws-core.html#aws-protocols-httpchecksum-trait httpChecksum}
*/
readonly WHEN_SUPPORTED: "WHEN_SUPPORTED";
/**
* When set, a checksum will only be calculated for request payloads of operations
* modeled with the {@link httpChecksum} trait where `requestChecksumRequired` is `true`
* OR where a `requestAlgorithmMember` is modeled and the user sets it.
* {@link https://smithy.io/2.0/aws/aws-core.html#aws-protocols-httpchecksum-trait httpChecksum}
*/
readonly WHEN_REQUIRED: "WHEN_REQUIRED";
};
/**
* @public
*/
export type RequestChecksumCalculation = (typeof RequestChecksumCalculation)[keyof typeof RequestChecksumCalculation];
/**
* @internal
*/
export declare const DEFAULT_REQUEST_CHECKSUM_CALCULATION: "WHEN_SUPPORTED";
/**
* Determines when checksum validation will be performed on response payloads.
* @public
*/
export declare const ResponseChecksumValidation: {
/**
* When set, checksum validation MUST be performed on all response payloads of operations
* modeled with the {@link httpChecksum} trait where `responseAlgorithms` is modeled,
* except when no modeled checksum algorithms are supported by an SDK.
* {@link https://smithy.io/2.0/aws/aws-core.html#aws-protocols-httpchecksum-trait httpChecksum}
*/
readonly WHEN_SUPPORTED: "WHEN_SUPPORTED";
/**
* When set, checksum validation MUST NOT be performed on response payloads of operations UNLESS
* the SDK supports the modeled checksum algorithms AND the user has set the `requestValidationModeMember` to `ENABLED`.
* It is currently impossible to model an operation as requiring a response checksum,
* but this setting leaves the door open for future updates.
*/
readonly WHEN_REQUIRED: "WHEN_REQUIRED";
};
/**
* @public
*/
export type ResponseChecksumValidation = (typeof ResponseChecksumValidation)[keyof typeof ResponseChecksumValidation];
/**
* @internal
*/
export declare const DEFAULT_RESPONSE_CHECKSUM_VALIDATION: "WHEN_SUPPORTED";
/**
* Checksum Algorithms supported by the SDK.
* @public
*/
export declare enum ChecksumAlgorithm {
/**
* @deprecated Use {@link ChecksumAlgorithm.CRC32} instead.
*/
MD5 = "MD5",
CRC32 = "CRC32",
CRC32C = "CRC32C",
CRC64NVME = "CRC64NVME",
SHA1 = "SHA1",
SHA256 = "SHA256"
}
/**
* Location when the checksum is stored in the request body.
* @internal
*/
export declare enum ChecksumLocation {
HEADER = "header",
TRAILER = "trailer"
}
/**
* @internal
*/
export declare const DEFAULT_CHECKSUM_ALGORITHM = ChecksumAlgorithm.CRC32;
@@ -0,0 +1,13 @@
import { ChecksumConstructor } from "@smithy/types";
/**
* @internal
*
* \@aws-sdk/crc64-nvme-crt will install the constructor in this
* container if it is installed.
*
* This avoids a runtime-require being interpreted statically by bundlers.
*
*/
export declare const crc64NvmeCrtContainer: {
CrtCrc64Nvme: null | ChecksumConstructor;
};
@@ -0,0 +1,22 @@
import { RelativeMiddlewareOptions, SerializeMiddleware } from "@smithy/types";
import { PreviouslyResolved } from "./configuration";
/**
* @internal
*/
export interface FlexibleChecksumsInputMiddlewareConfig {
/**
* Defines a top-level operation input member used to opt-in to best-effort validation
* of a checksum returned in the HTTP response of the operation.
*/
requestValidationModeMember?: string;
}
/**
* @internal
*/
export declare const flexibleChecksumsInputMiddlewareOptions: RelativeMiddlewareOptions;
/**
* @internal
*
* The input counterpart to the flexibleChecksumsMiddleware.
*/
export declare const flexibleChecksumsInputMiddleware: (config: PreviouslyResolved, middlewareConfig: FlexibleChecksumsInputMiddlewareConfig) => SerializeMiddleware<any, any>;
@@ -0,0 +1,33 @@
import { BuildHandlerOptions, BuildMiddleware } from "@smithy/types";
import { PreviouslyResolved } from "./configuration";
/**
* @internal
*/
export interface FlexibleChecksumsRequestMiddlewareConfig {
/**
* Indicates an operation requires a checksum in its HTTP request.
*/
requestChecksumRequired: boolean;
/**
* Member that is used to configure request checksum behavior.
*/
requestAlgorithmMember?: {
/**
* Defines a top-level operation input member that is used to configure request checksum behavior.
*/
name: string;
/**
* The {@link httpHeader} value, if present.
* {@link https://smithy.io/2.0/spec/http-bindings.html#httpheader-trait httpHeader}
*/
httpHeader?: string;
};
}
/**
* @internal
*/
export declare const flexibleChecksumsMiddlewareOptions: BuildHandlerOptions;
/**
* @internal
*/
export declare const flexibleChecksumsMiddleware: (config: PreviouslyResolved, middlewareConfig: FlexibleChecksumsRequestMiddlewareConfig) => BuildMiddleware<any, any>;
@@ -0,0 +1,27 @@
import { DeserializeMiddleware, RelativeMiddlewareOptions } from "@smithy/types";
import { PreviouslyResolved } from "./configuration";
/**
* @internal
*/
export interface FlexibleChecksumsResponseMiddlewareConfig {
/**
* Defines a top-level operation input member used to opt-in to best-effort validation
* of a checksum returned in the HTTP response of the operation.
*/
requestValidationModeMember?: string;
/**
* Defines the checksum algorithms clients SHOULD look for when validating checksums
* returned in the HTTP response.
*/
responseAlgorithms?: string[];
}
/**
* @internal
*/
export declare const flexibleChecksumsResponseMiddlewareOptions: RelativeMiddlewareOptions;
/**
* @internal
*
* The validation counterpart to the flexibleChecksumsMiddleware.
*/
export declare const flexibleChecksumsResponseMiddleware: (config: PreviouslyResolved, middlewareConfig: FlexibleChecksumsResponseMiddlewareConfig) => DeserializeMiddleware<any, any>;
@@ -0,0 +1,6 @@
import { ChecksumConstructor, Encoder, HashConstructor } from "@smithy/types";
export interface GetChecksumDigestOptions {
checksumAlgorithmFn: ChecksumConstructor | HashConstructor;
base64Encoder: Encoder;
}
export declare const getChecksum: (body: unknown, { checksumAlgorithmFn, base64Encoder }: GetChecksumDigestOptions) => Promise<string>;
@@ -0,0 +1,21 @@
import { ChecksumAlgorithm, RequestChecksumCalculation } from "./constants";
export interface GetChecksumAlgorithmForRequestOptions {
/**
* Indicates an operation requires a checksum in its HTTP request.
*/
requestChecksumRequired: boolean;
/**
* Defines a top-level operation input member that is used to configure request checksum behavior.
*/
requestAlgorithmMember?: string;
/**
* Determines when a checksum will be calculated for request payloads
*/
requestChecksumCalculation: RequestChecksumCalculation;
}
/**
* Returns the checksum algorithm to use for the request, along with
* the priority array of location to use to populate checksum and names
* to be used as a key at the location.
*/
export declare const getChecksumAlgorithmForRequest: (input: any, { requestChecksumRequired, requestAlgorithmMember, requestChecksumCalculation }: GetChecksumAlgorithmForRequestOptions) => ChecksumAlgorithm | undefined;
@@ -0,0 +1,6 @@
import { ChecksumAlgorithm } from "./constants";
/**
* Returns the priority array of algorithm to use to verify checksum and names
* to be used as a key in the response header.
*/
export declare const getChecksumAlgorithmListForResponse: (responseAlgorithms?: string[]) => ChecksumAlgorithm[];
@@ -0,0 +1,5 @@
import { ChecksumAlgorithm } from "./constants";
/**
* Returns location (header/trailer) name to use to populate checksum in.
*/
export declare const getChecksumLocationName: (algorithm: ChecksumAlgorithm) => string;
@@ -0,0 +1,2 @@
import { AwsCrc32 } from "@aws-crypto/crc32";
export declare const getCrc32ChecksumAlgorithmFunction: () => typeof AwsCrc32;
@@ -0,0 +1,10 @@
import { AwsCrc32 } from "@aws-crypto/crc32";
import { Checksum } from "@smithy/types";
declare class NodeCrc32 implements Checksum {
private checksum;
update(data: Uint8Array): void;
digest(): Promise<Uint8Array<ArrayBufferLike>>;
reset(): void;
}
export declare const getCrc32ChecksumAlgorithmFunction: () => typeof NodeCrc32 | typeof AwsCrc32;
export {};
@@ -0,0 +1,14 @@
import { Pluggable } from "@smithy/types";
import { PreviouslyResolved } from "./configuration";
import { FlexibleChecksumsInputMiddlewareConfig } from "./flexibleChecksumsInputMiddleware";
import { FlexibleChecksumsRequestMiddlewareConfig } from "./flexibleChecksumsMiddleware";
import { FlexibleChecksumsResponseMiddlewareConfig } from "./flexibleChecksumsResponseMiddleware";
/**
* @internal
*/
export interface FlexibleChecksumsMiddlewareConfig extends FlexibleChecksumsRequestMiddlewareConfig, FlexibleChecksumsInputMiddlewareConfig, FlexibleChecksumsResponseMiddlewareConfig {
}
/**
* @internal
*/
export declare const getFlexibleChecksumsPlugin: (config: PreviouslyResolved, middlewareConfig: FlexibleChecksumsMiddlewareConfig) => Pluggable<any, any>;
@@ -0,0 +1,6 @@
import { HeaderBag } from "@smithy/types";
/**
* Returns true if header is present in headers.
* Comparisons are case-insensitive.
*/
export declare const hasHeader: (header: string, headers: HeaderBag) => boolean;
@@ -0,0 +1,6 @@
import { HeaderBag } from "@smithy/types";
/**
* Returns true if header with headerPrefix is present in headers.
* Comparisons are case-insensitive.
*/
export declare const hasHeaderWithPrefix: (headerPrefix: string, headers: HeaderBag) => boolean;
@@ -0,0 +1,7 @@
export * from "./NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS";
export * from "./NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS";
export * from "./constants";
export * from "./crc64-nvme-crt-container";
export * from "./flexibleChecksumsMiddleware";
export * from "./getFlexibleChecksumsPlugin";
export * from "./resolveFlexibleChecksumsConfig";
@@ -0,0 +1 @@
export declare const isChecksumWithPartNumber: (checksum: string) => boolean;
@@ -0,0 +1,4 @@
/**
* Returns true if the given value is a streaming response.
*/
export declare const isStreaming: (body: unknown) => boolean;
@@ -0,0 +1,43 @@
import { Provider } from "@smithy/types";
import { RequestChecksumCalculation, ResponseChecksumValidation } from "./constants";
/**
* @public
*/
export interface FlexibleChecksumsInputConfig {
/**
* Determines when a checksum will be calculated for request payloads.
*/
requestChecksumCalculation?: RequestChecksumCalculation | Provider<RequestChecksumCalculation>;
/**
* Determines when checksum validation will be performed on response payloads.
*/
responseChecksumValidation?: ResponseChecksumValidation | Provider<ResponseChecksumValidation>;
/**
* Default 0 (off).
*
* When set to a value greater than or equal to 8192, sets the minimum number
* of bytes to buffer into a chunk when processing input streams
* with chunked encoding (that is, when request checksums are enabled).
* A minimum of 8kb = 8 * 1024 is required, and 64kb or higher is recommended.
*
* See https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-streaming.html.
*
* This has a slight performance penalty because it must wrap and buffer
* your input stream.
* You do not need to set this value if your stream already flows chunks
* of 8kb or greater.
*/
requestStreamBufferSize?: number | false;
}
/**
* @internal
*/
export interface FlexibleChecksumsResolvedConfig {
requestChecksumCalculation: Provider<RequestChecksumCalculation>;
responseChecksumValidation: Provider<ResponseChecksumValidation>;
requestStreamBufferSize: number;
}
/**
* @internal
*/
export declare const resolveFlexibleChecksumsConfig: <T>(input: T & FlexibleChecksumsInputConfig) => T & FlexibleChecksumsResolvedConfig;
@@ -0,0 +1,7 @@
import { ChecksumConstructor, HashConstructor } from "@smithy/types";
import { PreviouslyResolved } from "./configuration";
import { ChecksumAlgorithm } from "./constants";
/**
* Returns the function that will compute the checksum for the given {@link ChecksumAlgorithm}.
*/
export declare const selectChecksumAlgorithmFunction: (checksumAlgorithm: ChecksumAlgorithm, config: PreviouslyResolved) => ChecksumConstructor | HashConstructor;
@@ -0,0 +1,5 @@
import { ChecksumConstructor, HashConstructor } from "@smithy/types";
/**
* A function that, given a hash constructor and a string, calculates the hash of the string.
*/
export declare const stringHasher: (checksumAlgorithmFn: ChecksumConstructor | HashConstructor, body: any) => Promise<Uint8Array<ArrayBufferLike>>;
@@ -0,0 +1,12 @@
export declare enum SelectorType {
ENV = "env",
CONFIG = "shared config entry"
}
/**
* Returns undefined, if obj[key] is not defined.
* Returns string value, if the string is defined in obj[key] and it's uppercase matches union value.
* Throws error for all other cases.
*
* @internal
*/
export declare const stringUnionSelector: <U extends object, K extends keyof U>(obj: Record<string, string | undefined>, key: string, union: U, type: SelectorType) => U[K] | undefined;
@@ -0,0 +1,7 @@
import { LoadedConfigSelectors } from "@smithy/node-config-provider";
import { RequestChecksumCalculation } from "./constants";
export declare const ENV_REQUEST_CHECKSUM_CALCULATION =
"AWS_REQUEST_CHECKSUM_CALCULATION";
export declare const CONFIG_REQUEST_CHECKSUM_CALCULATION =
"request_checksum_calculation";
export declare const NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS: LoadedConfigSelectors<RequestChecksumCalculation>;
@@ -0,0 +1,7 @@
import { LoadedConfigSelectors } from "@smithy/node-config-provider";
import { ResponseChecksumValidation } from "./constants";
export declare const ENV_RESPONSE_CHECKSUM_VALIDATION =
"AWS_RESPONSE_CHECKSUM_VALIDATION";
export declare const CONFIG_RESPONSE_CHECKSUM_VALIDATION =
"response_checksum_validation";
export declare const NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS: LoadedConfigSelectors<ResponseChecksumValidation>;
@@ -0,0 +1,27 @@
import {
BodyLengthCalculator,
ChecksumConstructor,
Encoder,
GetAwsChunkedEncodingStream,
HashConstructor,
Provider,
StreamCollector,
StreamHasher,
} from "@smithy/types";
import {
RequestChecksumCalculation,
ResponseChecksumValidation,
} from "./constants";
export interface PreviouslyResolved {
base64Encoder: Encoder;
bodyLengthChecker: BodyLengthCalculator;
getAwsChunkedEncodingStream: GetAwsChunkedEncodingStream;
md5: ChecksumConstructor | HashConstructor;
requestChecksumCalculation: Provider<RequestChecksumCalculation>;
responseChecksumValidation: Provider<ResponseChecksumValidation>;
sha1: ChecksumConstructor | HashConstructor;
sha256: ChecksumConstructor | HashConstructor;
streamHasher: StreamHasher<any>;
streamCollector: StreamCollector;
requestStreamBufferSize: number;
}
@@ -0,0 +1,27 @@
export declare const RequestChecksumCalculation: {
readonly WHEN_SUPPORTED: "WHEN_SUPPORTED";
readonly WHEN_REQUIRED: "WHEN_REQUIRED";
};
export type RequestChecksumCalculation =
(typeof RequestChecksumCalculation)[keyof typeof RequestChecksumCalculation];
export declare const DEFAULT_REQUEST_CHECKSUM_CALCULATION: "WHEN_SUPPORTED";
export declare const ResponseChecksumValidation: {
readonly WHEN_SUPPORTED: "WHEN_SUPPORTED";
readonly WHEN_REQUIRED: "WHEN_REQUIRED";
};
export type ResponseChecksumValidation =
(typeof ResponseChecksumValidation)[keyof typeof ResponseChecksumValidation];
export declare const DEFAULT_RESPONSE_CHECKSUM_VALIDATION: "WHEN_SUPPORTED";
export declare enum ChecksumAlgorithm {
MD5 = "MD5",
CRC32 = "CRC32",
CRC32C = "CRC32C",
CRC64NVME = "CRC64NVME",
SHA1 = "SHA1",
SHA256 = "SHA256",
}
export declare enum ChecksumLocation {
HEADER = "header",
TRAILER = "trailer",
}
export declare const DEFAULT_CHECKSUM_ALGORITHM = ChecksumAlgorithm.CRC32;
@@ -0,0 +1,4 @@
import { ChecksumConstructor } from "@smithy/types";
export declare const crc64NvmeCrtContainer: {
CrtCrc64Nvme: null | ChecksumConstructor;
};
@@ -0,0 +1,10 @@
import { RelativeMiddlewareOptions, SerializeMiddleware } from "@smithy/types";
import { PreviouslyResolved } from "./configuration";
export interface FlexibleChecksumsInputMiddlewareConfig {
requestValidationModeMember?: string;
}
export declare const flexibleChecksumsInputMiddlewareOptions: RelativeMiddlewareOptions;
export declare const flexibleChecksumsInputMiddleware: (
config: PreviouslyResolved,
middlewareConfig: FlexibleChecksumsInputMiddlewareConfig
) => SerializeMiddleware<any, any>;
@@ -0,0 +1,14 @@
import { BuildHandlerOptions, BuildMiddleware } from "@smithy/types";
import { PreviouslyResolved } from "./configuration";
export interface FlexibleChecksumsRequestMiddlewareConfig {
requestChecksumRequired: boolean;
requestAlgorithmMember?: {
name: string;
httpHeader?: string;
};
}
export declare const flexibleChecksumsMiddlewareOptions: BuildHandlerOptions;
export declare const flexibleChecksumsMiddleware: (
config: PreviouslyResolved,
middlewareConfig: FlexibleChecksumsRequestMiddlewareConfig
) => BuildMiddleware<any, any>;
@@ -0,0 +1,14 @@
import {
DeserializeMiddleware,
RelativeMiddlewareOptions,
} from "@smithy/types";
import { PreviouslyResolved } from "./configuration";
export interface FlexibleChecksumsResponseMiddlewareConfig {
requestValidationModeMember?: string;
responseAlgorithms?: string[];
}
export declare const flexibleChecksumsResponseMiddlewareOptions: RelativeMiddlewareOptions;
export declare const flexibleChecksumsResponseMiddleware: (
config: PreviouslyResolved,
middlewareConfig: FlexibleChecksumsResponseMiddlewareConfig
) => DeserializeMiddleware<any, any>;
@@ -0,0 +1,9 @@
import { ChecksumConstructor, Encoder, HashConstructor } from "@smithy/types";
export interface GetChecksumDigestOptions {
checksumAlgorithmFn: ChecksumConstructor | HashConstructor;
base64Encoder: Encoder;
}
export declare const getChecksum: (
body: unknown,
{ checksumAlgorithmFn, base64Encoder }: GetChecksumDigestOptions
) => Promise<string>;
@@ -0,0 +1,14 @@
import { ChecksumAlgorithm, RequestChecksumCalculation } from "./constants";
export interface GetChecksumAlgorithmForRequestOptions {
requestChecksumRequired: boolean;
requestAlgorithmMember?: string;
requestChecksumCalculation: RequestChecksumCalculation;
}
export declare const getChecksumAlgorithmForRequest: (
input: any,
{
requestChecksumRequired,
requestAlgorithmMember,
requestChecksumCalculation,
}: GetChecksumAlgorithmForRequestOptions
) => ChecksumAlgorithm | undefined;
@@ -0,0 +1,4 @@
import { ChecksumAlgorithm } from "./constants";
export declare const getChecksumAlgorithmListForResponse: (
responseAlgorithms?: string[]
) => ChecksumAlgorithm[];
@@ -0,0 +1,4 @@
import { ChecksumAlgorithm } from "./constants";
export declare const getChecksumLocationName: (
algorithm: ChecksumAlgorithm
) => string;
@@ -0,0 +1,2 @@
import { AwsCrc32 } from "@aws-crypto/crc32";
export declare const getCrc32ChecksumAlgorithmFunction: () => typeof AwsCrc32;
@@ -0,0 +1,12 @@
import { AwsCrc32 } from "@aws-crypto/crc32";
import { Checksum } from "@smithy/types";
declare class NodeCrc32 implements Checksum {
private checksum;
update(data: Uint8Array): void;
digest(): Promise<Uint8Array<ArrayBufferLike>>;
reset(): void;
}
export declare const getCrc32ChecksumAlgorithmFunction: () =>
| typeof NodeCrc32
| typeof AwsCrc32;
export {};
@@ -0,0 +1,13 @@
import { Pluggable } from "@smithy/types";
import { PreviouslyResolved } from "./configuration";
import { FlexibleChecksumsInputMiddlewareConfig } from "./flexibleChecksumsInputMiddleware";
import { FlexibleChecksumsRequestMiddlewareConfig } from "./flexibleChecksumsMiddleware";
import { FlexibleChecksumsResponseMiddlewareConfig } from "./flexibleChecksumsResponseMiddleware";
export interface FlexibleChecksumsMiddlewareConfig
extends FlexibleChecksumsRequestMiddlewareConfig,
FlexibleChecksumsInputMiddlewareConfig,
FlexibleChecksumsResponseMiddlewareConfig {}
export declare const getFlexibleChecksumsPlugin: (
config: PreviouslyResolved,
middlewareConfig: FlexibleChecksumsMiddlewareConfig
) => Pluggable<any, any>;
@@ -0,0 +1,2 @@
import { HeaderBag } from "@smithy/types";
export declare const hasHeader: (header: string, headers: HeaderBag) => boolean;
@@ -0,0 +1,5 @@
import { HeaderBag } from "@smithy/types";
export declare const hasHeaderWithPrefix: (
headerPrefix: string,
headers: HeaderBag
) => boolean;
@@ -0,0 +1,7 @@
export * from "./NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS";
export * from "./NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS";
export * from "./constants";
export * from "./crc64-nvme-crt-container";
export * from "./flexibleChecksumsMiddleware";
export * from "./getFlexibleChecksumsPlugin";
export * from "./resolveFlexibleChecksumsConfig";
@@ -0,0 +1 @@
export declare const isChecksumWithPartNumber: (checksum: string) => boolean;
@@ -0,0 +1 @@
export declare const isStreaming: (body: unknown) => boolean;
@@ -0,0 +1,22 @@
import { Provider } from "@smithy/types";
import {
RequestChecksumCalculation,
ResponseChecksumValidation,
} from "./constants";
export interface FlexibleChecksumsInputConfig {
requestChecksumCalculation?:
| RequestChecksumCalculation
| Provider<RequestChecksumCalculation>;
responseChecksumValidation?:
| ResponseChecksumValidation
| Provider<ResponseChecksumValidation>;
requestStreamBufferSize?: number | false;
}
export interface FlexibleChecksumsResolvedConfig {
requestChecksumCalculation: Provider<RequestChecksumCalculation>;
responseChecksumValidation: Provider<ResponseChecksumValidation>;
requestStreamBufferSize: number;
}
export declare const resolveFlexibleChecksumsConfig: <T>(
input: T & FlexibleChecksumsInputConfig
) => T & FlexibleChecksumsResolvedConfig;
@@ -0,0 +1,7 @@
import { ChecksumConstructor, HashConstructor } from "@smithy/types";
import { PreviouslyResolved } from "./configuration";
import { ChecksumAlgorithm } from "./constants";
export declare const selectChecksumAlgorithmFunction: (
checksumAlgorithm: ChecksumAlgorithm,
config: PreviouslyResolved
) => ChecksumConstructor | HashConstructor;
@@ -0,0 +1,5 @@
import { ChecksumConstructor, HashConstructor } from "@smithy/types";
export declare const stringHasher: (
checksumAlgorithmFn: ChecksumConstructor | HashConstructor,
body: any
) => Promise<Uint8Array<ArrayBufferLike>>;
@@ -0,0 +1,10 @@
export declare enum SelectorType {
ENV = "env",
CONFIG = "shared config entry",
}
export declare const stringUnionSelector: <U extends object, K extends keyof U>(
obj: Record<string, string | undefined>,
key: string,
union: U,
type: SelectorType
) => U[K] | undefined;
@@ -0,0 +1,3 @@
import { ChecksumAlgorithm } from "./constants";
export declare const CLIENT_SUPPORTED_ALGORITHMS: ChecksumAlgorithm[];
export declare const PRIORITY_ORDER_ALGORITHMS: ChecksumAlgorithm[];
@@ -0,0 +1,12 @@
import { HttpResponse } from "@smithy/protocol-http";
import { Logger } from "@smithy/types";
import { PreviouslyResolved } from "./configuration";
export interface ValidateChecksumFromResponseOptions {
config: PreviouslyResolved;
responseAlgorithms?: string[];
logger?: Logger;
}
export declare const validateChecksumFromResponse: (
response: HttpResponse,
{ config, responseAlgorithms, logger }: ValidateChecksumFromResponseOptions
) => Promise<void>;
@@ -0,0 +1,9 @@
import { ChecksumAlgorithm } from "./constants";
/**
* List of algorithms supported by client.
*/
export declare const CLIENT_SUPPORTED_ALGORITHMS: ChecksumAlgorithm[];
/**
* Priority order for validating checksum algorithm. A faster algorithm has higher priority.
*/
export declare const PRIORITY_ORDER_ALGORITHMS: ChecksumAlgorithm[];
@@ -0,0 +1,13 @@
import { HttpResponse } from "@smithy/protocol-http";
import { Logger } from "@smithy/types";
import { PreviouslyResolved } from "./configuration";
export interface ValidateChecksumFromResponseOptions {
config: PreviouslyResolved;
/**
* Defines the checksum algorithms clients SHOULD look for when validating checksums
* returned in the HTTP response.
*/
responseAlgorithms?: string[];
logger?: Logger;
}
export declare const validateChecksumFromResponse: (response: HttpResponse, { config, responseAlgorithms, logger }: ValidateChecksumFromResponseOptions) => Promise<void>;
@@ -0,0 +1,76 @@
{
"name": "@aws-sdk/middleware-flexible-checksums",
"version": "3.840.0",
"scripts": {
"build": "concurrently 'yarn:build:cjs' 'yarn:build:es' 'yarn:build:types'",
"build:cjs": "node ../../scripts/compilation/inline middleware-flexible-checksums",
"build:es": "tsc -p tsconfig.es.json",
"build:include:deps": "lerna run --scope $npm_package_name --include-dependencies build",
"build:types": "tsc -p tsconfig.types.json",
"build:types:downlevel": "downlevel-dts dist-types dist-types/ts3.4",
"clean": "rimraf ./dist-* && rimraf *.tsbuildinfo",
"extract:docs": "api-extractor run --local",
"test": "yarn g:vitest run",
"test:watch": "yarn g:vitest watch",
"test:integration": "yarn g:vitest run -c vitest.config.integ.ts",
"test:integration:watch": "yarn g:vitest watch -c vitest.config.integ.ts",
"test:e2e": "yarn g:vitest run -c vitest.config.e2e.ts",
"test:e2e:watch": "yarn g:vitest watch -c vitest.config.e2e.ts"
},
"main": "./dist-cjs/index.js",
"module": "./dist-es/index.js",
"browser": {
"./dist-es/getCrc32ChecksumAlgorithmFunction": "./dist-es/getCrc32ChecksumAlgorithmFunction.browser"
},
"react-native": {
"./dist-es/getCrc32ChecksumAlgorithmFunction": "./dist-es/getCrc32ChecksumAlgorithmFunction.browser",
"./dist-cjs/getCrc32ChecksumAlgorithmFunction": "./dist-cjs/getCrc32ChecksumAlgorithmFunction.browser"
},
"types": "./dist-types/index.d.ts",
"author": {
"name": "AWS SDK for JavaScript Team",
"url": "https://aws.amazon.com/javascript/"
},
"license": "Apache-2.0",
"dependencies": {
"@aws-crypto/crc32": "5.2.0",
"@aws-crypto/crc32c": "5.2.0",
"@aws-crypto/util": "5.2.0",
"@aws-sdk/core": "3.840.0",
"@aws-sdk/types": "3.840.0",
"@smithy/is-array-buffer": "^4.0.0",
"@smithy/node-config-provider": "^4.1.3",
"@smithy/protocol-http": "^5.1.2",
"@smithy/types": "^4.3.1",
"@smithy/util-middleware": "^4.0.4",
"@smithy/util-stream": "^4.2.2",
"@smithy/util-utf8": "^4.0.0",
"tslib": "^2.6.2"
},
"devDependencies": {
"@smithy/node-http-handler": "^4.0.6",
"concurrently": "7.0.0",
"downlevel-dts": "0.10.1",
"rimraf": "3.0.2",
"typescript": "~5.8.3"
},
"engines": {
"node": ">=18.0.0"
},
"typesVersions": {
"<4.0": {
"dist-types/*": [
"dist-types/ts3.4/*"
]
}
},
"files": [
"dist-*/**"
],
"homepage": "https://github.com/aws/aws-sdk-js-v3/tree/main/packages/middleware-flexible-checksums",
"repository": {
"type": "git",
"url": "https://github.com/aws/aws-sdk-js-v3.git",
"directory": "packages/middleware-flexible-checksums"
}
}