@bymax-one/nest-storage 1.1.2 → 1.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -13,6 +13,56 @@ note on each entry is the compatibility contract — read it, not the number.
13
13
 
14
14
  ## [Unreleased]
15
15
 
16
+ ## [1.1.4] - 2026-11-01
17
+
18
+ ### Changed
19
+
20
+ - **A missing bucket is no longer reported as an absent object, and `delete()` no longer hides it.** When
21
+ the provider answers `NoSuchBucket`, `download()`, `upload()`, `list()`, `copy()` and `delete()` now
22
+ reject with the new `STORAGE_BUCKET_NOT_FOUND` (404) instead of `STORAGE_OBJECT_NOT_FOUND`, and
23
+ `delete()`, which used to resolve successfully against a bucket that does not exist, rejects it.
24
+
25
+ **Apply to a derived backend:** a behaviour change for a deployment whose bucket is missing or
26
+ misnamed. Code that treated `STORAGE_OBJECT_NOT_FOUND` after a failed `download()`, `upload()`, `list()`
27
+ or `copy()` as "the bucket or key is not there" must also handle `STORAGE_BUCKET_NOT_FOUND`, and a
28
+ `delete()` that used to succeed silently now fails until the bucket exists. `head()` and `exists()` are
29
+ unchanged: a `HEAD` response has no body, so the provider cannot say which of the bucket and the key is
30
+ missing, and a missing bucket still reads as an absent object there (use `checkBucket()` to tell).
31
+
32
+ ### Added
33
+
34
+ - **`StorageService.checkBucket()`.** One `HeadBucket` that resolves when the bucket is reachable with these
35
+ credentials and otherwise rejects with a typed code: `STORAGE_BUCKET_NOT_FOUND` (404),
36
+ `STORAGE_BUCKET_ACCESS_DENIED` (403, which a provider also answers for a bucket the caller cannot list),
37
+ `STORAGE_BUCKET_REGION_MISMATCH` (301 or `PermanentRedirect`), `STORAGE_TIMEOUT`, or
38
+ `STORAGE_PROVIDER_ERROR`. Nothing calls it at boot; wire it into a readiness endpoint so a misconfigured
39
+ bucket keeps the instance out of rotation. It needs `s3:ListBucket`.
40
+
41
+ ## [1.1.3] - 2026-11-01
42
+
43
+ ### Fixed
44
+
45
+ - **A stream that stops delivering no longer holds a multipart upload open forever.** A multipart upload
46
+ waiting for the next bytes of a stream has no request in flight, so `requestTimeoutMs` never fired:
47
+ a client that sent a few MiB and went silent left `upload()` pending and the upload (and its parts)
48
+ open on the provider until a lifecycle rule reaped it. A new `uploadIdleTimeoutMs` bounds the silence.
49
+ Past it the library sends `AbortMultipartUpload`, destroys your stream and rejects `upload()` with
50
+ `STORAGE_TIMEOUT` and `details.phase: 'source-idle'`. The clock restarts on every chunk and runs only
51
+ while the library is waiting for data.
52
+
53
+ **Apply to a derived backend:** a behaviour change, on by default. A stream source that delivers no
54
+ bytes for `uploadIdleTimeoutMs` now aborts the multipart upload and rejects `STORAGE_TIMEOUT`; the
55
+ limit defaults to `requestTimeoutMs` (30 s). Set `uploadIdleTimeoutMs: 0` to restore the old
56
+ behaviour, or raise it for a source that legitimately pauses longer. It applies only to a stream that
57
+ takes the multipart path (no `size`, or at or above `multipart.thresholdBytes`); single-shot uploads
58
+ and `Buffer` bodies are unchanged. An invalid value (negative, fractional, not a number) is rejected
59
+ at startup as `STORAGE_INVALID_CONFIG`.
60
+ - **Reporting a failure can no longer replace it.** `deleteMany()`, the post-upload cleanup, `exists()` and
61
+ the multipart error mapping built a message with `String(err)` or `err.message`; for a rejection value
62
+ with no usable `toString` (an object with no prototype, one whose `toString` throws) that raised from
63
+ inside the catch and the new error escaped in place of the one being reported. A value is now described
64
+ by its string `message`, else its string form, else `non-printable rejection value`, and never throws.
65
+
16
66
  ## [1.1.2] - 2026-10-31
17
67
 
18
68
  ### Changed
@@ -455,4 +505,6 @@ have regressed from. They are kept because the reasoning is worth having.
455
505
  [1.1.0]: https://github.com/bymaxone/nest-storage/compare/v1.0.6...v1.1.0
456
506
  [1.1.1]: https://github.com/bymaxone/nest-storage/compare/v1.1.0...v1.1.1
457
507
  [1.1.2]: https://github.com/bymaxone/nest-storage/compare/v1.1.1...v1.1.2
458
- [Unreleased]: https://github.com/bymaxone/nest-storage/compare/v1.1.2...HEAD
508
+ [1.1.3]: https://github.com/bymaxone/nest-storage/compare/v1.1.2...v1.1.3
509
+ [1.1.4]: https://github.com/bymaxone/nest-storage/compare/v1.1.3...v1.1.4
510
+ [Unreleased]: https://github.com/bymaxone/nest-storage/compare/v1.1.4...HEAD
package/README.md CHANGED
@@ -267,6 +267,7 @@ The full configuration reference lives in `docs/technical_specification.md` §4.
267
267
  | `defaultCacheControl` | `string` | `public, max-age=31536000, immutable` | Default `Cache-Control` on uploads |
268
268
  | `defaultContentDisposition` | `'inline' \| 'attachment'` | `inline` | Default `Content-Disposition` on uploads |
269
269
  | `requestTimeoutMs` | `number` | `30000` | Per attempt, until the response headers arrive; see below the table |
270
+ | `uploadIdleTimeoutMs` | `number` | `30000` | Longest silence from a stream body during a multipart upload; follows `requestTimeoutMs` unless set, `0` disables; see below the table |
270
271
  | `signedUrls.defaultGetTtlSeconds` | `number` | `300` | Default TTL for `getDownloadUrl` |
271
272
  | `signedUrls.defaultPutTtlSeconds` | `number` | `300` | Default TTL for `getUploadUrl` |
272
273
  | `signedUrls.maxTtlSeconds` | `number` | `604800` | Per-request TTLs above this are clamped; a value above 604800 (the 7-day SigV4 limit) is reduced to it at init |
@@ -280,8 +281,11 @@ The full configuration reference lives in `docs/technical_specification.md` §4.
280
281
 
281
282
  **`requestTimeoutMs`** is passed to the S3 client's request handler as `requestTimeout` with `throwOnRequestTimeout` ([AWS SDK for JavaScript v3: `requestHandler: { requestTimeout: 3_000, ... }`][sdk-request-timeout]). It bounds one attempt, from sending the request until the response headers arrive, and an upload body counts toward it, so a large single-shot upload on a slow link needs a larger value. It does not limit reading a download stream. With `maxAttempts` above 1 a stalled request is retried, so the total wait is the timeout times the attempts.
282
283
 
284
+ **`uploadIdleTimeoutMs`** covers the gap `requestTimeoutMs` cannot: a multipart upload that is waiting for the next bytes of a stream has no request in flight, so a source that stops delivering (a client that stalls, a pipe that never closes) would hold the upload open on the provider indefinitely. When the source delivers nothing for this long, the upload is aborted (the provider is sent `AbortMultipartUpload`), your stream is destroyed and `upload()` rejects with `STORAGE_TIMEOUT` and `details.phase` set to `'source-idle'`. The clock restarts on every chunk and runs only while the library is waiting for data, so a slow but live source succeeds and a slow provider does not trip it. It defaults to the value of `requestTimeoutMs`; `0` turns it off. It applies only to a stream that takes the multipart path; a single-shot upload is bounded by `requestTimeoutMs`, and a `Buffer` cannot stall.
285
+
283
286
  [aws-presigned-expiry]: https://docs.aws.amazon.com/AmazonS3/latest/userguide/using-presigned-url.html
284
287
  [aws-get-object]: https://docs.aws.amazon.com/AmazonS3/latest/API/API_GetObject.html
288
+ [aws-head-object]: https://docs.aws.amazon.com/AmazonS3/latest/API/API_HeadObject.html
285
289
  [aws-mpu-limits]: https://docs.aws.amazon.com/AmazonS3/latest/userguide/qfacts.html
286
290
  [aws-mpu-abort-rule]: https://docs.aws.amazon.com/AmazonS3/latest/userguide/mpu-abort-incomplete-mpu-lifecycle-config.html
287
291
  [sdk-request-timeout]: https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/node-configuring-maxsockets.html
@@ -742,10 +746,13 @@ All errors are thrown as `StorageException extends HttpException`. The response
742
746
  | `STORAGE_BUCKET_UNDEFINED` | 400 | Operation without a bucket and no default in config |
743
747
  | `STORAGE_MULTIPART_ABORTED` | 500 | Multipart upload failed and was aborted |
744
748
  | `STORAGE_INVALID_CONFIG` | 500 | `BymaxStorageModuleOptions` validation failed at initialization |
745
- | `STORAGE_TIMEOUT` | 504 | An attempt got no response headers within `requestTimeoutMs` (the SDK's `TimeoutError`); a failure inside a multipart upload surfaces as `STORAGE_MULTIPART_ABORTED` |
749
+ | `STORAGE_TIMEOUT` | 504 | An attempt got no response headers within `requestTimeoutMs` (the SDK's `TimeoutError`); a multipart source that stays silent for `uploadIdleTimeoutMs` also surfaces as `STORAGE_TIMEOUT` (`details.phase: 'source-idle'`); any other failure inside a multipart upload surfaces as `STORAGE_MULTIPART_ABORTED` |
746
750
  | `STORAGE_LIFECYCLE_RULE_INVALID` | 400 | `BucketLifecycleService` input rejected: empty or over-long `id`, non-positive or non-integer `expirationDays`, bad `prefix`, or an id naming a rule outside `keyPrefix` (`details.reason`) |
747
751
  | `STORAGE_LIFECYCLE_UNSUPPORTED` | 501 | The provider does not implement the lifecycle API |
748
752
  | `STORAGE_LIFECYCLE_REJECTED` | 422 | The provider refused the lifecycle configuration |
753
+ | `STORAGE_BUCKET_NOT_FOUND` | 404 | The provider answered `NoSuchBucket` (any operation that gets an error body: `download()`, `upload()`, `list()`, `copy()`, `delete()`), or `checkBucket()` got a 404 |
754
+ | `STORAGE_BUCKET_ACCESS_DENIED` | 403 | `checkBucket()` got a 403: the credentials cannot use the bucket, or it does not exist and the credentials cannot list (S3 answers 403 to a caller without `s3:ListBucket`) |
755
+ | `STORAGE_BUCKET_REGION_MISMATCH` | 500 | `checkBucket()` got a 301 or `PermanentRedirect`: the bucket lives in another region than the configured one |
749
756
  | `STORAGE_NOT_MODIFIED` | 304 | `download()` with `ifNoneMatch` equal to the current ETag |
750
757
  | `STORAGE_PRECONDITION_FAILED` | 412 | `download()` with `ifMatch` different from the current ETag |
751
758
 
@@ -779,10 +786,13 @@ This is the index.
779
786
  | `head` | `(key, options?) => Promise<ObjectMetadata>` | Metadata without transferring the body |
780
787
  | `exists` | `(key, options?) => Promise<boolean>` | `head` reduced to a boolean; any non-404 failure is logged and returns `false` |
781
788
  | `getPublicUrl` | `(key, options?) => string` | Composed, not signed — for buckets that are public by policy |
782
- | `delete` | `(key, options?) => Promise<void>` | Idempotent, as S3 delete is |
789
+ | `delete` | `(key, options?) => Promise<void>` | Idempotent for a missing object, as S3 delete is; a missing bucket rejects `STORAGE_BUCKET_NOT_FOUND` |
783
790
  | `deleteMany` | `(keys: string[], options?) => Promise<DeleteManyResult>` | Partial failures are reported, not thrown |
784
791
  | `list` | `(options: ListOptions) => Promise<ListResult>` | Paginated by continuation token |
785
792
  | `copy` | `(options: CopyOptions) => Promise<{ etag }>` | Server-side; the bytes never reach this process |
793
+ | `checkBucket` | `(options?) => Promise<void>` | One `HeadBucket` for a readiness check; resolves when the bucket is reachable, otherwise rejects `STORAGE_BUCKET_NOT_FOUND`, `STORAGE_BUCKET_ACCESS_DENIED`, `STORAGE_BUCKET_REGION_MISMATCH` or `STORAGE_TIMEOUT`; needs `s3:ListBucket`; never called at boot |
794
+
795
+ **A missing bucket and `head()` / `exists()`.** A `HEAD` response has no body, so the provider cannot say which of the bucket and the key is missing: AWS documents that "if the `HEAD` request generates an error, it returns a generic code, such as `400 Bad Request`, `403 Forbidden`, `404 Not Found` ... It's not possible to retrieve the exact exception of these error codes" ([HeadObject][aws-head-object]). `head()` therefore rejects `STORAGE_OBJECT_NOT_FOUND` and `exists()` returns `false` for a missing bucket too. Call `checkBucket()` to tell the two apart, for example from a readiness endpoint.
786
796
 
787
797
  ### `SignedUrlService`
788
798
 
@@ -50,7 +50,10 @@ var STORAGE_ERROR_CODES = {
50
50
  STORAGE_LIFECYCLE_UNSUPPORTED: "STORAGE_LIFECYCLE_UNSUPPORTED",
51
51
  STORAGE_LIFECYCLE_REJECTED: "STORAGE_LIFECYCLE_REJECTED",
52
52
  STORAGE_NOT_MODIFIED: "STORAGE_NOT_MODIFIED",
53
- STORAGE_PRECONDITION_FAILED: "STORAGE_PRECONDITION_FAILED"
53
+ STORAGE_PRECONDITION_FAILED: "STORAGE_PRECONDITION_FAILED",
54
+ STORAGE_BUCKET_NOT_FOUND: "STORAGE_BUCKET_NOT_FOUND",
55
+ STORAGE_BUCKET_ACCESS_DENIED: "STORAGE_BUCKET_ACCESS_DENIED",
56
+ STORAGE_BUCKET_REGION_MISMATCH: "STORAGE_BUCKET_REGION_MISMATCH"
54
57
  };
55
58
 
56
59
  // src/server/errors/storage-error-messages.ts
@@ -77,7 +80,10 @@ var STORAGE_ERROR_MESSAGES = {
77
80
  [STORAGE_ERROR_CODES.STORAGE_LIFECYCLE_UNSUPPORTED]: "The storage provider does not support bucket lifecycle configuration",
78
81
  [STORAGE_ERROR_CODES.STORAGE_LIFECYCLE_REJECTED]: "The storage provider rejected the lifecycle configuration",
79
82
  [STORAGE_ERROR_CODES.STORAGE_NOT_MODIFIED]: "The object has not changed since the supplied ETag",
80
- [STORAGE_ERROR_CODES.STORAGE_PRECONDITION_FAILED]: "The object does not satisfy the supplied precondition"
83
+ [STORAGE_ERROR_CODES.STORAGE_PRECONDITION_FAILED]: "The object does not satisfy the supplied precondition",
84
+ [STORAGE_ERROR_CODES.STORAGE_BUCKET_NOT_FOUND]: "The bucket does not exist",
85
+ [STORAGE_ERROR_CODES.STORAGE_BUCKET_ACCESS_DENIED]: "The bucket cannot be accessed with these credentials (it may also not exist)",
86
+ [STORAGE_ERROR_CODES.STORAGE_BUCKET_REGION_MISMATCH]: "The bucket belongs to a different region than the configured one"
81
87
  };
82
88
  var STORAGE_ERROR_STATUS = {
83
89
  [STORAGE_ERROR_CODES.STORAGE_NOT_CONFIGURED]: common.HttpStatus.SERVICE_UNAVAILABLE,
@@ -102,7 +108,10 @@ var STORAGE_ERROR_STATUS = {
102
108
  [STORAGE_ERROR_CODES.STORAGE_LIFECYCLE_UNSUPPORTED]: common.HttpStatus.NOT_IMPLEMENTED,
103
109
  [STORAGE_ERROR_CODES.STORAGE_LIFECYCLE_REJECTED]: common.HttpStatus.UNPROCESSABLE_ENTITY,
104
110
  [STORAGE_ERROR_CODES.STORAGE_NOT_MODIFIED]: common.HttpStatus.NOT_MODIFIED,
105
- [STORAGE_ERROR_CODES.STORAGE_PRECONDITION_FAILED]: common.HttpStatus.PRECONDITION_FAILED
111
+ [STORAGE_ERROR_CODES.STORAGE_PRECONDITION_FAILED]: common.HttpStatus.PRECONDITION_FAILED,
112
+ [STORAGE_ERROR_CODES.STORAGE_BUCKET_NOT_FOUND]: common.HttpStatus.NOT_FOUND,
113
+ [STORAGE_ERROR_CODES.STORAGE_BUCKET_ACCESS_DENIED]: common.HttpStatus.FORBIDDEN,
114
+ [STORAGE_ERROR_CODES.STORAGE_BUCKET_REGION_MISMATCH]: common.HttpStatus.INTERNAL_SERVER_ERROR
106
115
  };
107
116
 
108
117
  // src/server/errors/storage-exception.ts
@@ -160,6 +169,10 @@ function validateOptions(options) {
160
169
  if (isObject(multipart) && typeof multipart.partSizeBytes === "number" && multipart.partSizeBytes < MIN_PART_SIZE_BYTES) {
161
170
  throw invalid("multipart.partSizeBytes must be >= 5 MB (S3 hard limit)");
162
171
  }
172
+ const idle = options.uploadIdleTimeoutMs;
173
+ if (idle !== void 0 && (typeof idle !== "number" || !Number.isInteger(idle) || idle < 0)) {
174
+ throw invalid("uploadIdleTimeoutMs must be an integer >= 0 (0 disables the guard)");
175
+ }
163
176
  if (options.serverSideEncryption === "aws:kms" && !options.kmsKeyId) {
164
177
  throw invalid('kmsKeyId is required when serverSideEncryption === "aws:kms"');
165
178
  }
@@ -213,6 +226,7 @@ function applyDefaults(options) {
213
226
  const hasCredentials = Boolean(options.credentials.accessKeyId) && Boolean(options.credentials.secretAccessKey);
214
227
  const publicBaseUrl = options.publicBaseUrl ?? `${trimTrailingSlashes(options.endpoint)}/${options.bucket}`;
215
228
  const credentials = { ...options.credentials };
229
+ const requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
216
230
  const resolved = {
217
231
  endpoint: options.endpoint,
218
232
  region: options.region,
@@ -233,7 +247,8 @@ function applyDefaults(options) {
233
247
  requestChecksumCalculation: options.requestChecksumCalculation ?? DEFAULT_CHECKSUM_CALCULATION,
234
248
  responseChecksumValidation: options.responseChecksumValidation ?? DEFAULT_CHECKSUM_VALIDATION,
235
249
  maxAttempts: options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS,
236
- requestTimeoutMs: options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
250
+ requestTimeoutMs,
251
+ uploadIdleTimeoutMs: options.uploadIdleTimeoutMs ?? requestTimeoutMs,
237
252
  hasCredentials
238
253
  };
239
254
  Object.defineProperty(resolved, "credentials", {
@@ -409,6 +424,13 @@ function mapAwsError(err, context) {
409
424
  requestId,
410
425
  awsMessage: e.message
411
426
  };
427
+ if (awsCode === "NoSuchBucket") {
428
+ return new StorageException(
429
+ STORAGE_ERROR_CODES.STORAGE_BUCKET_NOT_FOUND,
430
+ common.HttpStatus.NOT_FOUND,
431
+ details
432
+ );
433
+ }
412
434
  if (e.name === "NotFound" || httpStatus === 404) {
413
435
  return new StorageException(
414
436
  STORAGE_ERROR_CODES.STORAGE_OBJECT_NOT_FOUND,
@@ -996,6 +1018,145 @@ FileScannerService = __decorateClass([
996
1018
  __decorateParam(1, common.Inject(BYMAX_STORAGE_FILE_SCANNER))
997
1019
  ], FileScannerService);
998
1020
 
1021
+ // src/server/utils/describe-error.ts
1022
+ var NON_PRINTABLE_REJECTION = "non-printable rejection value";
1023
+ function describeError(value) {
1024
+ try {
1025
+ if (typeof value === "object" && value !== null) {
1026
+ const message = value.message;
1027
+ if (typeof message === "string") {
1028
+ return message;
1029
+ }
1030
+ }
1031
+ return String(value);
1032
+ } catch {
1033
+ return NON_PRINTABLE_REJECTION;
1034
+ }
1035
+ }
1036
+ var SourceIdleError = class extends Error {
1037
+ constructor(idleMs) {
1038
+ super(`The upload source delivered no bytes for ${String(idleMs)} ms`);
1039
+ this.idleMs = idleMs;
1040
+ this.name = "SourceIdleError";
1041
+ }
1042
+ idleMs;
1043
+ };
1044
+ function withinIdleTime(next, idleMs) {
1045
+ return new Promise((resolve, reject) => {
1046
+ const timer = setTimeout(() => {
1047
+ reject(new SourceIdleError(idleMs));
1048
+ }, idleMs);
1049
+ next.then(
1050
+ (value) => {
1051
+ clearTimeout(timer);
1052
+ resolve(value);
1053
+ },
1054
+ (error) => {
1055
+ clearTimeout(timer);
1056
+ reject(error instanceof Error ? error : new Error(describeError(error)));
1057
+ }
1058
+ );
1059
+ });
1060
+ }
1061
+ function withIdleTimeout(source, idleMs) {
1062
+ const iterator = source[Symbol.asyncIterator]();
1063
+ const wrapper = new stream.Readable({
1064
+ objectMode: false,
1065
+ // No read-ahead: with a buffer to fill, Node calls read() while the consumer is paused, and the
1066
+ // clock would run for bytes nobody has asked for. At 0, read() runs only on demand.
1067
+ highWaterMark: 0,
1068
+ read() {
1069
+ withinIdleTime(iterator.next(), idleMs).then(
1070
+ (step) => {
1071
+ wrapper.push(step.done === true ? null : step.value);
1072
+ },
1073
+ (error) => {
1074
+ wrapper.destroy(error);
1075
+ }
1076
+ );
1077
+ },
1078
+ destroy(error, callback) {
1079
+ destroyStream(source);
1080
+ callback(error);
1081
+ }
1082
+ });
1083
+ wrapper.once("error", () => void 0);
1084
+ return wrapper;
1085
+ }
1086
+ function guardIdleBody(body, idleMs) {
1087
+ if (isBufferLike(body)) {
1088
+ return body;
1089
+ }
1090
+ return idleMs === 0 ? body : withIdleTimeout(body, idleMs);
1091
+ }
1092
+
1093
+ // src/server/errors/multipart-error-mapper.ts
1094
+ function mapMultipartError(err, context) {
1095
+ if (err instanceof SourceIdleError) {
1096
+ return new StorageException(STORAGE_ERROR_CODES.STORAGE_TIMEOUT, common.HttpStatus.GATEWAY_TIMEOUT, {
1097
+ ...context,
1098
+ phase: "source-idle",
1099
+ idleMs: err.idleMs
1100
+ });
1101
+ }
1102
+ const bucketMissing = mapAwsError(err, context);
1103
+ if (bucketMissing.code === STORAGE_ERROR_CODES.STORAGE_BUCKET_NOT_FOUND) {
1104
+ return bucketMissing;
1105
+ }
1106
+ return new StorageException(STORAGE_ERROR_CODES.STORAGE_MULTIPART_ABORTED, void 0, {
1107
+ ...context,
1108
+ awsMessage: describeError(err)
1109
+ });
1110
+ }
1111
+ function mapBucketCheckError(err, context) {
1112
+ const failure = err ?? {};
1113
+ const status = failure.$metadata?.httpStatusCode;
1114
+ const details = { ...context, httpStatus: status, awsCode: failure.name };
1115
+ if (status === 301 || failure.name === "PermanentRedirect") {
1116
+ return new StorageException(
1117
+ STORAGE_ERROR_CODES.STORAGE_BUCKET_REGION_MISMATCH,
1118
+ void 0,
1119
+ details
1120
+ );
1121
+ }
1122
+ if (status === 403) {
1123
+ return new StorageException(
1124
+ STORAGE_ERROR_CODES.STORAGE_BUCKET_ACCESS_DENIED,
1125
+ void 0,
1126
+ details
1127
+ );
1128
+ }
1129
+ if (status === 404) {
1130
+ return new StorageException(
1131
+ STORAGE_ERROR_CODES.STORAGE_BUCKET_NOT_FOUND,
1132
+ common.HttpStatus.NOT_FOUND,
1133
+ details
1134
+ );
1135
+ }
1136
+ return mapAwsError(err, context);
1137
+ }
1138
+
1139
+ // src/server/utils/list-result.ts
1140
+ function toListedObject(obj, stripPrefix) {
1141
+ return {
1142
+ key: stripPrefix(obj.Key ?? ""),
1143
+ size: obj.Size ?? 0,
1144
+ etag: obj.ETag ?? "",
1145
+ lastModified: obj.LastModified ?? /* @__PURE__ */ new Date(0),
1146
+ ...obj.StorageClass !== void 0 ? { storageClass: obj.StorageClass } : {}
1147
+ };
1148
+ }
1149
+ function toListResult(response, stripPrefix) {
1150
+ const objects = (response.Contents ?? []).map((obj) => toListedObject(obj, stripPrefix));
1151
+ const commonPrefixes = (response.CommonPrefixes ?? []).map((cp) => cp.Prefix ?? "").filter((cp) => cp.length > 0).map((cp) => stripPrefix(cp));
1152
+ return {
1153
+ objects,
1154
+ commonPrefixes,
1155
+ isTruncated: response.IsTruncated ?? false,
1156
+ ...response.NextContinuationToken !== void 0 ? { nextContinuationToken: response.NextContinuationToken } : {}
1157
+ };
1158
+ }
1159
+
999
1160
  // src/server/utils/header-utils.ts
1000
1161
  function buildContentDisposition(perCall, defaultValue) {
1001
1162
  return perCall ?? defaultValue;
@@ -1191,7 +1352,7 @@ exports.StorageService = class StorageService {
1191
1352
  await this.delete(finalKey, { bucket }).catch((deleteErr) => {
1192
1353
  this.logger.error(
1193
1354
  `Post-upload cleanup failed for infected/inconclusive object: ${finalKey}`,
1194
- deleteErr.message
1355
+ describeError(deleteErr)
1195
1356
  );
1196
1357
  });
1197
1358
  throw scanErr;
@@ -1232,7 +1393,7 @@ exports.StorageService = class StorageService {
1232
1393
  if (err instanceof StorageException && err.code === STORAGE_ERROR_CODES.STORAGE_OBJECT_NOT_FOUND) {
1233
1394
  return false;
1234
1395
  }
1235
- this.logger.warn(`exists() \u2014 treating a non-404 error as "false": ${err.message}`);
1396
+ this.logger.warn(`exists() \u2014 treating a non-404 error as "false": ${describeError(err)}`);
1236
1397
  return false;
1237
1398
  }
1238
1399
  }
@@ -1321,6 +1482,26 @@ exports.StorageService = class StorageService {
1321
1482
  throw mapped;
1322
1483
  }
1323
1484
  }
1485
+ /**
1486
+ * Probes the bucket with one `HeadBucket`, for a readiness check: it resolves when the bucket
1487
+ * is reachable with these credentials and otherwise rejects with a typed code. Nothing in the
1488
+ * module calls it on its own, so booting costs no request. Needs `s3:ListBucket`.
1489
+ *
1490
+ * @param options - Optional per-call bucket override.
1491
+ * @throws StorageException `STORAGE_BUCKET_NOT_FOUND` (404), `STORAGE_BUCKET_ACCESS_DENIED` (403,
1492
+ * which a provider also answers for a bucket the caller cannot see), `STORAGE_BUCKET_REGION_MISMATCH`
1493
+ * (301), `STORAGE_TIMEOUT`, or `STORAGE_PROVIDER_ERROR`; `STORAGE_NOT_CONFIGURED` and
1494
+ * `STORAGE_BUCKET_UNDEFINED` before any request.
1495
+ */
1496
+ async checkBucket(options) {
1497
+ this.assertConfigured();
1498
+ const bucket = this.resolveBucket(options?.bucket);
1499
+ try {
1500
+ await this.s3Provider.getClient().send(new clientS3.HeadBucketCommand({ Bucket: bucket }));
1501
+ } catch (err) {
1502
+ throw mapBucketCheckError(err, { bucket, op: "checkBucket" });
1503
+ }
1504
+ }
1324
1505
  /** Throws when the S3 client was never built (missing credentials). */
1325
1506
  assertConfigured() {
1326
1507
  if (!this.s3Provider.isConfigured()) {
@@ -1416,7 +1597,7 @@ exports.StorageService = class StorageService {
1416
1597
  const params = {
1417
1598
  Bucket: bucket,
1418
1599
  Key: finalKey,
1419
- Body: options.body,
1600
+ Body: guardIdleBody(options.body, this.options.uploadIdleTimeoutMs),
1420
1601
  ContentType: options.contentType,
1421
1602
  CacheControl: buildCacheControl(options.cacheControl, this.options.defaultCacheControl),
1422
1603
  ContentDisposition: buildContentDisposition(
@@ -1452,11 +1633,7 @@ exports.StorageService = class StorageService {
1452
1633
  multipart: true
1453
1634
  });
1454
1635
  } catch (err) {
1455
- throw new StorageException(STORAGE_ERROR_CODES.STORAGE_MULTIPART_ABORTED, void 0, {
1456
- key: finalKey,
1457
- bucket,
1458
- awsMessage: err.message
1459
- });
1636
+ throw mapMultipartError(err, { key: finalKey, bucket });
1460
1637
  }
1461
1638
  }
1462
1639
  /** Converts a `Uint8Array` body to a `Buffer` for SDK safety; passes others through. */
@@ -1512,32 +1689,11 @@ exports.StorageService = class StorageService {
1512
1689
  Delimiter: options.delimiter
1513
1690
  })
1514
1691
  );
1515
- return this.toListResult(response);
1692
+ return toListResult(response, (key) => this.keyResolver.stripPrefix(key));
1516
1693
  } catch (err) {
1517
1694
  throw mapAwsError(err, { bucket, prefix, op: "list" });
1518
1695
  }
1519
1696
  }
1520
- /** Maps a `ListObjectsV2` response onto the public `ListResult` shape. */
1521
- toListResult(response) {
1522
- const objects = (response.Contents ?? []).map((obj) => this.toListedObject(obj));
1523
- const commonPrefixes = (response.CommonPrefixes ?? []).map((cp) => cp.Prefix ?? "").filter((cp) => cp.length > 0).map((cp) => this.keyResolver.stripPrefix(cp));
1524
- return {
1525
- objects,
1526
- commonPrefixes,
1527
- isTruncated: response.IsTruncated ?? false,
1528
- ...response.NextContinuationToken !== void 0 ? { nextContinuationToken: response.NextContinuationToken } : {}
1529
- };
1530
- }
1531
- /** Maps one `Contents` entry onto `ListedObject`, stripping the global prefix. */
1532
- toListedObject(obj) {
1533
- return {
1534
- key: this.keyResolver.stripPrefix(obj.Key ?? ""),
1535
- size: obj.Size ?? 0,
1536
- etag: obj.ETag ?? "",
1537
- lastModified: obj.LastModified ?? /* @__PURE__ */ new Date(0),
1538
- ...obj.StorageClass !== void 0 ? { storageClass: obj.StorageClass } : {}
1539
- };
1540
- }
1541
1697
  /**
1542
1698
  * Server-side copy of an object (no bytes flow through the app). Supports both
1543
1699
  * same-bucket and cross-bucket copies and preserves the source metadata.
@@ -1624,7 +1780,7 @@ exports.StorageService = class StorageService {
1624
1780
  }
1625
1781
  }
1626
1782
  } catch (err) {
1627
- const message = err instanceof Error ? err.message : String(err);
1783
+ const message = describeError(err);
1628
1784
  for (const key of chunk) {
1629
1785
  failed.push({ key: this.keyResolver.stripPrefix(key), error: message });
1630
1786
  }
@@ -168,6 +168,12 @@ interface BymaxStorageModuleOptions {
168
168
  maxAttempts?: number;
169
169
  /** Per-request timeout. Default: `30000` ms. */
170
170
  requestTimeoutMs?: number;
171
+ /**
172
+ * Longest silence, in milliseconds, tolerated from a stream body while a multipart upload
173
+ * waits for its next bytes; past it the upload is aborted and rejects `STORAGE_TIMEOUT`.
174
+ * An integer of at least `0`; `0` turns the guard off. Default: `requestTimeoutMs`.
175
+ */
176
+ uploadIdleTimeoutMs?: number;
171
177
  }
172
178
  /**
173
179
  * Asynchronous configuration for `BymaxStorageModule.forRootAsync()` — the
@@ -296,6 +302,7 @@ interface ResolvedBymaxStorageOptions {
296
302
  responseChecksumValidation: 'WHEN_SUPPORTED' | 'WHEN_REQUIRED';
297
303
  maxAttempts: number;
298
304
  requestTimeoutMs: number;
305
+ uploadIdleTimeoutMs: number;
299
306
  /** True when both `accessKeyId` and `secretAccessKey` are non-empty. */
300
307
  hasCredentials: boolean;
301
308
  }
@@ -805,6 +812,18 @@ declare class StorageService {
805
812
  * @param options - Optional per-call bucket override.
806
813
  */
807
814
  delete(key: string, options?: BucketScopedOptions): Promise<void>;
815
+ /**
816
+ * Probes the bucket with one `HeadBucket`, for a readiness check: it resolves when the bucket
817
+ * is reachable with these credentials and otherwise rejects with a typed code. Nothing in the
818
+ * module calls it on its own, so booting costs no request. Needs `s3:ListBucket`.
819
+ *
820
+ * @param options - Optional per-call bucket override.
821
+ * @throws StorageException `STORAGE_BUCKET_NOT_FOUND` (404), `STORAGE_BUCKET_ACCESS_DENIED` (403,
822
+ * which a provider also answers for a bucket the caller cannot see), `STORAGE_BUCKET_REGION_MISMATCH`
823
+ * (301), `STORAGE_TIMEOUT`, or `STORAGE_PROVIDER_ERROR`; `STORAGE_NOT_CONFIGURED` and
824
+ * `STORAGE_BUCKET_UNDEFINED` before any request.
825
+ */
826
+ checkBucket(options?: BucketScopedOptions): Promise<void>;
808
827
  /** Throws when the S3 client was never built (missing credentials). */
809
828
  private assertConfigured;
810
829
  /** Resolves the target bucket from a per-call override or the module default. */
@@ -843,10 +862,6 @@ declare class StorageService {
843
862
  * @throws StorageException mapped from any AWS failure.
844
863
  */
845
864
  list(options: ListOptions): Promise<ListResult>;
846
- /** Maps a `ListObjectsV2` response onto the public `ListResult` shape. */
847
- private toListResult;
848
- /** Maps one `Contents` entry onto `ListedObject`, stripping the global prefix. */
849
- private toListedObject;
850
865
  /**
851
866
  * Server-side copy of an object (no bytes flow through the app). Supports both
852
867
  * same-bucket and cross-bucket copies and preserves the source metadata.
@@ -1342,6 +1357,9 @@ declare const STORAGE_ERROR_CODES: {
1342
1357
  readonly STORAGE_LIFECYCLE_REJECTED: "STORAGE_LIFECYCLE_REJECTED";
1343
1358
  readonly STORAGE_NOT_MODIFIED: "STORAGE_NOT_MODIFIED";
1344
1359
  readonly STORAGE_PRECONDITION_FAILED: "STORAGE_PRECONDITION_FAILED";
1360
+ readonly STORAGE_BUCKET_NOT_FOUND: "STORAGE_BUCKET_NOT_FOUND";
1361
+ readonly STORAGE_BUCKET_ACCESS_DENIED: "STORAGE_BUCKET_ACCESS_DENIED";
1362
+ readonly STORAGE_BUCKET_REGION_MISMATCH: "STORAGE_BUCKET_REGION_MISMATCH";
1345
1363
  };
1346
1364
  /** Union of every stable storage error code. */
1347
1365
  type StorageErrorCode = (typeof STORAGE_ERROR_CODES)[keyof typeof STORAGE_ERROR_CODES];
@@ -168,6 +168,12 @@ interface BymaxStorageModuleOptions {
168
168
  maxAttempts?: number;
169
169
  /** Per-request timeout. Default: `30000` ms. */
170
170
  requestTimeoutMs?: number;
171
+ /**
172
+ * Longest silence, in milliseconds, tolerated from a stream body while a multipart upload
173
+ * waits for its next bytes; past it the upload is aborted and rejects `STORAGE_TIMEOUT`.
174
+ * An integer of at least `0`; `0` turns the guard off. Default: `requestTimeoutMs`.
175
+ */
176
+ uploadIdleTimeoutMs?: number;
171
177
  }
172
178
  /**
173
179
  * Asynchronous configuration for `BymaxStorageModule.forRootAsync()` — the
@@ -296,6 +302,7 @@ interface ResolvedBymaxStorageOptions {
296
302
  responseChecksumValidation: 'WHEN_SUPPORTED' | 'WHEN_REQUIRED';
297
303
  maxAttempts: number;
298
304
  requestTimeoutMs: number;
305
+ uploadIdleTimeoutMs: number;
299
306
  /** True when both `accessKeyId` and `secretAccessKey` are non-empty. */
300
307
  hasCredentials: boolean;
301
308
  }
@@ -805,6 +812,18 @@ declare class StorageService {
805
812
  * @param options - Optional per-call bucket override.
806
813
  */
807
814
  delete(key: string, options?: BucketScopedOptions): Promise<void>;
815
+ /**
816
+ * Probes the bucket with one `HeadBucket`, for a readiness check: it resolves when the bucket
817
+ * is reachable with these credentials and otherwise rejects with a typed code. Nothing in the
818
+ * module calls it on its own, so booting costs no request. Needs `s3:ListBucket`.
819
+ *
820
+ * @param options - Optional per-call bucket override.
821
+ * @throws StorageException `STORAGE_BUCKET_NOT_FOUND` (404), `STORAGE_BUCKET_ACCESS_DENIED` (403,
822
+ * which a provider also answers for a bucket the caller cannot see), `STORAGE_BUCKET_REGION_MISMATCH`
823
+ * (301), `STORAGE_TIMEOUT`, or `STORAGE_PROVIDER_ERROR`; `STORAGE_NOT_CONFIGURED` and
824
+ * `STORAGE_BUCKET_UNDEFINED` before any request.
825
+ */
826
+ checkBucket(options?: BucketScopedOptions): Promise<void>;
808
827
  /** Throws when the S3 client was never built (missing credentials). */
809
828
  private assertConfigured;
810
829
  /** Resolves the target bucket from a per-call override or the module default. */
@@ -843,10 +862,6 @@ declare class StorageService {
843
862
  * @throws StorageException mapped from any AWS failure.
844
863
  */
845
864
  list(options: ListOptions): Promise<ListResult>;
846
- /** Maps a `ListObjectsV2` response onto the public `ListResult` shape. */
847
- private toListResult;
848
- /** Maps one `Contents` entry onto `ListedObject`, stripping the global prefix. */
849
- private toListedObject;
850
865
  /**
851
866
  * Server-side copy of an object (no bytes flow through the app). Supports both
852
867
  * same-bucket and cross-bucket copies and preserves the source metadata.
@@ -1342,6 +1357,9 @@ declare const STORAGE_ERROR_CODES: {
1342
1357
  readonly STORAGE_LIFECYCLE_REJECTED: "STORAGE_LIFECYCLE_REJECTED";
1343
1358
  readonly STORAGE_NOT_MODIFIED: "STORAGE_NOT_MODIFIED";
1344
1359
  readonly STORAGE_PRECONDITION_FAILED: "STORAGE_PRECONDITION_FAILED";
1360
+ readonly STORAGE_BUCKET_NOT_FOUND: "STORAGE_BUCKET_NOT_FOUND";
1361
+ readonly STORAGE_BUCKET_ACCESS_DENIED: "STORAGE_BUCKET_ACCESS_DENIED";
1362
+ readonly STORAGE_BUCKET_REGION_MISMATCH: "STORAGE_BUCKET_REGION_MISMATCH";
1345
1363
  };
1346
1364
  /** Union of every stable storage error code. */
1347
1365
  type StorageErrorCode = (typeof STORAGE_ERROR_CODES)[keyof typeof STORAGE_ERROR_CODES];
@@ -1,7 +1,7 @@
1
1
  import { HttpStatus, Injectable, Inject, Global, Module, Logger, HttpException } from '@nestjs/common';
2
- import { S3Client, GetBucketLifecycleConfigurationCommand, DeleteBucketLifecycleCommand, PutBucketLifecycleConfigurationCommand, HeadObjectCommand, GetObjectCommand, DeleteObjectCommand, PutObjectCommand, ListObjectsV2Command, CopyObjectCommand, DeleteObjectsCommand, CreateMultipartUploadCommand, UploadPartCommand, CompleteMultipartUploadCommand } from '@aws-sdk/client-s3';
2
+ import { S3Client, GetBucketLifecycleConfigurationCommand, DeleteBucketLifecycleCommand, PutBucketLifecycleConfigurationCommand, HeadObjectCommand, GetObjectCommand, DeleteObjectCommand, HeadBucketCommand, PutObjectCommand, ListObjectsV2Command, CopyObjectCommand, DeleteObjectsCommand, CreateMultipartUploadCommand, UploadPartCommand, CompleteMultipartUploadCommand } from '@aws-sdk/client-s3';
3
3
  import { Upload } from '@aws-sdk/lib-storage';
4
- import { PassThrough } from 'stream';
4
+ import { PassThrough, Readable } from 'stream';
5
5
  import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
6
6
  import { createHash } from 'crypto';
7
7
 
@@ -48,7 +48,10 @@ var STORAGE_ERROR_CODES = {
48
48
  STORAGE_LIFECYCLE_UNSUPPORTED: "STORAGE_LIFECYCLE_UNSUPPORTED",
49
49
  STORAGE_LIFECYCLE_REJECTED: "STORAGE_LIFECYCLE_REJECTED",
50
50
  STORAGE_NOT_MODIFIED: "STORAGE_NOT_MODIFIED",
51
- STORAGE_PRECONDITION_FAILED: "STORAGE_PRECONDITION_FAILED"
51
+ STORAGE_PRECONDITION_FAILED: "STORAGE_PRECONDITION_FAILED",
52
+ STORAGE_BUCKET_NOT_FOUND: "STORAGE_BUCKET_NOT_FOUND",
53
+ STORAGE_BUCKET_ACCESS_DENIED: "STORAGE_BUCKET_ACCESS_DENIED",
54
+ STORAGE_BUCKET_REGION_MISMATCH: "STORAGE_BUCKET_REGION_MISMATCH"
52
55
  };
53
56
 
54
57
  // src/server/errors/storage-error-messages.ts
@@ -75,7 +78,10 @@ var STORAGE_ERROR_MESSAGES = {
75
78
  [STORAGE_ERROR_CODES.STORAGE_LIFECYCLE_UNSUPPORTED]: "The storage provider does not support bucket lifecycle configuration",
76
79
  [STORAGE_ERROR_CODES.STORAGE_LIFECYCLE_REJECTED]: "The storage provider rejected the lifecycle configuration",
77
80
  [STORAGE_ERROR_CODES.STORAGE_NOT_MODIFIED]: "The object has not changed since the supplied ETag",
78
- [STORAGE_ERROR_CODES.STORAGE_PRECONDITION_FAILED]: "The object does not satisfy the supplied precondition"
81
+ [STORAGE_ERROR_CODES.STORAGE_PRECONDITION_FAILED]: "The object does not satisfy the supplied precondition",
82
+ [STORAGE_ERROR_CODES.STORAGE_BUCKET_NOT_FOUND]: "The bucket does not exist",
83
+ [STORAGE_ERROR_CODES.STORAGE_BUCKET_ACCESS_DENIED]: "The bucket cannot be accessed with these credentials (it may also not exist)",
84
+ [STORAGE_ERROR_CODES.STORAGE_BUCKET_REGION_MISMATCH]: "The bucket belongs to a different region than the configured one"
79
85
  };
80
86
  var STORAGE_ERROR_STATUS = {
81
87
  [STORAGE_ERROR_CODES.STORAGE_NOT_CONFIGURED]: HttpStatus.SERVICE_UNAVAILABLE,
@@ -100,7 +106,10 @@ var STORAGE_ERROR_STATUS = {
100
106
  [STORAGE_ERROR_CODES.STORAGE_LIFECYCLE_UNSUPPORTED]: HttpStatus.NOT_IMPLEMENTED,
101
107
  [STORAGE_ERROR_CODES.STORAGE_LIFECYCLE_REJECTED]: HttpStatus.UNPROCESSABLE_ENTITY,
102
108
  [STORAGE_ERROR_CODES.STORAGE_NOT_MODIFIED]: HttpStatus.NOT_MODIFIED,
103
- [STORAGE_ERROR_CODES.STORAGE_PRECONDITION_FAILED]: HttpStatus.PRECONDITION_FAILED
109
+ [STORAGE_ERROR_CODES.STORAGE_PRECONDITION_FAILED]: HttpStatus.PRECONDITION_FAILED,
110
+ [STORAGE_ERROR_CODES.STORAGE_BUCKET_NOT_FOUND]: HttpStatus.NOT_FOUND,
111
+ [STORAGE_ERROR_CODES.STORAGE_BUCKET_ACCESS_DENIED]: HttpStatus.FORBIDDEN,
112
+ [STORAGE_ERROR_CODES.STORAGE_BUCKET_REGION_MISMATCH]: HttpStatus.INTERNAL_SERVER_ERROR
104
113
  };
105
114
 
106
115
  // src/server/errors/storage-exception.ts
@@ -158,6 +167,10 @@ function validateOptions(options) {
158
167
  if (isObject(multipart) && typeof multipart.partSizeBytes === "number" && multipart.partSizeBytes < MIN_PART_SIZE_BYTES) {
159
168
  throw invalid("multipart.partSizeBytes must be >= 5 MB (S3 hard limit)");
160
169
  }
170
+ const idle = options.uploadIdleTimeoutMs;
171
+ if (idle !== void 0 && (typeof idle !== "number" || !Number.isInteger(idle) || idle < 0)) {
172
+ throw invalid("uploadIdleTimeoutMs must be an integer >= 0 (0 disables the guard)");
173
+ }
161
174
  if (options.serverSideEncryption === "aws:kms" && !options.kmsKeyId) {
162
175
  throw invalid('kmsKeyId is required when serverSideEncryption === "aws:kms"');
163
176
  }
@@ -211,6 +224,7 @@ function applyDefaults(options) {
211
224
  const hasCredentials = Boolean(options.credentials.accessKeyId) && Boolean(options.credentials.secretAccessKey);
212
225
  const publicBaseUrl = options.publicBaseUrl ?? `${trimTrailingSlashes(options.endpoint)}/${options.bucket}`;
213
226
  const credentials = { ...options.credentials };
227
+ const requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
214
228
  const resolved = {
215
229
  endpoint: options.endpoint,
216
230
  region: options.region,
@@ -231,7 +245,8 @@ function applyDefaults(options) {
231
245
  requestChecksumCalculation: options.requestChecksumCalculation ?? DEFAULT_CHECKSUM_CALCULATION,
232
246
  responseChecksumValidation: options.responseChecksumValidation ?? DEFAULT_CHECKSUM_VALIDATION,
233
247
  maxAttempts: options.maxAttempts ?? DEFAULT_MAX_ATTEMPTS,
234
- requestTimeoutMs: options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
248
+ requestTimeoutMs,
249
+ uploadIdleTimeoutMs: options.uploadIdleTimeoutMs ?? requestTimeoutMs,
235
250
  hasCredentials
236
251
  };
237
252
  Object.defineProperty(resolved, "credentials", {
@@ -407,6 +422,13 @@ function mapAwsError(err, context) {
407
422
  requestId,
408
423
  awsMessage: e.message
409
424
  };
425
+ if (awsCode === "NoSuchBucket") {
426
+ return new StorageException(
427
+ STORAGE_ERROR_CODES.STORAGE_BUCKET_NOT_FOUND,
428
+ HttpStatus.NOT_FOUND,
429
+ details
430
+ );
431
+ }
410
432
  if (e.name === "NotFound" || httpStatus === 404) {
411
433
  return new StorageException(
412
434
  STORAGE_ERROR_CODES.STORAGE_OBJECT_NOT_FOUND,
@@ -994,6 +1016,145 @@ FileScannerService = __decorateClass([
994
1016
  __decorateParam(1, Inject(BYMAX_STORAGE_FILE_SCANNER))
995
1017
  ], FileScannerService);
996
1018
 
1019
+ // src/server/utils/describe-error.ts
1020
+ var NON_PRINTABLE_REJECTION = "non-printable rejection value";
1021
+ function describeError(value) {
1022
+ try {
1023
+ if (typeof value === "object" && value !== null) {
1024
+ const message = value.message;
1025
+ if (typeof message === "string") {
1026
+ return message;
1027
+ }
1028
+ }
1029
+ return String(value);
1030
+ } catch {
1031
+ return NON_PRINTABLE_REJECTION;
1032
+ }
1033
+ }
1034
+ var SourceIdleError = class extends Error {
1035
+ constructor(idleMs) {
1036
+ super(`The upload source delivered no bytes for ${String(idleMs)} ms`);
1037
+ this.idleMs = idleMs;
1038
+ this.name = "SourceIdleError";
1039
+ }
1040
+ idleMs;
1041
+ };
1042
+ function withinIdleTime(next, idleMs) {
1043
+ return new Promise((resolve, reject) => {
1044
+ const timer = setTimeout(() => {
1045
+ reject(new SourceIdleError(idleMs));
1046
+ }, idleMs);
1047
+ next.then(
1048
+ (value) => {
1049
+ clearTimeout(timer);
1050
+ resolve(value);
1051
+ },
1052
+ (error) => {
1053
+ clearTimeout(timer);
1054
+ reject(error instanceof Error ? error : new Error(describeError(error)));
1055
+ }
1056
+ );
1057
+ });
1058
+ }
1059
+ function withIdleTimeout(source, idleMs) {
1060
+ const iterator = source[Symbol.asyncIterator]();
1061
+ const wrapper = new Readable({
1062
+ objectMode: false,
1063
+ // No read-ahead: with a buffer to fill, Node calls read() while the consumer is paused, and the
1064
+ // clock would run for bytes nobody has asked for. At 0, read() runs only on demand.
1065
+ highWaterMark: 0,
1066
+ read() {
1067
+ withinIdleTime(iterator.next(), idleMs).then(
1068
+ (step) => {
1069
+ wrapper.push(step.done === true ? null : step.value);
1070
+ },
1071
+ (error) => {
1072
+ wrapper.destroy(error);
1073
+ }
1074
+ );
1075
+ },
1076
+ destroy(error, callback) {
1077
+ destroyStream(source);
1078
+ callback(error);
1079
+ }
1080
+ });
1081
+ wrapper.once("error", () => void 0);
1082
+ return wrapper;
1083
+ }
1084
+ function guardIdleBody(body, idleMs) {
1085
+ if (isBufferLike(body)) {
1086
+ return body;
1087
+ }
1088
+ return idleMs === 0 ? body : withIdleTimeout(body, idleMs);
1089
+ }
1090
+
1091
+ // src/server/errors/multipart-error-mapper.ts
1092
+ function mapMultipartError(err, context) {
1093
+ if (err instanceof SourceIdleError) {
1094
+ return new StorageException(STORAGE_ERROR_CODES.STORAGE_TIMEOUT, HttpStatus.GATEWAY_TIMEOUT, {
1095
+ ...context,
1096
+ phase: "source-idle",
1097
+ idleMs: err.idleMs
1098
+ });
1099
+ }
1100
+ const bucketMissing = mapAwsError(err, context);
1101
+ if (bucketMissing.code === STORAGE_ERROR_CODES.STORAGE_BUCKET_NOT_FOUND) {
1102
+ return bucketMissing;
1103
+ }
1104
+ return new StorageException(STORAGE_ERROR_CODES.STORAGE_MULTIPART_ABORTED, void 0, {
1105
+ ...context,
1106
+ awsMessage: describeError(err)
1107
+ });
1108
+ }
1109
+ function mapBucketCheckError(err, context) {
1110
+ const failure = err ?? {};
1111
+ const status = failure.$metadata?.httpStatusCode;
1112
+ const details = { ...context, httpStatus: status, awsCode: failure.name };
1113
+ if (status === 301 || failure.name === "PermanentRedirect") {
1114
+ return new StorageException(
1115
+ STORAGE_ERROR_CODES.STORAGE_BUCKET_REGION_MISMATCH,
1116
+ void 0,
1117
+ details
1118
+ );
1119
+ }
1120
+ if (status === 403) {
1121
+ return new StorageException(
1122
+ STORAGE_ERROR_CODES.STORAGE_BUCKET_ACCESS_DENIED,
1123
+ void 0,
1124
+ details
1125
+ );
1126
+ }
1127
+ if (status === 404) {
1128
+ return new StorageException(
1129
+ STORAGE_ERROR_CODES.STORAGE_BUCKET_NOT_FOUND,
1130
+ HttpStatus.NOT_FOUND,
1131
+ details
1132
+ );
1133
+ }
1134
+ return mapAwsError(err, context);
1135
+ }
1136
+
1137
+ // src/server/utils/list-result.ts
1138
+ function toListedObject(obj, stripPrefix) {
1139
+ return {
1140
+ key: stripPrefix(obj.Key ?? ""),
1141
+ size: obj.Size ?? 0,
1142
+ etag: obj.ETag ?? "",
1143
+ lastModified: obj.LastModified ?? /* @__PURE__ */ new Date(0),
1144
+ ...obj.StorageClass !== void 0 ? { storageClass: obj.StorageClass } : {}
1145
+ };
1146
+ }
1147
+ function toListResult(response, stripPrefix) {
1148
+ const objects = (response.Contents ?? []).map((obj) => toListedObject(obj, stripPrefix));
1149
+ const commonPrefixes = (response.CommonPrefixes ?? []).map((cp) => cp.Prefix ?? "").filter((cp) => cp.length > 0).map((cp) => stripPrefix(cp));
1150
+ return {
1151
+ objects,
1152
+ commonPrefixes,
1153
+ isTruncated: response.IsTruncated ?? false,
1154
+ ...response.NextContinuationToken !== void 0 ? { nextContinuationToken: response.NextContinuationToken } : {}
1155
+ };
1156
+ }
1157
+
997
1158
  // src/server/utils/header-utils.ts
998
1159
  function buildContentDisposition(perCall, defaultValue) {
999
1160
  return perCall ?? defaultValue;
@@ -1189,7 +1350,7 @@ var StorageService = class {
1189
1350
  await this.delete(finalKey, { bucket }).catch((deleteErr) => {
1190
1351
  this.logger.error(
1191
1352
  `Post-upload cleanup failed for infected/inconclusive object: ${finalKey}`,
1192
- deleteErr.message
1353
+ describeError(deleteErr)
1193
1354
  );
1194
1355
  });
1195
1356
  throw scanErr;
@@ -1230,7 +1391,7 @@ var StorageService = class {
1230
1391
  if (err instanceof StorageException && err.code === STORAGE_ERROR_CODES.STORAGE_OBJECT_NOT_FOUND) {
1231
1392
  return false;
1232
1393
  }
1233
- this.logger.warn(`exists() \u2014 treating a non-404 error as "false": ${err.message}`);
1394
+ this.logger.warn(`exists() \u2014 treating a non-404 error as "false": ${describeError(err)}`);
1234
1395
  return false;
1235
1396
  }
1236
1397
  }
@@ -1319,6 +1480,26 @@ var StorageService = class {
1319
1480
  throw mapped;
1320
1481
  }
1321
1482
  }
1483
+ /**
1484
+ * Probes the bucket with one `HeadBucket`, for a readiness check: it resolves when the bucket
1485
+ * is reachable with these credentials and otherwise rejects with a typed code. Nothing in the
1486
+ * module calls it on its own, so booting costs no request. Needs `s3:ListBucket`.
1487
+ *
1488
+ * @param options - Optional per-call bucket override.
1489
+ * @throws StorageException `STORAGE_BUCKET_NOT_FOUND` (404), `STORAGE_BUCKET_ACCESS_DENIED` (403,
1490
+ * which a provider also answers for a bucket the caller cannot see), `STORAGE_BUCKET_REGION_MISMATCH`
1491
+ * (301), `STORAGE_TIMEOUT`, or `STORAGE_PROVIDER_ERROR`; `STORAGE_NOT_CONFIGURED` and
1492
+ * `STORAGE_BUCKET_UNDEFINED` before any request.
1493
+ */
1494
+ async checkBucket(options) {
1495
+ this.assertConfigured();
1496
+ const bucket = this.resolveBucket(options?.bucket);
1497
+ try {
1498
+ await this.s3Provider.getClient().send(new HeadBucketCommand({ Bucket: bucket }));
1499
+ } catch (err) {
1500
+ throw mapBucketCheckError(err, { bucket, op: "checkBucket" });
1501
+ }
1502
+ }
1322
1503
  /** Throws when the S3 client was never built (missing credentials). */
1323
1504
  assertConfigured() {
1324
1505
  if (!this.s3Provider.isConfigured()) {
@@ -1414,7 +1595,7 @@ var StorageService = class {
1414
1595
  const params = {
1415
1596
  Bucket: bucket,
1416
1597
  Key: finalKey,
1417
- Body: options.body,
1598
+ Body: guardIdleBody(options.body, this.options.uploadIdleTimeoutMs),
1418
1599
  ContentType: options.contentType,
1419
1600
  CacheControl: buildCacheControl(options.cacheControl, this.options.defaultCacheControl),
1420
1601
  ContentDisposition: buildContentDisposition(
@@ -1450,11 +1631,7 @@ var StorageService = class {
1450
1631
  multipart: true
1451
1632
  });
1452
1633
  } catch (err) {
1453
- throw new StorageException(STORAGE_ERROR_CODES.STORAGE_MULTIPART_ABORTED, void 0, {
1454
- key: finalKey,
1455
- bucket,
1456
- awsMessage: err.message
1457
- });
1634
+ throw mapMultipartError(err, { key: finalKey, bucket });
1458
1635
  }
1459
1636
  }
1460
1637
  /** Converts a `Uint8Array` body to a `Buffer` for SDK safety; passes others through. */
@@ -1510,32 +1687,11 @@ var StorageService = class {
1510
1687
  Delimiter: options.delimiter
1511
1688
  })
1512
1689
  );
1513
- return this.toListResult(response);
1690
+ return toListResult(response, (key) => this.keyResolver.stripPrefix(key));
1514
1691
  } catch (err) {
1515
1692
  throw mapAwsError(err, { bucket, prefix, op: "list" });
1516
1693
  }
1517
1694
  }
1518
- /** Maps a `ListObjectsV2` response onto the public `ListResult` shape. */
1519
- toListResult(response) {
1520
- const objects = (response.Contents ?? []).map((obj) => this.toListedObject(obj));
1521
- const commonPrefixes = (response.CommonPrefixes ?? []).map((cp) => cp.Prefix ?? "").filter((cp) => cp.length > 0).map((cp) => this.keyResolver.stripPrefix(cp));
1522
- return {
1523
- objects,
1524
- commonPrefixes,
1525
- isTruncated: response.IsTruncated ?? false,
1526
- ...response.NextContinuationToken !== void 0 ? { nextContinuationToken: response.NextContinuationToken } : {}
1527
- };
1528
- }
1529
- /** Maps one `Contents` entry onto `ListedObject`, stripping the global prefix. */
1530
- toListedObject(obj) {
1531
- return {
1532
- key: this.keyResolver.stripPrefix(obj.Key ?? ""),
1533
- size: obj.Size ?? 0,
1534
- etag: obj.ETag ?? "",
1535
- lastModified: obj.LastModified ?? /* @__PURE__ */ new Date(0),
1536
- ...obj.StorageClass !== void 0 ? { storageClass: obj.StorageClass } : {}
1537
- };
1538
- }
1539
1695
  /**
1540
1696
  * Server-side copy of an object (no bytes flow through the app). Supports both
1541
1697
  * same-bucket and cross-bucket copies and preserves the source metadata.
@@ -1622,7 +1778,7 @@ var StorageService = class {
1622
1778
  }
1623
1779
  }
1624
1780
  } catch (err) {
1625
- const message = err instanceof Error ? err.message : String(err);
1781
+ const message = describeError(err);
1626
1782
  for (const key of chunk) {
1627
1783
  failed.push({ key: this.keyResolver.stripPrefix(key), error: message });
1628
1784
  }
@@ -26,7 +26,10 @@ var STORAGE_ERROR_CODES = {
26
26
  STORAGE_LIFECYCLE_UNSUPPORTED: "STORAGE_LIFECYCLE_UNSUPPORTED",
27
27
  STORAGE_LIFECYCLE_REJECTED: "STORAGE_LIFECYCLE_REJECTED",
28
28
  STORAGE_NOT_MODIFIED: "STORAGE_NOT_MODIFIED",
29
- STORAGE_PRECONDITION_FAILED: "STORAGE_PRECONDITION_FAILED"
29
+ STORAGE_PRECONDITION_FAILED: "STORAGE_PRECONDITION_FAILED",
30
+ STORAGE_BUCKET_NOT_FOUND: "STORAGE_BUCKET_NOT_FOUND",
31
+ STORAGE_BUCKET_ACCESS_DENIED: "STORAGE_BUCKET_ACCESS_DENIED",
32
+ STORAGE_BUCKET_REGION_MISMATCH: "STORAGE_BUCKET_REGION_MISMATCH"
30
33
  };
31
34
 
32
35
  // src/shared/constants/mime-types.constants.ts
@@ -95,6 +95,9 @@ declare const STORAGE_ERROR_CODES: {
95
95
  readonly STORAGE_LIFECYCLE_REJECTED: "STORAGE_LIFECYCLE_REJECTED";
96
96
  readonly STORAGE_NOT_MODIFIED: "STORAGE_NOT_MODIFIED";
97
97
  readonly STORAGE_PRECONDITION_FAILED: "STORAGE_PRECONDITION_FAILED";
98
+ readonly STORAGE_BUCKET_NOT_FOUND: "STORAGE_BUCKET_NOT_FOUND";
99
+ readonly STORAGE_BUCKET_ACCESS_DENIED: "STORAGE_BUCKET_ACCESS_DENIED";
100
+ readonly STORAGE_BUCKET_REGION_MISMATCH: "STORAGE_BUCKET_REGION_MISMATCH";
98
101
  };
99
102
  /** Union of every stable storage error code. */
100
103
  type StorageErrorCode = (typeof STORAGE_ERROR_CODES)[keyof typeof STORAGE_ERROR_CODES];
@@ -95,6 +95,9 @@ declare const STORAGE_ERROR_CODES: {
95
95
  readonly STORAGE_LIFECYCLE_REJECTED: "STORAGE_LIFECYCLE_REJECTED";
96
96
  readonly STORAGE_NOT_MODIFIED: "STORAGE_NOT_MODIFIED";
97
97
  readonly STORAGE_PRECONDITION_FAILED: "STORAGE_PRECONDITION_FAILED";
98
+ readonly STORAGE_BUCKET_NOT_FOUND: "STORAGE_BUCKET_NOT_FOUND";
99
+ readonly STORAGE_BUCKET_ACCESS_DENIED: "STORAGE_BUCKET_ACCESS_DENIED";
100
+ readonly STORAGE_BUCKET_REGION_MISMATCH: "STORAGE_BUCKET_REGION_MISMATCH";
98
101
  };
99
102
  /** Union of every stable storage error code. */
100
103
  type StorageErrorCode = (typeof STORAGE_ERROR_CODES)[keyof typeof STORAGE_ERROR_CODES];
@@ -24,7 +24,10 @@ var STORAGE_ERROR_CODES = {
24
24
  STORAGE_LIFECYCLE_UNSUPPORTED: "STORAGE_LIFECYCLE_UNSUPPORTED",
25
25
  STORAGE_LIFECYCLE_REJECTED: "STORAGE_LIFECYCLE_REJECTED",
26
26
  STORAGE_NOT_MODIFIED: "STORAGE_NOT_MODIFIED",
27
- STORAGE_PRECONDITION_FAILED: "STORAGE_PRECONDITION_FAILED"
27
+ STORAGE_PRECONDITION_FAILED: "STORAGE_PRECONDITION_FAILED",
28
+ STORAGE_BUCKET_NOT_FOUND: "STORAGE_BUCKET_NOT_FOUND",
29
+ STORAGE_BUCKET_ACCESS_DENIED: "STORAGE_BUCKET_ACCESS_DENIED",
30
+ STORAGE_BUCKET_REGION_MISMATCH: "STORAGE_BUCKET_REGION_MISMATCH"
28
31
  };
29
32
 
30
33
  // src/shared/constants/mime-types.constants.ts
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-storage",
3
- "version": "1.1.2",
3
+ "version": "1.1.4",
4
4
  "description": "Provider-agnostic S3-compatible object storage for NestJS. Works with AWS S3, DigitalOcean Spaces, Cloudflare R2, Backblaze B2, MinIO, Wasabi.",
5
5
  "author": "Bymax One <support@bymax.one>",
6
6
  "license": "MIT",