fix: 修复配额说明重复和undefined问题

- 在editStorageForm中初始化oss_storage_quota_value和oss_quota_unit
- 删除重复的旧配额说明块,保留新的当前配额设置显示

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
2026-01-22 19:39:53 +08:00
commit 4350113979
7649 changed files with 897277 additions and 0 deletions

View File

@@ -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.

View File

@@ -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.

View File

@@ -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;

View File

@@ -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;

View File

@@ -0,0 +1,436 @@
'use strict';
var core = require('@aws-sdk/core');
var protocolHttp = require('@smithy/protocol-http');
var utilStream = require('@smithy/util-stream');
var isArrayBuffer = require('@smithy/is-array-buffer');
var crc32c = require('@aws-crypto/crc32c');
var crc64Nvme = require('@aws-sdk/crc64-nvme');
var getCrc32ChecksumAlgorithmFunction = require('./getCrc32ChecksumAlgorithmFunction');
var utilUtf8 = require('@smithy/util-utf8');
var utilMiddleware = require('@smithy/util-middleware');
const RequestChecksumCalculation = {
WHEN_SUPPORTED: "WHEN_SUPPORTED",
WHEN_REQUIRED: "WHEN_REQUIRED",
};
const DEFAULT_REQUEST_CHECKSUM_CALCULATION = RequestChecksumCalculation.WHEN_SUPPORTED;
const ResponseChecksumValidation = {
WHEN_SUPPORTED: "WHEN_SUPPORTED",
WHEN_REQUIRED: "WHEN_REQUIRED",
};
const DEFAULT_RESPONSE_CHECKSUM_VALIDATION = RequestChecksumCalculation.WHEN_SUPPORTED;
exports.ChecksumAlgorithm = void 0;
(function (ChecksumAlgorithm) {
ChecksumAlgorithm["MD5"] = "MD5";
ChecksumAlgorithm["CRC32"] = "CRC32";
ChecksumAlgorithm["CRC32C"] = "CRC32C";
ChecksumAlgorithm["CRC64NVME"] = "CRC64NVME";
ChecksumAlgorithm["SHA1"] = "SHA1";
ChecksumAlgorithm["SHA256"] = "SHA256";
})(exports.ChecksumAlgorithm || (exports.ChecksumAlgorithm = {}));
exports.ChecksumLocation = void 0;
(function (ChecksumLocation) {
ChecksumLocation["HEADER"] = "header";
ChecksumLocation["TRAILER"] = "trailer";
})(exports.ChecksumLocation || (exports.ChecksumLocation = {}));
const DEFAULT_CHECKSUM_ALGORITHM = exports.ChecksumAlgorithm.CRC32;
var SelectorType;
(function (SelectorType) {
SelectorType["ENV"] = "env";
SelectorType["CONFIG"] = "shared config entry";
})(SelectorType || (SelectorType = {}));
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;
};
const ENV_REQUEST_CHECKSUM_CALCULATION = "AWS_REQUEST_CHECKSUM_CALCULATION";
const CONFIG_REQUEST_CHECKSUM_CALCULATION = "request_checksum_calculation";
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,
};
const ENV_RESPONSE_CHECKSUM_VALIDATION = "AWS_RESPONSE_CHECKSUM_VALIDATION";
const CONFIG_RESPONSE_CHECKSUM_VALIDATION = "response_checksum_validation";
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,
};
const CLIENT_SUPPORTED_ALGORITHMS = [
exports.ChecksumAlgorithm.CRC32,
exports.ChecksumAlgorithm.CRC32C,
exports.ChecksumAlgorithm.CRC64NVME,
exports.ChecksumAlgorithm.SHA1,
exports.ChecksumAlgorithm.SHA256,
];
const PRIORITY_ORDER_ALGORITHMS = [
exports.ChecksumAlgorithm.SHA256,
exports.ChecksumAlgorithm.SHA1,
exports.ChecksumAlgorithm.CRC32,
exports.ChecksumAlgorithm.CRC32C,
exports.ChecksumAlgorithm.CRC64NVME,
];
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;
};
const getChecksumLocationName = (algorithm) => algorithm === exports.ChecksumAlgorithm.MD5 ? "content-md5" : `x-amz-checksum-${algorithm.toLowerCase()}`;
const hasHeader = (header, headers) => {
const soughtHeader = header.toLowerCase();
for (const headerName of Object.keys(headers)) {
if (soughtHeader === headerName.toLowerCase()) {
return true;
}
}
return false;
};
const hasHeaderWithPrefix = (headerPrefix, headers) => {
const soughtHeaderPrefix = headerPrefix.toLowerCase();
for (const headerName of Object.keys(headers)) {
if (headerName.toLowerCase().startsWith(soughtHeaderPrefix)) {
return true;
}
}
return false;
};
const isStreaming = (body) => body !== undefined && typeof body !== "string" && !ArrayBuffer.isView(body) && !isArrayBuffer.isArrayBuffer(body);
const selectChecksumAlgorithmFunction = (checksumAlgorithm, config) => {
switch (checksumAlgorithm) {
case exports.ChecksumAlgorithm.MD5:
return config.md5;
case exports.ChecksumAlgorithm.CRC32:
return getCrc32ChecksumAlgorithmFunction.getCrc32ChecksumAlgorithmFunction();
case exports.ChecksumAlgorithm.CRC32C:
return crc32c.AwsCrc32c;
case exports.ChecksumAlgorithm.CRC64NVME:
if (typeof crc64Nvme.crc64NvmeCrtContainer.CrtCrc64Nvme !== "function") {
return crc64Nvme.Crc64Nvme;
}
return crc64Nvme.crc64NvmeCrtContainer.CrtCrc64Nvme;
case exports.ChecksumAlgorithm.SHA1:
return config.sha1;
case exports.ChecksumAlgorithm.SHA256:
return config.sha256;
default:
throw new Error(`Unsupported checksum algorithm: ${checksumAlgorithm}`);
}
};
const stringHasher = (checksumAlgorithmFn, body) => {
const hash = new checksumAlgorithmFn();
hash.update(utilUtf8.toUint8Array(body || ""));
return hash.digest();
};
const flexibleChecksumsMiddlewareOptions = {
name: "flexibleChecksumsMiddleware",
step: "build",
tags: ["BODY_CHECKSUM"],
override: true,
};
const flexibleChecksumsMiddleware = (config, middlewareConfig) => (next, context) => async (args) => {
if (!protocolHttp.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 exports.ChecksumAlgorithm.CRC32:
core.setFeature(context, "FLEXIBLE_CHECKSUMS_REQ_CRC32", "U");
break;
case exports.ChecksumAlgorithm.CRC32C:
core.setFeature(context, "FLEXIBLE_CHECKSUMS_REQ_CRC32C", "V");
break;
case exports.ChecksumAlgorithm.CRC64NVME:
core.setFeature(context, "FLEXIBLE_CHECKSUMS_REQ_CRC64", "W");
break;
case exports.ChecksumAlgorithm.SHA1:
core.setFeature(context, "FLEXIBLE_CHECKSUMS_REQ_SHA1", "X");
break;
case exports.ChecksumAlgorithm.SHA256:
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
? utilStream.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),
};
}
}
try {
const result = await next({
...args,
request: {
...request,
headers: updatedHeaders,
body: updatedBody,
},
});
return result;
}
catch (e) {
if (e instanceof Error && e.name === "InvalidChunkSizeError") {
try {
if (!e.message.endsWith(".")) {
e.message += ".";
}
e.message +=
" Set [requestStreamBufferSize=number e.g. 65_536] in client constructor to instruct AWS SDK to buffer your input stream.";
}
catch (ignored) {
}
}
throw e;
}
};
const flexibleChecksumsInputMiddlewareOptions = {
name: "flexibleChecksumsInputMiddleware",
toMiddleware: "serializerMiddleware",
relation: "before",
tags: ["BODY_CHECKSUM"],
override: true,
};
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:
core.setFeature(context, "FLEXIBLE_CHECKSUMS_REQ_WHEN_REQUIRED", "a");
break;
case RequestChecksumCalculation.WHEN_SUPPORTED:
core.setFeature(context, "FLEXIBLE_CHECKSUMS_REQ_WHEN_SUPPORTED", "Z");
break;
}
switch (responseChecksumValidation) {
case ResponseChecksumValidation.WHEN_REQUIRED:
core.setFeature(context, "FLEXIBLE_CHECKSUMS_RES_WHEN_REQUIRED", "c");
break;
case ResponseChecksumValidation.WHEN_SUPPORTED:
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);
};
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;
};
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;
};
const getChecksum = async (body, { checksumAlgorithmFn, base64Encoder }) => base64Encoder(await stringHasher(checksumAlgorithmFn, body));
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 === exports.ChecksumAlgorithm.CRC64NVME) {
logger?.warn(`Skipping ${exports.ChecksumAlgorithm.CRC64NVME} checksum validation: ${error.message}`);
continue;
}
throw error;
}
const { base64Encoder } = config;
if (isStreaming(responseBody)) {
response.body = utilStream.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}".`);
}
}
};
const flexibleChecksumsResponseMiddlewareOptions = {
name: "flexibleChecksumsResponseMiddleware",
toMiddleware: "deserializerMiddleware",
relation: "after",
tags: ["BODY_CHECKSUM"],
override: true,
};
const flexibleChecksumsResponseMiddleware = (config, middlewareConfig) => (next, context) => async (args) => {
if (!protocolHttp.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;
};
const getFlexibleChecksumsPlugin = (config, middlewareConfig) => ({
applyToStack: (clientStack) => {
clientStack.add(flexibleChecksumsMiddleware(config, middlewareConfig), flexibleChecksumsMiddlewareOptions);
clientStack.addRelativeTo(flexibleChecksumsInputMiddleware(config, middlewareConfig), flexibleChecksumsInputMiddlewareOptions);
clientStack.addRelativeTo(flexibleChecksumsResponseMiddleware(config, middlewareConfig), flexibleChecksumsResponseMiddlewareOptions);
},
});
const resolveFlexibleChecksumsConfig = (input) => {
const { requestChecksumCalculation, responseChecksumValidation, requestStreamBufferSize } = input;
return Object.assign(input, {
requestChecksumCalculation: utilMiddleware.normalizeProvider(requestChecksumCalculation ?? DEFAULT_REQUEST_CHECKSUM_CALCULATION),
responseChecksumValidation: utilMiddleware.normalizeProvider(responseChecksumValidation ?? DEFAULT_RESPONSE_CHECKSUM_VALIDATION),
requestStreamBufferSize: Number(requestStreamBufferSize ?? 0),
});
};
exports.CONFIG_REQUEST_CHECKSUM_CALCULATION = CONFIG_REQUEST_CHECKSUM_CALCULATION;
exports.CONFIG_RESPONSE_CHECKSUM_VALIDATION = CONFIG_RESPONSE_CHECKSUM_VALIDATION;
exports.DEFAULT_CHECKSUM_ALGORITHM = DEFAULT_CHECKSUM_ALGORITHM;
exports.DEFAULT_REQUEST_CHECKSUM_CALCULATION = DEFAULT_REQUEST_CHECKSUM_CALCULATION;
exports.DEFAULT_RESPONSE_CHECKSUM_VALIDATION = DEFAULT_RESPONSE_CHECKSUM_VALIDATION;
exports.ENV_REQUEST_CHECKSUM_CALCULATION = ENV_REQUEST_CHECKSUM_CALCULATION;
exports.ENV_RESPONSE_CHECKSUM_VALIDATION = ENV_RESPONSE_CHECKSUM_VALIDATION;
exports.NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS = NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS;
exports.NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS = NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS;
exports.RequestChecksumCalculation = RequestChecksumCalculation;
exports.ResponseChecksumValidation = ResponseChecksumValidation;
exports.flexibleChecksumsMiddleware = flexibleChecksumsMiddleware;
exports.flexibleChecksumsMiddlewareOptions = flexibleChecksumsMiddlewareOptions;
exports.getFlexibleChecksumsPlugin = getFlexibleChecksumsPlugin;
exports.resolveFlexibleChecksumsConfig = resolveFlexibleChecksumsConfig;

View File

@@ -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,
};

View File

@@ -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,
};

View File

@@ -0,0 +1 @@
export {};

View File

@@ -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;

View File

@@ -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);
};

View File

@@ -0,0 +1,123 @@
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),
};
}
}
try {
const result = await next({
...args,
request: {
...request,
headers: updatedHeaders,
body: updatedBody,
},
});
return result;
}
catch (e) {
if (e instanceof Error && e.name === "InvalidChunkSizeError") {
try {
if (!e.message.endsWith(".")) {
e.message += ".";
}
e.message +=
" Set [requestStreamBufferSize=number e.g. 65_536] in client constructor to instruct AWS SDK to buffer your input stream.";
}
catch (ignored) {
}
}
throw e;
}
};

View File

@@ -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;
};

View File

@@ -0,0 +1,2 @@
import { stringHasher } from "./stringHasher";
export const getChecksum = async (body, { checksumAlgorithmFn, base64Encoder }) => base64Encoder(await stringHasher(checksumAlgorithmFn, body));

View File

@@ -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;
};

View File

@@ -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;
};

View File

@@ -0,0 +1,2 @@
import { ChecksumAlgorithm } from "./constants";
export const getChecksumLocationName = (algorithm) => algorithm === ChecksumAlgorithm.MD5 ? "content-md5" : `x-amz-checksum-${algorithm.toLowerCase()}`;

View File

@@ -0,0 +1,2 @@
import { AwsCrc32 } from "@aws-crypto/crc32";
export const getCrc32ChecksumAlgorithmFunction = () => AwsCrc32;

View File

@@ -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;
};

View File

@@ -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);
},
});

View File

@@ -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;
};

View File

@@ -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;
};

View File

@@ -0,0 +1,6 @@
export * from "./NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS";
export * from "./NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS";
export * from "./constants";
export * from "./flexibleChecksumsMiddleware";
export * from "./getFlexibleChecksumsPlugin";
export * from "./resolveFlexibleChecksumsConfig";

View File

@@ -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;
};

View File

@@ -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);

View File

@@ -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),
});
};

View File

@@ -0,0 +1,25 @@
import { AwsCrc32c } from "@aws-crypto/crc32c";
import { Crc64Nvme, crc64NvmeCrtContainer } from "@aws-sdk/crc64-nvme";
import { ChecksumAlgorithm } from "./constants";
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") {
return Crc64Nvme;
}
return crc64NvmeCrtContainer.CrtCrc64Nvme;
case ChecksumAlgorithm.SHA1:
return config.sha1;
case ChecksumAlgorithm.SHA256:
return config.sha256;
default:
throw new Error(`Unsupported checksum algorithm: ${checksumAlgorithm}`);
}
};

View File

@@ -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();
};

View File

@@ -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;
};

View File

@@ -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,
];

View File

@@ -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}".`);
}
}
};

View File

@@ -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>;

View File

@@ -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>;

View File

@@ -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;
}

View File

@@ -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;

View File

@@ -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>;

View File

@@ -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>;

View File

@@ -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>;

View File

@@ -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>;

View File

@@ -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;

View File

@@ -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[];

View File

@@ -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;

View File

@@ -0,0 +1,2 @@
import { AwsCrc32 } from "@aws-crypto/crc32";
export declare const getCrc32ChecksumAlgorithmFunction: () => typeof AwsCrc32;

View File

@@ -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>;
reset(): void;
}
export declare const getCrc32ChecksumAlgorithmFunction: () => typeof NodeCrc32 | typeof AwsCrc32;
export {};

View File

@@ -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>;

View File

@@ -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;

View File

@@ -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;

View File

@@ -0,0 +1,6 @@
export * from "./NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS";
export * from "./NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS";
export * from "./constants";
export * from "./flexibleChecksumsMiddleware";
export * from "./getFlexibleChecksumsPlugin";
export * from "./resolveFlexibleChecksumsConfig";

View File

@@ -0,0 +1 @@
export declare const isChecksumWithPartNumber: (checksum: string) => boolean;

View File

@@ -0,0 +1,4 @@
/**
* Returns true if the given value is a streaming response.
*/
export declare const isStreaming: (body: unknown) => boolean;

View File

@@ -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;

View File

@@ -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;

View File

@@ -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>;

View File

@@ -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;

View File

@@ -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>;

View File

@@ -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>;

View File

@@ -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;
}

View File

@@ -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;

View File

@@ -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>;

View File

@@ -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>;

View File

@@ -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>;

View File

@@ -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>;

View File

@@ -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;

View File

@@ -0,0 +1,4 @@
import { ChecksumAlgorithm } from "./constants";
export declare const getChecksumAlgorithmListForResponse: (
responseAlgorithms?: string[]
) => ChecksumAlgorithm[];

View File

@@ -0,0 +1,4 @@
import { ChecksumAlgorithm } from "./constants";
export declare const getChecksumLocationName: (
algorithm: ChecksumAlgorithm
) => string;

View File

@@ -0,0 +1,2 @@
import { AwsCrc32 } from "@aws-crypto/crc32";
export declare const getCrc32ChecksumAlgorithmFunction: () => typeof AwsCrc32;

View File

@@ -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>;
reset(): void;
}
export declare const getCrc32ChecksumAlgorithmFunction: () =>
| typeof NodeCrc32
| typeof AwsCrc32;
export {};

View File

@@ -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>;

View File

@@ -0,0 +1,2 @@
import { HeaderBag } from "@smithy/types";
export declare const hasHeader: (header: string, headers: HeaderBag) => boolean;

View File

@@ -0,0 +1,5 @@
import { HeaderBag } from "@smithy/types";
export declare const hasHeaderWithPrefix: (
headerPrefix: string,
headers: HeaderBag
) => boolean;

View File

@@ -0,0 +1,6 @@
export * from "./NODE_REQUEST_CHECKSUM_CALCULATION_CONFIG_OPTIONS";
export * from "./NODE_RESPONSE_CHECKSUM_VALIDATION_CONFIG_OPTIONS";
export * from "./constants";
export * from "./flexibleChecksumsMiddleware";
export * from "./getFlexibleChecksumsPlugin";
export * from "./resolveFlexibleChecksumsConfig";

View File

@@ -0,0 +1 @@
export declare const isChecksumWithPartNumber: (checksum: string) => boolean;

View File

@@ -0,0 +1 @@
export declare const isStreaming: (body: unknown) => boolean;

View File

@@ -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;

View File

@@ -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;

View File

@@ -0,0 +1,5 @@
import { ChecksumConstructor, HashConstructor } from "@smithy/types";
export declare const stringHasher: (
checksumAlgorithmFn: ChecksumConstructor | HashConstructor,
body: any
) => Promise<Uint8Array>;

View File

@@ -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;

View File

@@ -0,0 +1,3 @@
import { ChecksumAlgorithm } from "./constants";
export declare const CLIENT_SUPPORTED_ALGORITHMS: ChecksumAlgorithm[];
export declare const PRIORITY_ORDER_ALGORITHMS: ChecksumAlgorithm[];

View File

@@ -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>;

View File

@@ -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[];

View File

@@ -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>;

View File

@@ -0,0 +1,78 @@
{
"name": "@aws-sdk/middleware-flexible-checksums",
"version": "3.971.0",
"scripts": {
"build": "concurrently 'yarn:build:types' 'yarn:build:es' && yarn build:cjs",
"build:cjs": "node ../../scripts/compilation/inline middleware-flexible-checksums",
"build:es": "tsc -p tsconfig.es.json",
"build:include:deps": "yarn g:turbo run build -F=\"$npm_package_name\"",
"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.mts",
"test:integration:watch": "yarn g:vitest watch -c vitest.config.integ.mts",
"test:e2e": "yarn g:vitest run -c vitest.config.e2e.mts",
"test:e2e:watch": "yarn g:vitest watch -c vitest.config.e2e.mts"
},
"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",
"sideEffects": false,
"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.970.0",
"@aws-sdk/crc64-nvme": "3.969.0",
"@aws-sdk/types": "3.969.0",
"@smithy/is-array-buffer": "^4.2.0",
"@smithy/node-config-provider": "^4.3.8",
"@smithy/protocol-http": "^5.3.8",
"@smithy/types": "^4.12.0",
"@smithy/util-middleware": "^4.2.8",
"@smithy/util-stream": "^4.5.10",
"@smithy/util-utf8": "^4.2.0",
"tslib": "^2.6.2"
},
"devDependencies": {
"@smithy/node-http-handler": "^4.4.8",
"concurrently": "7.0.0",
"downlevel-dts": "0.10.1",
"rimraf": "5.0.10",
"typescript": "~5.8.3"
},
"engines": {
"node": ">=20.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"
}
}