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

201
backend/node_modules/@aws-sdk/middleware-sdk-s3/LICENSE generated vendored Normal file
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 2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
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,4 @@
# @aws-sdk/middleware-sdk-s3
[![NPM version](https://img.shields.io/npm/v/@aws-sdk/middleware-sdk-s3/latest.svg)](https://www.npmjs.com/package/@aws-sdk/middleware-sdk-s3)
[![NPM downloads](https://img.shields.io/npm/dm/@aws-sdk/middleware-sdk-s3.svg)](https://www.npmjs.com/package/@aws-sdk/middleware-sdk-s3)

View File

@@ -0,0 +1,571 @@
'use strict';
var protocolHttp = require('@smithy/protocol-http');
var smithyClient = require('@smithy/smithy-client');
var utilStream = require('@smithy/util-stream');
var utilArnParser = require('@aws-sdk/util-arn-parser');
var signatureV4 = require('@smithy/signature-v4');
var utilConfigProvider = require('@smithy/util-config-provider');
var core = require('@aws-sdk/core');
var core$1 = require('@smithy/core');
require('@smithy/types');
var utilMiddleware = require('@smithy/util-middleware');
const CONTENT_LENGTH_HEADER = "content-length";
const DECODED_CONTENT_LENGTH_HEADER = "x-amz-decoded-content-length";
function checkContentLengthHeader() {
return (next, context) => async (args) => {
const { request } = args;
if (protocolHttp.HttpRequest.isInstance(request)) {
if (!(CONTENT_LENGTH_HEADER in request.headers) && !(DECODED_CONTENT_LENGTH_HEADER in request.headers)) {
const message = `Are you using a Stream of unknown length as the Body of a PutObject request? Consider using Upload instead from @aws-sdk/lib-storage.`;
if (typeof context?.logger?.warn === "function" && !(context.logger instanceof smithyClient.NoOpLogger)) {
context.logger.warn(message);
}
else {
console.warn(message);
}
}
}
return next({ ...args });
};
}
const checkContentLengthHeaderMiddlewareOptions = {
step: "finalizeRequest",
tags: ["CHECK_CONTENT_LENGTH_HEADER"],
name: "getCheckContentLengthHeaderPlugin",
override: true,
};
const getCheckContentLengthHeaderPlugin = (unused) => ({
applyToStack: (clientStack) => {
clientStack.add(checkContentLengthHeader(), checkContentLengthHeaderMiddlewareOptions);
},
});
const regionRedirectEndpointMiddleware = (config) => {
return (next, context) => async (args) => {
const originalRegion = await config.region();
const regionProviderRef = config.region;
let unlock = () => { };
if (context.__s3RegionRedirect) {
Object.defineProperty(config, "region", {
writable: false,
value: async () => {
return context.__s3RegionRedirect;
},
});
unlock = () => Object.defineProperty(config, "region", {
writable: true,
value: regionProviderRef,
});
}
try {
const result = await next(args);
if (context.__s3RegionRedirect) {
unlock();
const region = await config.region();
if (originalRegion !== region) {
throw new Error("Region was not restored following S3 region redirect.");
}
}
return result;
}
catch (e) {
unlock();
throw e;
}
};
};
const regionRedirectEndpointMiddlewareOptions = {
tags: ["REGION_REDIRECT", "S3"],
name: "regionRedirectEndpointMiddleware",
override: true,
relation: "before",
toMiddleware: "endpointV2Middleware",
};
function regionRedirectMiddleware(clientConfig) {
return (next, context) => async (args) => {
try {
return await next(args);
}
catch (err) {
if (clientConfig.followRegionRedirects) {
const statusCode = err?.$metadata?.httpStatusCode;
const isHeadBucket = context.commandName === "HeadBucketCommand";
const bucketRegionHeader = err?.$response?.headers?.["x-amz-bucket-region"];
if (bucketRegionHeader) {
if (statusCode === 301 ||
(statusCode === 400 && (err?.name === "IllegalLocationConstraintException" || isHeadBucket))) {
try {
const actualRegion = bucketRegionHeader;
context.logger?.debug(`Redirecting from ${await clientConfig.region()} to ${actualRegion}`);
context.__s3RegionRedirect = actualRegion;
}
catch (e) {
throw new Error("Region redirect failed: " + e);
}
return next(args);
}
}
}
throw err;
}
};
}
const regionRedirectMiddlewareOptions = {
step: "initialize",
tags: ["REGION_REDIRECT", "S3"],
name: "regionRedirectMiddleware",
override: true,
};
const getRegionRedirectMiddlewarePlugin = (clientConfig) => ({
applyToStack: (clientStack) => {
clientStack.add(regionRedirectMiddleware(clientConfig), regionRedirectMiddlewareOptions);
clientStack.addRelativeTo(regionRedirectEndpointMiddleware(clientConfig), regionRedirectEndpointMiddlewareOptions);
},
});
const s3ExpiresMiddleware = (config) => {
return (next, context) => async (args) => {
const result = await next(args);
const { response } = result;
if (protocolHttp.HttpResponse.isInstance(response)) {
if (response.headers.expires) {
response.headers.expiresstring = response.headers.expires;
try {
smithyClient.parseRfc7231DateTime(response.headers.expires);
}
catch (e) {
context.logger?.warn(`AWS SDK Warning for ${context.clientName}::${context.commandName} response parsing (${response.headers.expires}): ${e}`);
delete response.headers.expires;
}
}
}
return result;
};
};
const s3ExpiresMiddlewareOptions = {
tags: ["S3"],
name: "s3ExpiresMiddleware",
override: true,
relation: "after",
toMiddleware: "deserializerMiddleware",
};
const getS3ExpiresMiddlewarePlugin = (clientConfig) => ({
applyToStack: (clientStack) => {
clientStack.addRelativeTo(s3ExpiresMiddleware(), s3ExpiresMiddlewareOptions);
},
});
class S3ExpressIdentityCache {
data;
lastPurgeTime = Date.now();
static EXPIRED_CREDENTIAL_PURGE_INTERVAL_MS = 30_000;
constructor(data = {}) {
this.data = data;
}
get(key) {
const entry = this.data[key];
if (!entry) {
return;
}
return entry;
}
set(key, entry) {
this.data[key] = entry;
return entry;
}
delete(key) {
delete this.data[key];
}
async purgeExpired() {
const now = Date.now();
if (this.lastPurgeTime + S3ExpressIdentityCache.EXPIRED_CREDENTIAL_PURGE_INTERVAL_MS > now) {
return;
}
for (const key in this.data) {
const entry = this.data[key];
if (!entry.isRefreshing) {
const credential = await entry.identity;
if (credential.expiration) {
if (credential.expiration.getTime() < now) {
delete this.data[key];
}
}
}
}
}
}
class S3ExpressIdentityCacheEntry {
_identity;
isRefreshing;
accessed;
constructor(_identity, isRefreshing = false, accessed = Date.now()) {
this._identity = _identity;
this.isRefreshing = isRefreshing;
this.accessed = accessed;
}
get identity() {
this.accessed = Date.now();
return this._identity;
}
}
class S3ExpressIdentityProviderImpl {
createSessionFn;
cache;
static REFRESH_WINDOW_MS = 60_000;
constructor(createSessionFn, cache = new S3ExpressIdentityCache()) {
this.createSessionFn = createSessionFn;
this.cache = cache;
}
async getS3ExpressIdentity(awsIdentity, identityProperties) {
const key = identityProperties.Bucket;
const { cache } = this;
const entry = cache.get(key);
if (entry) {
return entry.identity.then((identity) => {
const isExpired = (identity.expiration?.getTime() ?? 0) < Date.now();
if (isExpired) {
return cache.set(key, new S3ExpressIdentityCacheEntry(this.getIdentity(key))).identity;
}
const isExpiringSoon = (identity.expiration?.getTime() ?? 0) < Date.now() + S3ExpressIdentityProviderImpl.REFRESH_WINDOW_MS;
if (isExpiringSoon && !entry.isRefreshing) {
entry.isRefreshing = true;
this.getIdentity(key).then((id) => {
cache.set(key, new S3ExpressIdentityCacheEntry(Promise.resolve(id)));
});
}
return identity;
});
}
return cache.set(key, new S3ExpressIdentityCacheEntry(this.getIdentity(key))).identity;
}
async getIdentity(key) {
await this.cache.purgeExpired().catch((error) => {
console.warn("Error while clearing expired entries in S3ExpressIdentityCache: \n" + error);
});
const session = await this.createSessionFn(key);
if (!session.Credentials?.AccessKeyId || !session.Credentials?.SecretAccessKey) {
throw new Error("s3#createSession response credential missing AccessKeyId or SecretAccessKey.");
}
const identity = {
accessKeyId: session.Credentials.AccessKeyId,
secretAccessKey: session.Credentials.SecretAccessKey,
sessionToken: session.Credentials.SessionToken,
expiration: session.Credentials.Expiration ? new Date(session.Credentials.Expiration) : undefined,
};
return identity;
}
}
const S3_EXPRESS_BUCKET_TYPE = "Directory";
const S3_EXPRESS_BACKEND = "S3Express";
const S3_EXPRESS_AUTH_SCHEME = "sigv4-s3express";
const SESSION_TOKEN_QUERY_PARAM = "X-Amz-S3session-Token";
const SESSION_TOKEN_HEADER = SESSION_TOKEN_QUERY_PARAM.toLowerCase();
const NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_ENV_NAME = "AWS_S3_DISABLE_EXPRESS_SESSION_AUTH";
const NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_INI_NAME = "s3_disable_express_session_auth";
const NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_OPTIONS = {
environmentVariableSelector: (env) => utilConfigProvider.booleanSelector(env, NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_ENV_NAME, utilConfigProvider.SelectorType.ENV),
configFileSelector: (profile) => utilConfigProvider.booleanSelector(profile, NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_INI_NAME, utilConfigProvider.SelectorType.CONFIG),
default: false,
};
class SignatureV4S3Express extends signatureV4.SignatureV4 {
async signWithCredentials(requestToSign, credentials, options) {
const credentialsWithoutSessionToken = getCredentialsWithoutSessionToken(credentials);
requestToSign.headers[SESSION_TOKEN_HEADER] = credentials.sessionToken;
const privateAccess = this;
setSingleOverride(privateAccess, credentialsWithoutSessionToken);
return privateAccess.signRequest(requestToSign, options ?? {});
}
async presignWithCredentials(requestToSign, credentials, options) {
const credentialsWithoutSessionToken = getCredentialsWithoutSessionToken(credentials);
delete requestToSign.headers[SESSION_TOKEN_HEADER];
requestToSign.headers[SESSION_TOKEN_QUERY_PARAM] = credentials.sessionToken;
requestToSign.query = requestToSign.query ?? {};
requestToSign.query[SESSION_TOKEN_QUERY_PARAM] = credentials.sessionToken;
const privateAccess = this;
setSingleOverride(privateAccess, credentialsWithoutSessionToken);
return this.presign(requestToSign, options);
}
}
function getCredentialsWithoutSessionToken(credentials) {
const credentialsWithoutSessionToken = {
accessKeyId: credentials.accessKeyId,
secretAccessKey: credentials.secretAccessKey,
expiration: credentials.expiration,
};
return credentialsWithoutSessionToken;
}
function setSingleOverride(privateAccess, credentialsWithoutSessionToken) {
const id = setTimeout(() => {
throw new Error("SignatureV4S3Express credential override was created but not called.");
}, 10);
const currentCredentialProvider = privateAccess.credentialProvider;
const overrideCredentialsProviderOnce = () => {
clearTimeout(id);
privateAccess.credentialProvider = currentCredentialProvider;
return Promise.resolve(credentialsWithoutSessionToken);
};
privateAccess.credentialProvider = overrideCredentialsProviderOnce;
}
const s3ExpressMiddleware = (options) => {
return (next, context) => async (args) => {
if (context.endpointV2) {
const endpoint = context.endpointV2;
const isS3ExpressAuth = endpoint.properties?.authSchemes?.[0]?.name === S3_EXPRESS_AUTH_SCHEME;
const isS3ExpressBucket = endpoint.properties?.backend === S3_EXPRESS_BACKEND ||
endpoint.properties?.bucketType === S3_EXPRESS_BUCKET_TYPE;
if (isS3ExpressBucket) {
core.setFeature(context, "S3_EXPRESS_BUCKET", "J");
context.isS3ExpressBucket = true;
}
if (isS3ExpressAuth) {
const requestBucket = args.input.Bucket;
if (requestBucket) {
const s3ExpressIdentity = await options.s3ExpressIdentityProvider.getS3ExpressIdentity(await options.credentials(), {
Bucket: requestBucket,
});
context.s3ExpressIdentity = s3ExpressIdentity;
if (protocolHttp.HttpRequest.isInstance(args.request) && s3ExpressIdentity.sessionToken) {
args.request.headers[SESSION_TOKEN_HEADER] = s3ExpressIdentity.sessionToken;
}
}
}
}
return next(args);
};
};
const s3ExpressMiddlewareOptions = {
name: "s3ExpressMiddleware",
step: "build",
tags: ["S3", "S3_EXPRESS"],
override: true,
};
const getS3ExpressPlugin = (options) => ({
applyToStack: (clientStack) => {
clientStack.add(s3ExpressMiddleware(options), s3ExpressMiddlewareOptions);
},
});
const signS3Express = async (s3ExpressIdentity, signingOptions, request, sigV4MultiRegionSigner) => {
const signedRequest = await sigV4MultiRegionSigner.signWithCredentials(request, s3ExpressIdentity, {});
if (signedRequest.headers["X-Amz-Security-Token"] || signedRequest.headers["x-amz-security-token"]) {
throw new Error("X-Amz-Security-Token must not be set for s3-express requests.");
}
return signedRequest;
};
const defaultErrorHandler = (signingProperties) => (error) => {
throw error;
};
const defaultSuccessHandler = (httpResponse, signingProperties) => { };
const s3ExpressHttpSigningMiddlewareOptions = core$1.httpSigningMiddlewareOptions;
const s3ExpressHttpSigningMiddleware = (config) => (next, context) => async (args) => {
if (!protocolHttp.HttpRequest.isInstance(args.request)) {
return next(args);
}
const smithyContext = utilMiddleware.getSmithyContext(context);
const scheme = smithyContext.selectedHttpAuthScheme;
if (!scheme) {
throw new Error(`No HttpAuthScheme was selected: unable to sign request`);
}
const { httpAuthOption: { signingProperties = {} }, identity, signer, } = scheme;
let request;
if (context.s3ExpressIdentity) {
request = await signS3Express(context.s3ExpressIdentity, signingProperties, args.request, await config.signer());
}
else {
request = await signer.sign(args.request, identity, signingProperties);
}
const output = await next({
...args,
request,
}).catch((signer.errorHandler || defaultErrorHandler)(signingProperties));
(signer.successHandler || defaultSuccessHandler)(output.response, signingProperties);
return output;
};
const getS3ExpressHttpSigningPlugin = (config) => ({
applyToStack: (clientStack) => {
clientStack.addRelativeTo(s3ExpressHttpSigningMiddleware(config), core$1.httpSigningMiddlewareOptions);
},
});
const resolveS3Config = (input, { session, }) => {
const [s3ClientProvider, CreateSessionCommandCtor] = session;
const { forcePathStyle, useAccelerateEndpoint, disableMultiregionAccessPoints, followRegionRedirects, s3ExpressIdentityProvider, bucketEndpoint, expectContinueHeader, } = input;
return Object.assign(input, {
forcePathStyle: forcePathStyle ?? false,
useAccelerateEndpoint: useAccelerateEndpoint ?? false,
disableMultiregionAccessPoints: disableMultiregionAccessPoints ?? false,
followRegionRedirects: followRegionRedirects ?? false,
s3ExpressIdentityProvider: s3ExpressIdentityProvider ??
new S3ExpressIdentityProviderImpl(async (key) => s3ClientProvider().send(new CreateSessionCommandCtor({
Bucket: key,
}))),
bucketEndpoint: bucketEndpoint ?? false,
expectContinueHeader: expectContinueHeader ?? 2_097_152,
});
};
const THROW_IF_EMPTY_BODY = {
CopyObjectCommand: true,
UploadPartCopyCommand: true,
CompleteMultipartUploadCommand: true,
};
const MAX_BYTES_TO_INSPECT = 3000;
const throw200ExceptionsMiddleware = (config) => (next, context) => async (args) => {
const result = await next(args);
const { response } = result;
if (!protocolHttp.HttpResponse.isInstance(response)) {
return result;
}
const { statusCode, body: sourceBody } = response;
if (statusCode < 200 || statusCode >= 300) {
return result;
}
const isSplittableStream = typeof sourceBody?.stream === "function" ||
typeof sourceBody?.pipe === "function" ||
typeof sourceBody?.tee === "function";
if (!isSplittableStream) {
return result;
}
let bodyCopy = sourceBody;
let body = sourceBody;
if (sourceBody && typeof sourceBody === "object" && !(sourceBody instanceof Uint8Array)) {
[bodyCopy, body] = await utilStream.splitStream(sourceBody);
}
response.body = body;
const bodyBytes = await collectBody(bodyCopy, {
streamCollector: async (stream) => {
return utilStream.headStream(stream, MAX_BYTES_TO_INSPECT);
},
});
if (typeof bodyCopy?.destroy === "function") {
bodyCopy.destroy();
}
const bodyStringTail = config.utf8Encoder(bodyBytes.subarray(bodyBytes.length - 16));
if (bodyBytes.length === 0 && THROW_IF_EMPTY_BODY[context.commandName]) {
const err = new Error("S3 aborted request");
err.name = "InternalError";
throw err;
}
if (bodyStringTail && bodyStringTail.endsWith("</Error>")) {
response.statusCode = 400;
}
return result;
};
const collectBody = (streamBody = new Uint8Array(), context) => {
if (streamBody instanceof Uint8Array) {
return Promise.resolve(streamBody);
}
return context.streamCollector(streamBody) || Promise.resolve(new Uint8Array());
};
const throw200ExceptionsMiddlewareOptions = {
relation: "after",
toMiddleware: "deserializerMiddleware",
tags: ["THROW_200_EXCEPTIONS", "S3"],
name: "throw200ExceptionsMiddleware",
override: true,
};
const getThrow200ExceptionsPlugin = (config) => ({
applyToStack: (clientStack) => {
clientStack.addRelativeTo(throw200ExceptionsMiddleware(config), throw200ExceptionsMiddlewareOptions);
},
});
function bucketEndpointMiddleware(options) {
return (next, context) => async (args) => {
if (options.bucketEndpoint) {
const endpoint = context.endpointV2;
if (endpoint) {
const bucket = args.input.Bucket;
if (typeof bucket === "string") {
try {
const bucketEndpointUrl = new URL(bucket);
context.endpointV2 = {
...endpoint,
url: bucketEndpointUrl,
};
}
catch (e) {
const warning = `@aws-sdk/middleware-sdk-s3: bucketEndpoint=true was set but Bucket=${bucket} could not be parsed as URL.`;
if (context.logger?.constructor?.name === "NoOpLogger") {
console.warn(warning);
}
else {
context.logger?.warn?.(warning);
}
throw e;
}
}
}
}
return next(args);
};
}
const bucketEndpointMiddlewareOptions = {
name: "bucketEndpointMiddleware",
override: true,
relation: "after",
toMiddleware: "endpointV2Middleware",
};
function validateBucketNameMiddleware({ bucketEndpoint }) {
return (next) => async (args) => {
const { input: { Bucket }, } = args;
if (!bucketEndpoint && typeof Bucket === "string" && !utilArnParser.validate(Bucket) && Bucket.indexOf("/") >= 0) {
const err = new Error(`Bucket name shouldn't contain '/', received '${Bucket}'`);
err.name = "InvalidBucketName";
throw err;
}
return next({ ...args });
};
}
const validateBucketNameMiddlewareOptions = {
step: "initialize",
tags: ["VALIDATE_BUCKET_NAME"],
name: "validateBucketNameMiddleware",
override: true,
};
const getValidateBucketNamePlugin = (options) => ({
applyToStack: (clientStack) => {
clientStack.add(validateBucketNameMiddleware(options), validateBucketNameMiddlewareOptions);
clientStack.addRelativeTo(bucketEndpointMiddleware(options), bucketEndpointMiddlewareOptions);
},
});
exports.NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_OPTIONS = NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_OPTIONS;
exports.S3ExpressIdentityCache = S3ExpressIdentityCache;
exports.S3ExpressIdentityCacheEntry = S3ExpressIdentityCacheEntry;
exports.S3ExpressIdentityProviderImpl = S3ExpressIdentityProviderImpl;
exports.SignatureV4S3Express = SignatureV4S3Express;
exports.checkContentLengthHeader = checkContentLengthHeader;
exports.checkContentLengthHeaderMiddlewareOptions = checkContentLengthHeaderMiddlewareOptions;
exports.getCheckContentLengthHeaderPlugin = getCheckContentLengthHeaderPlugin;
exports.getRegionRedirectMiddlewarePlugin = getRegionRedirectMiddlewarePlugin;
exports.getS3ExpiresMiddlewarePlugin = getS3ExpiresMiddlewarePlugin;
exports.getS3ExpressHttpSigningPlugin = getS3ExpressHttpSigningPlugin;
exports.getS3ExpressPlugin = getS3ExpressPlugin;
exports.getThrow200ExceptionsPlugin = getThrow200ExceptionsPlugin;
exports.getValidateBucketNamePlugin = getValidateBucketNamePlugin;
exports.regionRedirectEndpointMiddleware = regionRedirectEndpointMiddleware;
exports.regionRedirectEndpointMiddlewareOptions = regionRedirectEndpointMiddlewareOptions;
exports.regionRedirectMiddleware = regionRedirectMiddleware;
exports.regionRedirectMiddlewareOptions = regionRedirectMiddlewareOptions;
exports.resolveS3Config = resolveS3Config;
exports.s3ExpiresMiddleware = s3ExpiresMiddleware;
exports.s3ExpiresMiddlewareOptions = s3ExpiresMiddlewareOptions;
exports.s3ExpressHttpSigningMiddleware = s3ExpressHttpSigningMiddleware;
exports.s3ExpressHttpSigningMiddlewareOptions = s3ExpressHttpSigningMiddlewareOptions;
exports.s3ExpressMiddleware = s3ExpressMiddleware;
exports.s3ExpressMiddlewareOptions = s3ExpressMiddlewareOptions;
exports.throw200ExceptionsMiddleware = throw200ExceptionsMiddleware;
exports.throw200ExceptionsMiddlewareOptions = throw200ExceptionsMiddlewareOptions;
exports.validateBucketNameMiddleware = validateBucketNameMiddleware;
exports.validateBucketNameMiddlewareOptions = validateBucketNameMiddlewareOptions;

View File

@@ -0,0 +1,36 @@
export function bucketEndpointMiddleware(options) {
return (next, context) => async (args) => {
if (options.bucketEndpoint) {
const endpoint = context.endpointV2;
if (endpoint) {
const bucket = args.input.Bucket;
if (typeof bucket === "string") {
try {
const bucketEndpointUrl = new URL(bucket);
context.endpointV2 = {
...endpoint,
url: bucketEndpointUrl,
};
}
catch (e) {
const warning = `@aws-sdk/middleware-sdk-s3: bucketEndpoint=true was set but Bucket=${bucket} could not be parsed as URL.`;
if (context.logger?.constructor?.name === "NoOpLogger") {
console.warn(warning);
}
else {
context.logger?.warn?.(warning);
}
throw e;
}
}
}
}
return next(args);
};
}
export const bucketEndpointMiddlewareOptions = {
name: "bucketEndpointMiddleware",
override: true,
relation: "after",
toMiddleware: "endpointV2Middleware",
};

View File

@@ -0,0 +1,32 @@
import { HttpRequest } from "@smithy/protocol-http";
import { NoOpLogger } from "@smithy/smithy-client";
const CONTENT_LENGTH_HEADER = "content-length";
const DECODED_CONTENT_LENGTH_HEADER = "x-amz-decoded-content-length";
export function checkContentLengthHeader() {
return (next, context) => async (args) => {
const { request } = args;
if (HttpRequest.isInstance(request)) {
if (!(CONTENT_LENGTH_HEADER in request.headers) && !(DECODED_CONTENT_LENGTH_HEADER in request.headers)) {
const message = `Are you using a Stream of unknown length as the Body of a PutObject request? Consider using Upload instead from @aws-sdk/lib-storage.`;
if (typeof context?.logger?.warn === "function" && !(context.logger instanceof NoOpLogger)) {
context.logger.warn(message);
}
else {
console.warn(message);
}
}
}
return next({ ...args });
};
}
export const checkContentLengthHeaderMiddlewareOptions = {
step: "finalizeRequest",
tags: ["CHECK_CONTENT_LENGTH_HEADER"],
name: "getCheckContentLengthHeaderPlugin",
override: true,
};
export const getCheckContentLengthHeaderPlugin = (unused) => ({
applyToStack: (clientStack) => {
clientStack.add(checkContentLengthHeader(), checkContentLengthHeaderMiddlewareOptions);
},
});

View File

@@ -0,0 +1,8 @@
export * from "./check-content-length-header";
export * from "./region-redirect-endpoint-middleware";
export * from "./region-redirect-middleware";
export * from "./s3-expires-middleware";
export * from "./s3-express/index";
export * from "./s3Configuration";
export * from "./throw-200-exceptions";
export * from "./validate-bucket-name";

View File

@@ -0,0 +1,41 @@
export const regionRedirectEndpointMiddleware = (config) => {
return (next, context) => async (args) => {
const originalRegion = await config.region();
const regionProviderRef = config.region;
let unlock = () => { };
if (context.__s3RegionRedirect) {
Object.defineProperty(config, "region", {
writable: false,
value: async () => {
return context.__s3RegionRedirect;
},
});
unlock = () => Object.defineProperty(config, "region", {
writable: true,
value: regionProviderRef,
});
}
try {
const result = await next(args);
if (context.__s3RegionRedirect) {
unlock();
const region = await config.region();
if (originalRegion !== region) {
throw new Error("Region was not restored following S3 region redirect.");
}
}
return result;
}
catch (e) {
unlock();
throw e;
}
};
};
export const regionRedirectEndpointMiddlewareOptions = {
tags: ["REGION_REDIRECT", "S3"],
name: "regionRedirectEndpointMiddleware",
override: true,
relation: "before",
toMiddleware: "endpointV2Middleware",
};

View File

@@ -0,0 +1,42 @@
import { regionRedirectEndpointMiddleware, regionRedirectEndpointMiddlewareOptions, } from "./region-redirect-endpoint-middleware";
export function regionRedirectMiddleware(clientConfig) {
return (next, context) => async (args) => {
try {
return await next(args);
}
catch (err) {
if (clientConfig.followRegionRedirects) {
const statusCode = err?.$metadata?.httpStatusCode;
const isHeadBucket = context.commandName === "HeadBucketCommand";
const bucketRegionHeader = err?.$response?.headers?.["x-amz-bucket-region"];
if (bucketRegionHeader) {
if (statusCode === 301 ||
(statusCode === 400 && (err?.name === "IllegalLocationConstraintException" || isHeadBucket))) {
try {
const actualRegion = bucketRegionHeader;
context.logger?.debug(`Redirecting from ${await clientConfig.region()} to ${actualRegion}`);
context.__s3RegionRedirect = actualRegion;
}
catch (e) {
throw new Error("Region redirect failed: " + e);
}
return next(args);
}
}
}
throw err;
}
};
}
export const regionRedirectMiddlewareOptions = {
step: "initialize",
tags: ["REGION_REDIRECT", "S3"],
name: "regionRedirectMiddleware",
override: true,
};
export const getRegionRedirectMiddlewarePlugin = (clientConfig) => ({
applyToStack: (clientStack) => {
clientStack.add(regionRedirectMiddleware(clientConfig), regionRedirectMiddlewareOptions);
clientStack.addRelativeTo(regionRedirectEndpointMiddleware(clientConfig), regionRedirectEndpointMiddlewareOptions);
},
});

View File

@@ -0,0 +1,33 @@
import { HttpResponse } from "@smithy/protocol-http";
import { parseRfc7231DateTime } from "@smithy/smithy-client";
export const s3ExpiresMiddleware = (config) => {
return (next, context) => async (args) => {
const result = await next(args);
const { response } = result;
if (HttpResponse.isInstance(response)) {
if (response.headers.expires) {
response.headers.expiresstring = response.headers.expires;
try {
parseRfc7231DateTime(response.headers.expires);
}
catch (e) {
context.logger?.warn(`AWS SDK Warning for ${context.clientName}::${context.commandName} response parsing (${response.headers.expires}): ${e}`);
delete response.headers.expires;
}
}
}
return result;
};
};
export const s3ExpiresMiddlewareOptions = {
tags: ["S3"],
name: "s3ExpiresMiddleware",
override: true,
relation: "after",
toMiddleware: "deserializerMiddleware",
};
export const getS3ExpiresMiddlewarePlugin = (clientConfig) => ({
applyToStack: (clientStack) => {
clientStack.addRelativeTo(s3ExpiresMiddleware(clientConfig), s3ExpiresMiddlewareOptions);
},
});

View File

@@ -0,0 +1,39 @@
export class S3ExpressIdentityCache {
data;
lastPurgeTime = Date.now();
static EXPIRED_CREDENTIAL_PURGE_INTERVAL_MS = 30_000;
constructor(data = {}) {
this.data = data;
}
get(key) {
const entry = this.data[key];
if (!entry) {
return;
}
return entry;
}
set(key, entry) {
this.data[key] = entry;
return entry;
}
delete(key) {
delete this.data[key];
}
async purgeExpired() {
const now = Date.now();
if (this.lastPurgeTime + S3ExpressIdentityCache.EXPIRED_CREDENTIAL_PURGE_INTERVAL_MS > now) {
return;
}
for (const key in this.data) {
const entry = this.data[key];
if (!entry.isRefreshing) {
const credential = await entry.identity;
if (credential.expiration) {
if (credential.expiration.getTime() < now) {
delete this.data[key];
}
}
}
}
}
}

View File

@@ -0,0 +1,14 @@
export class S3ExpressIdentityCacheEntry {
_identity;
isRefreshing;
accessed;
constructor(_identity, isRefreshing = false, accessed = Date.now()) {
this._identity = _identity;
this.isRefreshing = isRefreshing;
this.accessed = accessed;
}
get identity() {
this.accessed = Date.now();
return this._identity;
}
}

View File

@@ -0,0 +1,49 @@
import { S3ExpressIdentityCache } from "./S3ExpressIdentityCache";
import { S3ExpressIdentityCacheEntry } from "./S3ExpressIdentityCacheEntry";
export class S3ExpressIdentityProviderImpl {
createSessionFn;
cache;
static REFRESH_WINDOW_MS = 60_000;
constructor(createSessionFn, cache = new S3ExpressIdentityCache()) {
this.createSessionFn = createSessionFn;
this.cache = cache;
}
async getS3ExpressIdentity(awsIdentity, identityProperties) {
const key = identityProperties.Bucket;
const { cache } = this;
const entry = cache.get(key);
if (entry) {
return entry.identity.then((identity) => {
const isExpired = (identity.expiration?.getTime() ?? 0) < Date.now();
if (isExpired) {
return cache.set(key, new S3ExpressIdentityCacheEntry(this.getIdentity(key))).identity;
}
const isExpiringSoon = (identity.expiration?.getTime() ?? 0) < Date.now() + S3ExpressIdentityProviderImpl.REFRESH_WINDOW_MS;
if (isExpiringSoon && !entry.isRefreshing) {
entry.isRefreshing = true;
this.getIdentity(key).then((id) => {
cache.set(key, new S3ExpressIdentityCacheEntry(Promise.resolve(id)));
});
}
return identity;
});
}
return cache.set(key, new S3ExpressIdentityCacheEntry(this.getIdentity(key))).identity;
}
async getIdentity(key) {
await this.cache.purgeExpired().catch((error) => {
console.warn("Error while clearing expired entries in S3ExpressIdentityCache: \n" + error);
});
const session = await this.createSessionFn(key);
if (!session.Credentials?.AccessKeyId || !session.Credentials?.SecretAccessKey) {
throw new Error("s3#createSession response credential missing AccessKeyId or SecretAccessKey.");
}
const identity = {
accessKeyId: session.Credentials.AccessKeyId,
secretAccessKey: session.Credentials.SecretAccessKey,
sessionToken: session.Credentials.SessionToken,
expiration: session.Credentials.Expiration ? new Date(session.Credentials.Expiration) : undefined,
};
return identity;
}
}

View File

@@ -0,0 +1,41 @@
import { SignatureV4 } from "@smithy/signature-v4";
import { SESSION_TOKEN_HEADER, SESSION_TOKEN_QUERY_PARAM } from "../constants";
export class SignatureV4S3Express extends SignatureV4 {
async signWithCredentials(requestToSign, credentials, options) {
const credentialsWithoutSessionToken = getCredentialsWithoutSessionToken(credentials);
requestToSign.headers[SESSION_TOKEN_HEADER] = credentials.sessionToken;
const privateAccess = this;
setSingleOverride(privateAccess, credentialsWithoutSessionToken);
return privateAccess.signRequest(requestToSign, options ?? {});
}
async presignWithCredentials(requestToSign, credentials, options) {
const credentialsWithoutSessionToken = getCredentialsWithoutSessionToken(credentials);
delete requestToSign.headers[SESSION_TOKEN_HEADER];
requestToSign.headers[SESSION_TOKEN_QUERY_PARAM] = credentials.sessionToken;
requestToSign.query = requestToSign.query ?? {};
requestToSign.query[SESSION_TOKEN_QUERY_PARAM] = credentials.sessionToken;
const privateAccess = this;
setSingleOverride(privateAccess, credentialsWithoutSessionToken);
return this.presign(requestToSign, options);
}
}
function getCredentialsWithoutSessionToken(credentials) {
const credentialsWithoutSessionToken = {
accessKeyId: credentials.accessKeyId,
secretAccessKey: credentials.secretAccessKey,
expiration: credentials.expiration,
};
return credentialsWithoutSessionToken;
}
function setSingleOverride(privateAccess, credentialsWithoutSessionToken) {
const id = setTimeout(() => {
throw new Error("SignatureV4S3Express credential override was created but not called.");
}, 10);
const currentCredentialProvider = privateAccess.credentialProvider;
const overrideCredentialsProviderOnce = () => {
clearTimeout(id);
privateAccess.credentialProvider = currentCredentialProvider;
return Promise.resolve(credentialsWithoutSessionToken);
};
privateAccess.credentialProvider = overrideCredentialsProviderOnce;
}

View File

@@ -0,0 +1,13 @@
import { booleanSelector, SelectorType } from "@smithy/util-config-provider";
export const S3_EXPRESS_BUCKET_TYPE = "Directory";
export const S3_EXPRESS_BACKEND = "S3Express";
export const S3_EXPRESS_AUTH_SCHEME = "sigv4-s3express";
export const SESSION_TOKEN_QUERY_PARAM = "X-Amz-S3session-Token";
export const SESSION_TOKEN_HEADER = SESSION_TOKEN_QUERY_PARAM.toLowerCase();
export const NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_ENV_NAME = "AWS_S3_DISABLE_EXPRESS_SESSION_AUTH";
export const NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_INI_NAME = "s3_disable_express_session_auth";
export const NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_OPTIONS = {
environmentVariableSelector: (env) => booleanSelector(env, NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_ENV_NAME, SelectorType.ENV),
configFileSelector: (profile) => booleanSelector(profile, NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_INI_NAME, SelectorType.CONFIG),
default: false,
};

View File

@@ -0,0 +1,39 @@
import { httpSigningMiddlewareOptions } from "@smithy/core";
import { HttpRequest } from "@smithy/protocol-http";
import { SMITHY_CONTEXT_KEY, } from "@smithy/types";
import { getSmithyContext } from "@smithy/util-middleware";
import { signS3Express } from "./signS3Express";
const defaultErrorHandler = (signingProperties) => (error) => {
throw error;
};
const defaultSuccessHandler = (httpResponse, signingProperties) => { };
export const s3ExpressHttpSigningMiddlewareOptions = httpSigningMiddlewareOptions;
export const s3ExpressHttpSigningMiddleware = (config) => (next, context) => async (args) => {
if (!HttpRequest.isInstance(args.request)) {
return next(args);
}
const smithyContext = getSmithyContext(context);
const scheme = smithyContext.selectedHttpAuthScheme;
if (!scheme) {
throw new Error(`No HttpAuthScheme was selected: unable to sign request`);
}
const { httpAuthOption: { signingProperties = {} }, identity, signer, } = scheme;
let request;
if (context.s3ExpressIdentity) {
request = await signS3Express(context.s3ExpressIdentity, signingProperties, args.request, await config.signer());
}
else {
request = await signer.sign(args.request, identity, signingProperties);
}
const output = await next({
...args,
request,
}).catch((signer.errorHandler || defaultErrorHandler)(signingProperties));
(signer.successHandler || defaultSuccessHandler)(output.response, signingProperties);
return output;
};
export const getS3ExpressHttpSigningPlugin = (config) => ({
applyToStack: (clientStack) => {
clientStack.addRelativeTo(s3ExpressHttpSigningMiddleware(config), httpSigningMiddlewareOptions);
},
});

View File

@@ -0,0 +1,41 @@
import { setFeature } from "@aws-sdk/core";
import { HttpRequest } from "@smithy/protocol-http";
import { S3_EXPRESS_AUTH_SCHEME, S3_EXPRESS_BACKEND, S3_EXPRESS_BUCKET_TYPE, SESSION_TOKEN_HEADER } from "../constants";
export const s3ExpressMiddleware = (options) => {
return (next, context) => async (args) => {
if (context.endpointV2) {
const endpoint = context.endpointV2;
const isS3ExpressAuth = endpoint.properties?.authSchemes?.[0]?.name === S3_EXPRESS_AUTH_SCHEME;
const isS3ExpressBucket = endpoint.properties?.backend === S3_EXPRESS_BACKEND ||
endpoint.properties?.bucketType === S3_EXPRESS_BUCKET_TYPE;
if (isS3ExpressBucket) {
setFeature(context, "S3_EXPRESS_BUCKET", "J");
context.isS3ExpressBucket = true;
}
if (isS3ExpressAuth) {
const requestBucket = args.input.Bucket;
if (requestBucket) {
const s3ExpressIdentity = await options.s3ExpressIdentityProvider.getS3ExpressIdentity(await options.credentials(), {
Bucket: requestBucket,
});
context.s3ExpressIdentity = s3ExpressIdentity;
if (HttpRequest.isInstance(args.request) && s3ExpressIdentity.sessionToken) {
args.request.headers[SESSION_TOKEN_HEADER] = s3ExpressIdentity.sessionToken;
}
}
}
}
return next(args);
};
};
export const s3ExpressMiddlewareOptions = {
name: "s3ExpressMiddleware",
step: "build",
tags: ["S3", "S3_EXPRESS"],
override: true,
};
export const getS3ExpressPlugin = (options) => ({
applyToStack: (clientStack) => {
clientStack.add(s3ExpressMiddleware(options), s3ExpressMiddlewareOptions);
},
});

View File

@@ -0,0 +1,7 @@
export const signS3Express = async (s3ExpressIdentity, signingOptions, request, sigV4MultiRegionSigner) => {
const signedRequest = await sigV4MultiRegionSigner.signWithCredentials(request, s3ExpressIdentity, {});
if (signedRequest.headers["X-Amz-Security-Token"] || signedRequest.headers["x-amz-security-token"]) {
throw new Error("X-Amz-Security-Token must not be set for s3-express requests.");
}
return signedRequest;
};

View File

@@ -0,0 +1,7 @@
export { S3ExpressIdentityCache } from "./classes/S3ExpressIdentityCache";
export { S3ExpressIdentityCacheEntry } from "./classes/S3ExpressIdentityCacheEntry";
export { S3ExpressIdentityProviderImpl } from "./classes/S3ExpressIdentityProviderImpl";
export { SignatureV4S3Express } from "./classes/SignatureV4S3Express";
export { NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_OPTIONS } from "./constants";
export { getS3ExpressPlugin, s3ExpressMiddleware, s3ExpressMiddlewareOptions } from "./functions/s3ExpressMiddleware";
export { getS3ExpressHttpSigningPlugin, s3ExpressHttpSigningMiddleware, s3ExpressHttpSigningMiddlewareOptions, } from "./functions/s3ExpressHttpSigningMiddleware";

View File

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

View File

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

View File

@@ -0,0 +1,17 @@
import { S3ExpressIdentityProviderImpl } from "./s3-express";
export const resolveS3Config = (input, { session, }) => {
const [s3ClientProvider, CreateSessionCommandCtor] = session;
const { forcePathStyle, useAccelerateEndpoint, disableMultiregionAccessPoints, followRegionRedirects, s3ExpressIdentityProvider, bucketEndpoint, expectContinueHeader, } = input;
return Object.assign(input, {
forcePathStyle: forcePathStyle ?? false,
useAccelerateEndpoint: useAccelerateEndpoint ?? false,
disableMultiregionAccessPoints: disableMultiregionAccessPoints ?? false,
followRegionRedirects: followRegionRedirects ?? false,
s3ExpressIdentityProvider: s3ExpressIdentityProvider ??
new S3ExpressIdentityProviderImpl(async (key) => s3ClientProvider().send(new CreateSessionCommandCtor({
Bucket: key,
}))),
bucketEndpoint: bucketEndpoint ?? false,
expectContinueHeader: expectContinueHeader ?? 2_097_152,
});
};

View File

@@ -0,0 +1,67 @@
import { HttpResponse } from "@smithy/protocol-http";
import { headStream, splitStream } from "@smithy/util-stream";
const THROW_IF_EMPTY_BODY = {
CopyObjectCommand: true,
UploadPartCopyCommand: true,
CompleteMultipartUploadCommand: true,
};
const MAX_BYTES_TO_INSPECT = 3000;
export const throw200ExceptionsMiddleware = (config) => (next, context) => async (args) => {
const result = await next(args);
const { response } = result;
if (!HttpResponse.isInstance(response)) {
return result;
}
const { statusCode, body: sourceBody } = response;
if (statusCode < 200 || statusCode >= 300) {
return result;
}
const isSplittableStream = typeof sourceBody?.stream === "function" ||
typeof sourceBody?.pipe === "function" ||
typeof sourceBody?.tee === "function";
if (!isSplittableStream) {
return result;
}
let bodyCopy = sourceBody;
let body = sourceBody;
if (sourceBody && typeof sourceBody === "object" && !(sourceBody instanceof Uint8Array)) {
[bodyCopy, body] = await splitStream(sourceBody);
}
response.body = body;
const bodyBytes = await collectBody(bodyCopy, {
streamCollector: async (stream) => {
return headStream(stream, MAX_BYTES_TO_INSPECT);
},
});
if (typeof bodyCopy?.destroy === "function") {
bodyCopy.destroy();
}
const bodyStringTail = config.utf8Encoder(bodyBytes.subarray(bodyBytes.length - 16));
if (bodyBytes.length === 0 && THROW_IF_EMPTY_BODY[context.commandName]) {
const err = new Error("S3 aborted request");
err.name = "InternalError";
throw err;
}
if (bodyStringTail && bodyStringTail.endsWith("</Error>")) {
response.statusCode = 400;
}
return result;
};
const collectBody = (streamBody = new Uint8Array(), context) => {
if (streamBody instanceof Uint8Array) {
return Promise.resolve(streamBody);
}
return context.streamCollector(streamBody) || Promise.resolve(new Uint8Array());
};
export const throw200ExceptionsMiddlewareOptions = {
relation: "after",
toMiddleware: "deserializerMiddleware",
tags: ["THROW_200_EXCEPTIONS", "S3"],
name: "throw200ExceptionsMiddleware",
override: true,
};
export const getThrow200ExceptionsPlugin = (config) => ({
applyToStack: (clientStack) => {
clientStack.addRelativeTo(throw200ExceptionsMiddleware(config), throw200ExceptionsMiddlewareOptions);
},
});

View File

@@ -0,0 +1,25 @@
import { validate as validateArn } from "@aws-sdk/util-arn-parser";
import { bucketEndpointMiddleware, bucketEndpointMiddlewareOptions } from "./bucket-endpoint-middleware";
export function validateBucketNameMiddleware({ bucketEndpoint }) {
return (next) => async (args) => {
const { input: { Bucket }, } = args;
if (!bucketEndpoint && typeof Bucket === "string" && !validateArn(Bucket) && Bucket.indexOf("/") >= 0) {
const err = new Error(`Bucket name shouldn't contain '/', received '${Bucket}'`);
err.name = "InvalidBucketName";
throw err;
}
return next({ ...args });
};
}
export const validateBucketNameMiddlewareOptions = {
step: "initialize",
tags: ["VALIDATE_BUCKET_NAME"],
name: "validateBucketNameMiddleware",
override: true,
};
export const getValidateBucketNamePlugin = (options) => ({
applyToStack: (clientStack) => {
clientStack.add(validateBucketNameMiddleware(options), validateBucketNameMiddlewareOptions);
clientStack.addRelativeTo(bucketEndpointMiddleware(options), bucketEndpointMiddlewareOptions);
},
});

View File

@@ -0,0 +1,13 @@
import { RelativeMiddlewareOptions, SerializeMiddleware } from "@smithy/types";
interface PreviouslyResolved {
bucketEndpoint?: boolean;
}
/**
* @internal
*/
export declare function bucketEndpointMiddleware(options: PreviouslyResolved): SerializeMiddleware<any, any>;
/**
* @internal
*/
export declare const bucketEndpointMiddlewareOptions: RelativeMiddlewareOptions;
export {};

View File

@@ -0,0 +1,16 @@
import { FinalizeRequestHandlerOptions, FinalizeRequestMiddleware, Pluggable } from "@smithy/types";
/**
* @internal
*
* Log a warning if the input to PutObject is detected to be a Stream of unknown ContentLength and
* recommend the usage of the @aws-sdk/lib-storage Upload class.
*/
export declare function checkContentLengthHeader(): FinalizeRequestMiddleware<any, any>;
/**
* @internal
*/
export declare const checkContentLengthHeaderMiddlewareOptions: FinalizeRequestHandlerOptions;
/**
* @internal
*/
export declare const getCheckContentLengthHeaderPlugin: (unused: any) => Pluggable<any, any>;

View File

@@ -0,0 +1,8 @@
export * from "./check-content-length-header";
export * from "./region-redirect-endpoint-middleware";
export * from "./region-redirect-middleware";
export * from "./s3-expires-middleware";
export * from "./s3-express/index";
export * from "./s3Configuration";
export * from "./throw-200-exceptions";
export * from "./validate-bucket-name";

View File

@@ -0,0 +1,10 @@
import { RelativeMiddlewareOptions, SerializeMiddleware } from "@smithy/types";
import { PreviouslyResolved } from "./region-redirect-middleware";
/**
* @internal
*/
export declare const regionRedirectEndpointMiddleware: (config: PreviouslyResolved) => SerializeMiddleware<any, any>;
/**
* @internal
*/
export declare const regionRedirectEndpointMiddlewareOptions: RelativeMiddlewareOptions;

View File

@@ -0,0 +1,20 @@
import { InitializeHandlerOptions, InitializeMiddleware, Pluggable, Provider } from "@smithy/types";
/**
* @internal
*/
export interface PreviouslyResolved {
region: Provider<string>;
followRegionRedirects: boolean;
}
/**
* @internal
*/
export declare function regionRedirectMiddleware(clientConfig: PreviouslyResolved): InitializeMiddleware<any, any>;
/**
* @internal
*/
export declare const regionRedirectMiddlewareOptions: InitializeHandlerOptions;
/**
* @internal
*/
export declare const getRegionRedirectMiddlewarePlugin: (clientConfig: PreviouslyResolved) => Pluggable<any, any>;

View File

@@ -0,0 +1,26 @@
import { DeserializeMiddleware, Pluggable, RelativeMiddlewareOptions } from "@smithy/types";
/**
* @internal
*/
interface PreviouslyResolved {
}
/**
* @internal
*
* From the S3 Expires compatibility spec.
* A model transform will ensure S3#Expires remains a timestamp shape, though
* it is deprecated.
* If a particular object has a non-date string set as the Expires value,
* the SDK will have the raw string as "ExpiresString" on the response.
*
*/
export declare const s3ExpiresMiddleware: (config: PreviouslyResolved) => DeserializeMiddleware<any, any>;
/**
* @internal
*/
export declare const s3ExpiresMiddlewareOptions: RelativeMiddlewareOptions;
/**
* @internal
*/
export declare const getS3ExpiresMiddlewarePlugin: (clientConfig: PreviouslyResolved) => Pluggable<any, any>;
export {};

View File

@@ -0,0 +1,16 @@
import { S3ExpressIdentityCacheEntry } from "./S3ExpressIdentityCacheEntry";
/**
* @internal
*
* Stores identities by key.
*/
export declare class S3ExpressIdentityCache {
private data;
private lastPurgeTime;
static EXPIRED_CREDENTIAL_PURGE_INTERVAL_MS: number;
constructor(data?: Record<string, S3ExpressIdentityCacheEntry>);
get(key: string): undefined | S3ExpressIdentityCacheEntry;
set(key: string, entry: S3ExpressIdentityCacheEntry): S3ExpressIdentityCacheEntry;
delete(key: string): void;
purgeExpired(): Promise<void>;
}

View File

@@ -0,0 +1,16 @@
import { S3ExpressIdentity } from "../interfaces/S3ExpressIdentity";
/**
* @internal
*/
export declare class S3ExpressIdentityCacheEntry {
private _identity;
isRefreshing: boolean;
accessed: number;
/**
* @param identity - stored identity.
* @param accessed - timestamp of last access in epoch ms.
* @param isRefreshing - this key is currently in the process of being refreshed (background).
*/
constructor(_identity: Promise<S3ExpressIdentity>, isRefreshing?: boolean, accessed?: number);
get identity(): Promise<S3ExpressIdentity>;
}

View File

@@ -0,0 +1,32 @@
import { AwsCredentialIdentity } from "@aws-sdk/types";
import { S3ExpressIdentity } from "../interfaces/S3ExpressIdentity";
import { S3ExpressIdentityProvider } from "../interfaces/S3ExpressIdentityProvider";
import { S3ExpressIdentityCache } from "./S3ExpressIdentityCache";
/**
* @internal
*
* This should match S3::CreateSessionCommandOutput::SessionCredentials
* but it is not imported since that would create a circular dependency.
*/
type Credentials = {
AccessKeyId: string | undefined;
SecretAccessKey: string | undefined;
SessionToken: string | undefined;
Expiration: Date | undefined;
};
/**
* @internal
*/
export declare class S3ExpressIdentityProviderImpl implements S3ExpressIdentityProvider {
private createSessionFn;
private cache;
static REFRESH_WINDOW_MS: number;
constructor(createSessionFn: (key: string) => Promise<{
Credentials: Credentials;
}>, cache?: S3ExpressIdentityCache);
getS3ExpressIdentity(awsIdentity: AwsCredentialIdentity, identityProperties: {
Bucket: string;
} & Record<string, string>): Promise<S3ExpressIdentity>;
private getIdentity;
}
export {};

View File

@@ -0,0 +1,17 @@
import { AwsCredentialIdentity } from "@aws-sdk/types";
import { SignatureV4 } from "@smithy/signature-v4";
import { HttpRequest as IHttpRequest, RequestPresigningArguments, RequestSigningArguments } from "@smithy/types";
export declare class SignatureV4S3Express extends SignatureV4 {
/**
* Signs with alternate provided credentials instead of those provided in the
* constructor.
*
* Additionally omits the credential sessionToken and assigns it to the
* alternate header field for S3 Express.
*/
signWithCredentials(requestToSign: IHttpRequest, credentials: AwsCredentialIdentity, options?: RequestSigningArguments): Promise<IHttpRequest>;
/**
* Similar to {@link SignatureV4S3Express#signWithCredentials} but for presigning.
*/
presignWithCredentials(requestToSign: IHttpRequest, credentials: AwsCredentialIdentity, options?: RequestPresigningArguments): Promise<IHttpRequest>;
}

View File

@@ -0,0 +1,37 @@
import type { LoadedConfigSelectors } from "@smithy/node-config-provider";
/**
* @internal
*
* @deprecated will be replaced by backend.
*
* TODO(s3-express): non-beta value, backend == S3Express.
*/
export declare const S3_EXPRESS_BUCKET_TYPE = "Directory";
/**
* @internal
*/
export declare const S3_EXPRESS_BACKEND = "S3Express";
/**
* @internal
*/
export declare const S3_EXPRESS_AUTH_SCHEME = "sigv4-s3express";
/**
* @internal
*/
export declare const SESSION_TOKEN_QUERY_PARAM = "X-Amz-S3session-Token";
/**
* @internal
*/
export declare const SESSION_TOKEN_HEADER: string;
/**
* @internal
*/
export declare const NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_ENV_NAME = "AWS_S3_DISABLE_EXPRESS_SESSION_AUTH";
/**
* @internal
*/
export declare const NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_INI_NAME = "s3_disable_express_session_auth";
/**
* @internal
*/
export declare const NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_OPTIONS: LoadedConfigSelectors<boolean>;

View File

@@ -0,0 +1,27 @@
import { IHttpRequest } from "@smithy/protocol-http";
import { AuthScheme, AwsCredentialIdentity, FinalizeRequestMiddleware, Pluggable, RequestSigner } from "@smithy/types";
interface SigningProperties {
signingRegion: string;
signingDate: Date;
signingService: string;
}
interface PreviouslyResolved {
signer: (authScheme?: AuthScheme | undefined) => Promise<RequestSigner & {
signWithCredentials(req: IHttpRequest, identity: AwsCredentialIdentity, opts?: Partial<SigningProperties>): Promise<IHttpRequest>;
}>;
}
/**
* @internal
*/
export declare const s3ExpressHttpSigningMiddlewareOptions: import("@smithy/types").FinalizeRequestHandlerOptions & import("@smithy/types").RelativeLocation & Omit<import("@smithy/types").HandlerOptions, "step">;
/**
* @internal
*/
export declare const s3ExpressHttpSigningMiddleware: <Input extends object, Output extends object>(config: PreviouslyResolved) => FinalizeRequestMiddleware<any, any>;
/**
* @internal
*/
export declare const getS3ExpressHttpSigningPlugin: (config: {
signer: (authScheme?: AuthScheme | undefined) => Promise<RequestSigner>;
}) => Pluggable<any, any>;
export {};

View File

@@ -0,0 +1,32 @@
import { AwsCredentialIdentity } from "@aws-sdk/types";
import { BuildHandlerOptions, BuildMiddleware, Logger, MemoizedProvider, Pluggable } from "@smithy/types";
import { S3ExpressIdentity } from "../interfaces/S3ExpressIdentity";
import { S3ExpressIdentityProvider } from "../interfaces/S3ExpressIdentityProvider";
declare module "@smithy/types" {
interface HandlerExecutionContext {
/**
* Reserved key, only when using S3.
*/
s3ExpressIdentity?: S3ExpressIdentity;
}
}
/**
* @internal
*/
export interface S3ExpressResolvedConfig {
logger?: Logger;
s3ExpressIdentityProvider: S3ExpressIdentityProvider;
credentials: MemoizedProvider<AwsCredentialIdentity>;
}
/**
* @internal
*/
export declare const s3ExpressMiddleware: (options: S3ExpressResolvedConfig) => BuildMiddleware<any, any>;
/**
* @internal
*/
export declare const s3ExpressMiddlewareOptions: BuildHandlerOptions;
/**
* @internal
*/
export declare const getS3ExpressPlugin: (options: S3ExpressResolvedConfig) => Pluggable<any, any>;

View File

@@ -0,0 +1,9 @@
import type { AwsCredentialIdentity, HttpRequest as IHttpRequest } from "@smithy/types";
import { S3ExpressIdentity } from "../interfaces/S3ExpressIdentity";
export declare const signS3Express: (s3ExpressIdentity: S3ExpressIdentity, signingOptions: {
signingDate: Date;
signingRegion: string;
signingService: string;
}, request: IHttpRequest, sigV4MultiRegionSigner: {
signWithCredentials(req: IHttpRequest, identity: AwsCredentialIdentity, opts?: Partial<typeof signingOptions>): Promise<IHttpRequest>;
}) => Promise<IHttpRequest>;

View File

@@ -0,0 +1,9 @@
export { S3ExpressIdentityCache } from "./classes/S3ExpressIdentityCache";
export { S3ExpressIdentityCacheEntry } from "./classes/S3ExpressIdentityCacheEntry";
export { S3ExpressIdentityProviderImpl } from "./classes/S3ExpressIdentityProviderImpl";
export { SignatureV4S3Express } from "./classes/SignatureV4S3Express";
export { NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_OPTIONS } from "./constants";
export { getS3ExpressPlugin, s3ExpressMiddleware, s3ExpressMiddlewareOptions } from "./functions/s3ExpressMiddleware";
export { getS3ExpressHttpSigningPlugin, s3ExpressHttpSigningMiddleware, s3ExpressHttpSigningMiddlewareOptions, } from "./functions/s3ExpressHttpSigningMiddleware";
export { S3ExpressIdentity } from "./interfaces/S3ExpressIdentity";
export { S3ExpressIdentityProvider } from "./interfaces/S3ExpressIdentityProvider";

View File

@@ -0,0 +1,6 @@
import { AwsCredentialIdentity } from "@aws-sdk/types";
/**
* @public
*/
export interface S3ExpressIdentity extends AwsCredentialIdentity {
}

View File

@@ -0,0 +1,12 @@
import { AwsCredentialIdentity } from "@aws-sdk/types";
import { S3ExpressIdentity } from "./S3ExpressIdentity";
/**
* @public
*/
export interface S3ExpressIdentityProvider {
/**
* @param awsIdentity - pre-existing credentials.
* @param identityProperties - unknown.
*/
getS3ExpressIdentity(awsIdentity: AwsCredentialIdentity, identityProperties: Record<string, string>): Promise<S3ExpressIdentity>;
}

View File

@@ -0,0 +1,79 @@
import type { Client, Command } from "@smithy/types";
import { S3ExpressIdentityProvider } from "./s3-express";
/**
* All endpoint parameters with built-in bindings of AWS::S3::*
* @public
*/
export interface S3InputConfig {
/**
* Whether to force path style URLs for S3 objects
* (e.g., https://s3.amazonaws.com/<bucketName>/<key> instead of https://<bucketName>.s3.amazonaws.com/<key>
*/
forcePathStyle?: boolean;
/**
* Whether to use the S3 Transfer Acceleration endpoint by default
*/
useAccelerateEndpoint?: boolean;
/**
* Whether multi-region access points (MRAP) should be disabled.
*/
disableMultiregionAccessPoints?: boolean;
/**
* This feature was previously called the S3 Global Client.
* This can result in additional latency as failed requests are retried
* with a corrected region when receiving a permanent redirect error with status 301.
* This feature should only be used as a last resort if you do not know the region of your bucket(s) ahead of time.
*/
followRegionRedirects?: boolean;
/**
* Identity provider for an S3 feature.
*/
s3ExpressIdentityProvider?: S3ExpressIdentityProvider;
/**
* Whether to use the bucket name as the endpoint for this client.
*/
bucketEndpoint?: boolean;
/**
* This field configures the SDK's behavior around setting the `expect: 100-continue` header.
*
* Default: 2_097_152 (2 MB)
*
* When given as a boolean - always send or omit the header.
* When given as a number - minimum byte threshold of the payload before setting the header.
* Unmeasurable payload sizes (streams) will set the header too.
*
* The `expect: 100-continue` header is used to allow the server a chance to validate the PUT request
* headers before the client begins to send the object payload. This avoids wasteful data transmission for a
* request that is rejected.
*
* However, there is a trade-off where the request will take longer to complete.
*/
expectContinueHeader?: boolean | number;
}
/**
* This is a placeholder for the actual
* S3Client type from \@aws-sdk/client-s3. It is not explicitly
* imported to avoid a circular dependency.
* @internal
*/
type PlaceholderS3Client = Client<any, any, any> & any;
/**
* Placeholder for the constructor for CreateSessionCommand.
* @internal
*/
type PlaceholderCreateSessionCommandCtor = {
new (args: any): Command<any, any, any, any, any>;
};
export interface S3ResolvedConfig {
forcePathStyle: boolean;
useAccelerateEndpoint: boolean;
disableMultiregionAccessPoints: boolean;
followRegionRedirects: boolean;
s3ExpressIdentityProvider: S3ExpressIdentityProvider;
bucketEndpoint: boolean;
expectContinueHeader: boolean | number;
}
export declare const resolveS3Config: <T>(input: T & S3InputConfig, { session, }: {
session: [() => PlaceholderS3Client, PlaceholderCreateSessionCommandCtor];
}) => T & S3ResolvedConfig;
export {};

View File

@@ -0,0 +1,20 @@
import { DeserializeMiddleware, Encoder, Pluggable, RelativeMiddlewareOptions } from "@smithy/types";
type PreviouslyResolved = {
utf8Encoder: Encoder;
};
/**
* In case of an internal error/terminated connection, S3 operations may return 200 errors. CopyObject, UploadPartCopy,
* CompleteMultipartUpload may return empty payload or payload with only xml Preamble.
* @internal
*/
export declare const throw200ExceptionsMiddleware: (config: PreviouslyResolved) => DeserializeMiddleware<any, any>;
/**
* @internal
*/
export declare const throw200ExceptionsMiddlewareOptions: RelativeMiddlewareOptions;
/**
*
* @internal
*/
export declare const getThrow200ExceptionsPlugin: (config: PreviouslyResolved) => Pluggable<any, any>;
export {};

View File

@@ -0,0 +1,9 @@
import { RelativeMiddlewareOptions, SerializeMiddleware } from "@smithy/types";
interface PreviouslyResolved {
bucketEndpoint?: boolean;
}
export declare function bucketEndpointMiddleware(
options: PreviouslyResolved
): SerializeMiddleware<any, any>;
export declare const bucketEndpointMiddlewareOptions: RelativeMiddlewareOptions;
export {};

View File

@@ -0,0 +1,13 @@
import {
FinalizeRequestHandlerOptions,
FinalizeRequestMiddleware,
Pluggable,
} from "@smithy/types";
export declare function checkContentLengthHeader(): FinalizeRequestMiddleware<
any,
any
>;
export declare const checkContentLengthHeaderMiddlewareOptions: FinalizeRequestHandlerOptions;
export declare const getCheckContentLengthHeaderPlugin: (
unused: any
) => Pluggable<any, any>;

View File

@@ -0,0 +1,8 @@
export * from "./check-content-length-header";
export * from "./region-redirect-endpoint-middleware";
export * from "./region-redirect-middleware";
export * from "./s3-expires-middleware";
export * from "./s3-express/index";
export * from "./s3Configuration";
export * from "./throw-200-exceptions";
export * from "./validate-bucket-name";

View File

@@ -0,0 +1,6 @@
import { RelativeMiddlewareOptions, SerializeMiddleware } from "@smithy/types";
import { PreviouslyResolved } from "./region-redirect-middleware";
export declare const regionRedirectEndpointMiddleware: (
config: PreviouslyResolved
) => SerializeMiddleware<any, any>;
export declare const regionRedirectEndpointMiddlewareOptions: RelativeMiddlewareOptions;

View File

@@ -0,0 +1,17 @@
import {
InitializeHandlerOptions,
InitializeMiddleware,
Pluggable,
Provider,
} from "@smithy/types";
export interface PreviouslyResolved {
region: Provider<string>;
followRegionRedirects: boolean;
}
export declare function regionRedirectMiddleware(
clientConfig: PreviouslyResolved
): InitializeMiddleware<any, any>;
export declare const regionRedirectMiddlewareOptions: InitializeHandlerOptions;
export declare const getRegionRedirectMiddlewarePlugin: (
clientConfig: PreviouslyResolved
) => Pluggable<any, any>;

View File

@@ -0,0 +1,14 @@
import {
DeserializeMiddleware,
Pluggable,
RelativeMiddlewareOptions,
} from "@smithy/types";
interface PreviouslyResolved {}
export declare const s3ExpiresMiddleware: (
config: PreviouslyResolved
) => DeserializeMiddleware<any, any>;
export declare const s3ExpiresMiddlewareOptions: RelativeMiddlewareOptions;
export declare const getS3ExpiresMiddlewarePlugin: (
clientConfig: PreviouslyResolved
) => Pluggable<any, any>;
export {};

View File

@@ -0,0 +1,14 @@
import { S3ExpressIdentityCacheEntry } from "./S3ExpressIdentityCacheEntry";
export declare class S3ExpressIdentityCache {
private data;
private lastPurgeTime;
static EXPIRED_CREDENTIAL_PURGE_INTERVAL_MS: number;
constructor(data?: Record<string, S3ExpressIdentityCacheEntry>);
get(key: string): undefined | S3ExpressIdentityCacheEntry;
set(
key: string,
entry: S3ExpressIdentityCacheEntry
): S3ExpressIdentityCacheEntry;
delete(key: string): void;
purgeExpired(): Promise<void>;
}

View File

@@ -0,0 +1,12 @@
import { S3ExpressIdentity } from "../interfaces/S3ExpressIdentity";
export declare class S3ExpressIdentityCacheEntry {
private _identity;
isRefreshing: boolean;
accessed: number;
constructor(
_identity: Promise<S3ExpressIdentity>,
isRefreshing?: boolean,
accessed?: number
);
readonly identity: Promise<S3ExpressIdentity>;
}

View File

@@ -0,0 +1,31 @@
import { AwsCredentialIdentity } from "@aws-sdk/types";
import { S3ExpressIdentity } from "../interfaces/S3ExpressIdentity";
import { S3ExpressIdentityProvider } from "../interfaces/S3ExpressIdentityProvider";
import { S3ExpressIdentityCache } from "./S3ExpressIdentityCache";
type Credentials = {
AccessKeyId: string | undefined;
SecretAccessKey: string | undefined;
SessionToken: string | undefined;
Expiration: Date | undefined;
};
export declare class S3ExpressIdentityProviderImpl
implements S3ExpressIdentityProvider
{
private createSessionFn;
private cache;
static REFRESH_WINDOW_MS: number;
constructor(
createSessionFn: (key: string) => Promise<{
Credentials: Credentials;
}>,
cache?: S3ExpressIdentityCache
);
getS3ExpressIdentity(
awsIdentity: AwsCredentialIdentity,
identityProperties: {
Bucket: string;
} & Record<string, string>
): Promise<S3ExpressIdentity>;
private getIdentity;
}
export {};

View File

@@ -0,0 +1,19 @@
import { AwsCredentialIdentity } from "@aws-sdk/types";
import { SignatureV4 } from "@smithy/signature-v4";
import {
HttpRequest as IHttpRequest,
RequestPresigningArguments,
RequestSigningArguments,
} from "@smithy/types";
export declare class SignatureV4S3Express extends SignatureV4 {
signWithCredentials(
requestToSign: IHttpRequest,
credentials: AwsCredentialIdentity,
options?: RequestSigningArguments
): Promise<IHttpRequest>;
presignWithCredentials(
requestToSign: IHttpRequest,
credentials: AwsCredentialIdentity,
options?: RequestPresigningArguments
): Promise<IHttpRequest>;
}

View File

@@ -0,0 +1,11 @@
import { LoadedConfigSelectors } from "@smithy/node-config-provider";
export declare const S3_EXPRESS_BUCKET_TYPE = "Directory";
export declare const S3_EXPRESS_BACKEND = "S3Express";
export declare const S3_EXPRESS_AUTH_SCHEME = "sigv4-s3express";
export declare const SESSION_TOKEN_QUERY_PARAM = "X-Amz-S3session-Token";
export declare const SESSION_TOKEN_HEADER: string;
export declare const NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_ENV_NAME =
"AWS_S3_DISABLE_EXPRESS_SESSION_AUTH";
export declare const NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_INI_NAME =
"s3_disable_express_session_auth";
export declare const NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_OPTIONS: LoadedConfigSelectors<boolean>;

View File

@@ -0,0 +1,40 @@
import { IHttpRequest } from "@smithy/protocol-http";
import {
AuthScheme,
AwsCredentialIdentity,
FinalizeRequestMiddleware,
Pluggable,
RequestSigner,
} from "@smithy/types";
interface SigningProperties {
signingRegion: string;
signingDate: Date;
signingService: string;
}
interface PreviouslyResolved {
signer: (authScheme?: AuthScheme | undefined) => Promise<
RequestSigner & {
signWithCredentials(
req: IHttpRequest,
identity: AwsCredentialIdentity,
opts?: Partial<SigningProperties>
): Promise<IHttpRequest>;
}
>;
}
export declare const s3ExpressHttpSigningMiddlewareOptions: import("@smithy/types").FinalizeRequestHandlerOptions &
import("@smithy/types").RelativeLocation &
Pick<
import("@smithy/types").HandlerOptions,
Exclude<keyof import("@smithy/types").HandlerOptions, "step">
>;
export declare const s3ExpressHttpSigningMiddleware: <
Input extends object,
Output extends object
>(
config: PreviouslyResolved
) => FinalizeRequestMiddleware<any, any>;
export declare const getS3ExpressHttpSigningPlugin: (config: {
signer: (authScheme?: AuthScheme | undefined) => Promise<RequestSigner>;
}) => Pluggable<any, any>;
export {};

View File

@@ -0,0 +1,27 @@
import { AwsCredentialIdentity } from "@aws-sdk/types";
import {
BuildHandlerOptions,
BuildMiddleware,
Logger,
MemoizedProvider,
Pluggable,
} from "@smithy/types";
import { S3ExpressIdentity } from "../interfaces/S3ExpressIdentity";
import { S3ExpressIdentityProvider } from "../interfaces/S3ExpressIdentityProvider";
declare module "@smithy/types" {
interface HandlerExecutionContext {
s3ExpressIdentity?: S3ExpressIdentity;
}
}
export interface S3ExpressResolvedConfig {
logger?: Logger;
s3ExpressIdentityProvider: S3ExpressIdentityProvider;
credentials: MemoizedProvider<AwsCredentialIdentity>;
}
export declare const s3ExpressMiddleware: (
options: S3ExpressResolvedConfig
) => BuildMiddleware<any, any>;
export declare const s3ExpressMiddlewareOptions: BuildHandlerOptions;
export declare const getS3ExpressPlugin: (
options: S3ExpressResolvedConfig
) => Pluggable<any, any>;

View File

@@ -0,0 +1,21 @@
import {
AwsCredentialIdentity,
HttpRequest as IHttpRequest,
} from "@smithy/types";
import { S3ExpressIdentity } from "../interfaces/S3ExpressIdentity";
export declare const signS3Express: (
s3ExpressIdentity: S3ExpressIdentity,
signingOptions: {
signingDate: Date;
signingRegion: string;
signingService: string;
},
request: IHttpRequest,
sigV4MultiRegionSigner: {
signWithCredentials(
req: IHttpRequest,
identity: AwsCredentialIdentity,
opts?: Partial<typeof signingOptions>
): Promise<IHttpRequest>;
}
) => Promise<IHttpRequest>;

View File

@@ -0,0 +1,17 @@
export { S3ExpressIdentityCache } from "./classes/S3ExpressIdentityCache";
export { S3ExpressIdentityCacheEntry } from "./classes/S3ExpressIdentityCacheEntry";
export { S3ExpressIdentityProviderImpl } from "./classes/S3ExpressIdentityProviderImpl";
export { SignatureV4S3Express } from "./classes/SignatureV4S3Express";
export { NODE_DISABLE_S3_EXPRESS_SESSION_AUTH_OPTIONS } from "./constants";
export {
getS3ExpressPlugin,
s3ExpressMiddleware,
s3ExpressMiddlewareOptions,
} from "./functions/s3ExpressMiddleware";
export {
getS3ExpressHttpSigningPlugin,
s3ExpressHttpSigningMiddleware,
s3ExpressHttpSigningMiddlewareOptions,
} from "./functions/s3ExpressHttpSigningMiddleware";
export { S3ExpressIdentity } from "./interfaces/S3ExpressIdentity";
export { S3ExpressIdentityProvider } from "./interfaces/S3ExpressIdentityProvider";

View File

@@ -0,0 +1,2 @@
import { AwsCredentialIdentity } from "@aws-sdk/types";
export interface S3ExpressIdentity extends AwsCredentialIdentity {}

View File

@@ -0,0 +1,8 @@
import { AwsCredentialIdentity } from "@aws-sdk/types";
import { S3ExpressIdentity } from "./S3ExpressIdentity";
export interface S3ExpressIdentityProvider {
getS3ExpressIdentity(
awsIdentity: AwsCredentialIdentity,
identityProperties: Record<string, string>
): Promise<S3ExpressIdentity>;
}

View File

@@ -0,0 +1,33 @@
import { Client, Command } from "@smithy/types";
import { S3ExpressIdentityProvider } from "./s3-express";
export interface S3InputConfig {
forcePathStyle?: boolean;
useAccelerateEndpoint?: boolean;
disableMultiregionAccessPoints?: boolean;
followRegionRedirects?: boolean;
s3ExpressIdentityProvider?: S3ExpressIdentityProvider;
bucketEndpoint?: boolean;
expectContinueHeader?: boolean | number;
}
type PlaceholderS3Client = Client<any, any, any> & any;
type PlaceholderCreateSessionCommandCtor = {
new (args: any): Command<any, any, any, any, any>;
};
export interface S3ResolvedConfig {
forcePathStyle: boolean;
useAccelerateEndpoint: boolean;
disableMultiregionAccessPoints: boolean;
followRegionRedirects: boolean;
s3ExpressIdentityProvider: S3ExpressIdentityProvider;
bucketEndpoint: boolean;
expectContinueHeader: boolean | number;
}
export declare const resolveS3Config: <T>(
input: T & S3InputConfig,
{
session,
}: {
session: [() => PlaceholderS3Client, PlaceholderCreateSessionCommandCtor];
}
) => T & S3ResolvedConfig;
export {};

View File

@@ -0,0 +1,17 @@
import {
DeserializeMiddleware,
Encoder,
Pluggable,
RelativeMiddlewareOptions,
} from "@smithy/types";
type PreviouslyResolved = {
utf8Encoder: Encoder;
};
export declare const throw200ExceptionsMiddleware: (
config: PreviouslyResolved
) => DeserializeMiddleware<any, any>;
export declare const throw200ExceptionsMiddlewareOptions: RelativeMiddlewareOptions;
export declare const getThrow200ExceptionsPlugin: (
config: PreviouslyResolved
) => Pluggable<any, any>;
export {};

View File

@@ -0,0 +1,13 @@
import {
InitializeHandlerOptions,
InitializeMiddleware,
Pluggable,
} from "@smithy/types";
import { S3ResolvedConfig } from "./s3Configuration";
export declare function validateBucketNameMiddleware({
bucketEndpoint,
}: S3ResolvedConfig): InitializeMiddleware<any, any>;
export declare const validateBucketNameMiddlewareOptions: InitializeHandlerOptions;
export declare const getValidateBucketNamePlugin: (
options: S3ResolvedConfig
) => Pluggable<any, any>;

View File

@@ -0,0 +1,14 @@
import { InitializeHandlerOptions, InitializeMiddleware, Pluggable } from "@smithy/types";
import { S3ResolvedConfig } from "./s3Configuration";
/**
* @internal
*/
export declare function validateBucketNameMiddleware({ bucketEndpoint }: S3ResolvedConfig): InitializeMiddleware<any, any>;
/**
* @internal
*/
export declare const validateBucketNameMiddlewareOptions: InitializeHandlerOptions;
/**
* @internal
*/
export declare const getValidateBucketNamePlugin: (options: S3ResolvedConfig) => Pluggable<any, any>;

View File

@@ -0,0 +1,72 @@
{
"name": "@aws-sdk/middleware-sdk-s3",
"version": "3.970.0",
"scripts": {
"build": "concurrently 'yarn:build:types' 'yarn:build:es' && yarn build:cjs",
"build:cjs": "node ../../scripts/compilation/inline middleware-sdk-s3",
"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",
"test": "yarn g:vitest run",
"test:types": "tsc -p tsconfig.test.json",
"test:integration": "yarn g:vitest run -c vitest.config.integ.mts && yarn test:types",
"test:e2e": "yarn g:vitest run -c vitest.config.e2e.mts --mode development",
"extract:docs": "api-extractor run --local",
"test:watch": "yarn g:vitest watch",
"test:integration:watch": "yarn g:vitest watch -c vitest.config.integ.mts",
"test:e2e:watch": "yarn g:vitest watch -c vitest.config.e2e.mts"
},
"main": "./dist-cjs/index.js",
"module": "./dist-es/index.js",
"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-sdk/core": "3.970.0",
"@aws-sdk/types": "3.969.0",
"@aws-sdk/util-arn-parser": "3.968.0",
"@smithy/core": "^3.20.6",
"@smithy/node-config-provider": "^4.3.8",
"@smithy/protocol-http": "^5.3.8",
"@smithy/signature-v4": "^5.3.8",
"@smithy/smithy-client": "^4.10.8",
"@smithy/types": "^4.12.0",
"@smithy/util-config-provider": "^4.2.0",
"@smithy/util-middleware": "^4.2.8",
"@smithy/util-stream": "^4.5.10",
"@smithy/util-utf8": "^4.2.0",
"tslib": "^2.6.2"
},
"devDependencies": {
"@tsconfig/recommended": "1.0.1",
"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-sdk-s3",
"repository": {
"type": "git",
"url": "https://github.com/aws/aws-sdk-js-v3.git",
"directory": "packages/middleware-sdk-s3"
}
}