@bymax-one/nest-storage 1.1.15 → 1.1.16

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,30 @@ note on each entry is the compatibility contract — read it, not the number.
13
13
 
14
14
  ## [Unreleased]
15
15
 
16
+ ## [1.1.16] - 2026-11-17
17
+
18
+ ### Changed
19
+
20
+ - **The scanner's free-form `details` no longer reaches a client.** `STORAGE_SCAN_INFECTED` and
21
+ `STORAGE_SCAN_INCONCLUSIVE` copied the `details` an `IFileScanner` returned into the body of the error,
22
+ and that text is the scanner's own: an engine message, a quarantine path, an internal address. The body
23
+ now carries the `engine` and, for an infected object, the `threat` name, and nothing else the scanner
24
+ wrote. The `details` go to the warning log, written as one escaped, truncated token; a
25
+ rejected inconclusive result is now logged too.
26
+
27
+ **Apply to a derived backend:** a host that read `details.details` from either error must read the log
28
+ line instead, or put what it needs in `threat` or `engine`. The other fields of the body are unchanged.
29
+ A rejection whose `details` could not be serialised (a circular object, a `BigInt`, a `toJSON` that
30
+ throws) used to fail while the error body was written, and the host answered 500; it is now the typed
31
+ 422.
32
+
33
+ - **The `abortSignal` option documentation states what a body read ends with.** It said a `download()` stream
34
+ errors with the raw `AbortError` when `bodyIdleTimeoutMs` is `0` and left out `downloadBuffer()`. It now says
35
+ that `downloadBuffer()` and a guarded `download()` stream fail `STORAGE_REQUEST_ABORTED`, and that with the
36
+ guard off a `download()` stream is the SDK's own and errors with the SDK's error. The behaviour is unchanged.
37
+
38
+ **Apply to a derived backend:** nothing.
39
+
16
40
  ## [1.1.15] - 2026-11-17
17
41
 
18
42
  ### Fixed
@@ -883,4 +907,5 @@ have regressed from. They are kept because the reasoning is worth having.
883
907
  [1.1.13]: https://github.com/bymaxone/nest-storage/compare/v1.1.12...v1.1.13
884
908
  [1.1.14]: https://github.com/bymaxone/nest-storage/compare/v1.1.13...v1.1.14
885
909
  [1.1.15]: https://github.com/bymaxone/nest-storage/compare/v1.1.14...v1.1.15
886
- [Unreleased]: https://github.com/bymaxone/nest-storage/compare/v1.1.15...HEAD
910
+ [1.1.16]: https://github.com/bymaxone/nest-storage/compare/v1.1.15...v1.1.16
911
+ [Unreleased]: https://github.com/bymaxone/nest-storage/compare/v1.1.16...HEAD
package/README.md CHANGED
@@ -595,6 +595,11 @@ stream longer than the limit is refused with `STORAGE_VALIDATION_FAILED` as soon
595
595
  with no `maxSizeBytes` it is refused with a reason that says to set it or use `post-upload`. Buffer
596
596
  bodies are not affected, and `post-upload` hands the scanner the key only, no body.
597
597
 
598
+ **What a client is told.** `STORAGE_SCAN_INFECTED` carries `details.engine` and `details.threat`, and
599
+ `STORAGE_SCAN_INCONCLUSIVE` carries `details.engine`. The free-form `details` your scanner returns is the
600
+ scanner's own text, so it is written to the warning log (escaped and truncated) and never to the
601
+ body of the error.
602
+
598
603
  **A rejected object that could not be removed.** In `post-upload` mode the object is already stored
599
604
  when the scanner rejects it, so the library deletes it and rejects `upload()` with the verdict
600
605
  (`STORAGE_SCAN_INFECTED` or `STORAGE_SCAN_INCONCLUSIVE`). If that delete fails the verdict is still the
@@ -215,28 +215,7 @@ function assertTimerMs(options, name, min) {
215
215
  );
216
216
  }
217
217
  }
218
- function validateOptions(options) {
219
- if (!isObject(options)) {
220
- throw invalid("options object is required");
221
- }
222
- if (!isNonEmptyString(options.endpoint)) {
223
- throw invalid("options.endpoint must be a non-empty string");
224
- }
225
- for (const name of ["endpoint", "publicBaseUrl", "cdnBaseUrl"]) {
226
- const value = options[name];
227
- if (typeof value === "string" && urlCarriesCredentials(value)) {
228
- throw invalid(`options.${name} must not carry credentials; pass them in options.credentials`);
229
- }
230
- }
231
- if (!isNonEmptyString(options.region)) {
232
- throw invalid("options.region must be a non-empty string");
233
- }
234
- if (!isNonEmptyString(options.bucket)) {
235
- throw invalid("options.bucket must be a non-empty string");
236
- }
237
- if (!isObject(options.credentials)) {
238
- throw invalid("options.credentials is required");
239
- }
218
+ function assertLimitsAndEncryption(options) {
240
219
  const signedUrls = options.signedUrls;
241
220
  if (isObject(signedUrls) && typeof signedUrls.maxTtlSeconds === "number" && signedUrls.maxTtlSeconds <= 0) {
242
221
  throw invalid("signedUrls.maxTtlSeconds must be > 0");
@@ -261,6 +240,30 @@ function validateOptions(options) {
261
240
  }
262
241
  }
263
242
  }
243
+ function validateOptions(options) {
244
+ if (!isObject(options)) {
245
+ throw invalid("options object is required");
246
+ }
247
+ if (!isNonEmptyString(options.endpoint)) {
248
+ throw invalid("options.endpoint must be a non-empty string");
249
+ }
250
+ for (const name of ["endpoint", "publicBaseUrl", "cdnBaseUrl"]) {
251
+ const value = options[name];
252
+ if (typeof value === "string" && urlCarriesCredentials(value)) {
253
+ throw invalid(`options.${name} must not carry credentials; pass them in options.credentials`);
254
+ }
255
+ }
256
+ if (!isNonEmptyString(options.region)) {
257
+ throw invalid("options.region must be a non-empty string");
258
+ }
259
+ if (!isNonEmptyString(options.bucket)) {
260
+ throw invalid("options.bucket must be a non-empty string");
261
+ }
262
+ if (!isObject(options.credentials)) {
263
+ throw invalid("options.credentials is required");
264
+ }
265
+ assertLimitsAndEncryption(options);
266
+ }
264
267
 
265
268
  // src/server/utils/trim-trailing-slashes.ts
266
269
  var SLASH = "/";
@@ -306,6 +309,13 @@ function resolveSignedUrls(configured) {
306
309
  const merged = { ...DEFAULT_SIGNED_URLS, ...configured ?? {} };
307
310
  return { ...merged, maxTtlSeconds: Math.min(merged.maxTtlSeconds, MAX_SIGNED_URL_TTL_SECONDS) };
308
311
  }
312
+ function attachCredentials(resolved, credentials) {
313
+ Object.defineProperty(resolved, "credentials", {
314
+ get: () => credentials,
315
+ enumerable: false,
316
+ configurable: false
317
+ });
318
+ }
309
319
  function applyDefaults(options) {
310
320
  const hasCredentials = Boolean(options.credentials.accessKeyId) && Boolean(options.credentials.secretAccessKey);
311
321
  const publicBaseUrl = options.publicBaseUrl ?? `${trimTrailingSlashes(options.endpoint)}/${options.bucket}`;
@@ -336,11 +346,7 @@ function applyDefaults(options) {
336
346
  bodyIdleTimeoutMs: options.bodyIdleTimeoutMs ?? requestTimeoutMs,
337
347
  hasCredentials
338
348
  };
339
- Object.defineProperty(resolved, "credentials", {
340
- get: () => credentials,
341
- enumerable: false,
342
- configurable: false
343
- });
349
+ attachCredentials(resolved, credentials);
344
350
  return resolved;
345
351
  }
346
352
 
@@ -641,6 +647,31 @@ function awsCodeOf(err) {
641
647
  function isNoSuchBucket(err) {
642
648
  return awsCodeOf(err) === "NoSuchBucket";
643
649
  }
650
+ function mapAnsweredStatus(e, details) {
651
+ const status = e.$metadata?.httpStatusCode;
652
+ if (e.name === "NotFound" || status === 404) {
653
+ return new StorageException(
654
+ STORAGE_ERROR_CODES.STORAGE_OBJECT_NOT_FOUND,
655
+ common.HttpStatus.NOT_FOUND,
656
+ details
657
+ );
658
+ }
659
+ if (status === 304) {
660
+ return new StorageException(
661
+ STORAGE_ERROR_CODES.STORAGE_NOT_MODIFIED,
662
+ common.HttpStatus.NOT_MODIFIED,
663
+ details
664
+ );
665
+ }
666
+ if (status === 412) {
667
+ return new StorageException(
668
+ STORAGE_ERROR_CODES.STORAGE_PRECONDITION_FAILED,
669
+ common.HttpStatus.PRECONDITION_FAILED,
670
+ details
671
+ );
672
+ }
673
+ return void 0;
674
+ }
644
675
  function mapAwsError(err, context) {
645
676
  const e = err ?? {};
646
677
  const httpStatus = e.$metadata?.httpStatusCode;
@@ -661,27 +692,8 @@ function mapAwsError(err, context) {
661
692
  details
662
693
  );
663
694
  }
664
- if (e.name === "NotFound" || httpStatus === 404) {
665
- return new StorageException(
666
- STORAGE_ERROR_CODES.STORAGE_OBJECT_NOT_FOUND,
667
- common.HttpStatus.NOT_FOUND,
668
- details
669
- );
670
- }
671
- if (httpStatus === 304) {
672
- return new StorageException(
673
- STORAGE_ERROR_CODES.STORAGE_NOT_MODIFIED,
674
- common.HttpStatus.NOT_MODIFIED,
675
- details
676
- );
677
- }
678
- if (httpStatus === 412) {
679
- return new StorageException(
680
- STORAGE_ERROR_CODES.STORAGE_PRECONDITION_FAILED,
681
- common.HttpStatus.PRECONDITION_FAILED,
682
- details
683
- );
684
- }
695
+ const answered = mapAnsweredStatus(e, details);
696
+ if (answered) return answered;
685
697
  if (e.name === "TimeoutError") {
686
698
  logProviderFailure(err, context);
687
699
  return new StorageException(STORAGE_ERROR_CODES.STORAGE_TIMEOUT, void 0, details);
@@ -1216,6 +1228,21 @@ ValidationService = __decorateClass([
1216
1228
  __decorateParam(0, common.Inject(BYMAX_STORAGE_OPTIONS)),
1217
1229
  __decorateParam(1, common.Inject(BYMAX_STORAGE_UPLOAD_VALIDATORS))
1218
1230
  ], ValidationService);
1231
+ var UNSERIALISABLE = "[unserialisable]";
1232
+ var MAX_SCANNER_DETAILS_LENGTH = 300;
1233
+ function toJson(value) {
1234
+ return JSON.stringify(value);
1235
+ }
1236
+ function scannerDetailsForLog(details) {
1237
+ if (details === void 0) return "";
1238
+ let text;
1239
+ try {
1240
+ text = toJson(details) ?? UNSERIALISABLE;
1241
+ } catch {
1242
+ text = UNSERIALISABLE;
1243
+ }
1244
+ return ` details=${logValue(text.slice(0, MAX_SCANNER_DETAILS_LENGTH))}`;
1245
+ }
1219
1246
  var FileScannerService = class {
1220
1247
  constructor(options, scanner) {
1221
1248
  this.options = options;
@@ -1267,18 +1294,17 @@ var FileScannerService = class {
1267
1294
  }
1268
1295
  const result = await this.scanner.scan(input);
1269
1296
  if (result.status === "infected") {
1270
- this.logger.warn(`Infected file detected: key=${logValue(input.key)} engine=${logValue(result.engine)} threat=${logValue(result.threat ?? "unknown")}`);
1297
+ this.logger.warn(`Infected file detected: key=${logValue(input.key)} engine=${logValue(result.engine)} threat=${logValue(result.threat ?? "unknown")}${scannerDetailsForLog(result.details)}`);
1271
1298
  throw new StorageException(STORAGE_ERROR_CODES.STORAGE_SCAN_INFECTED, void 0, {
1272
1299
  engine: result.engine,
1273
- threat: result.threat,
1274
- details: result.details
1300
+ threat: result.threat
1275
1301
  });
1276
1302
  }
1277
1303
  if (result.status === "unknown") {
1278
1304
  if (this.options.scanner?.rejectOnUnknown) {
1305
+ this.logger.warn(`Inconclusive scan result rejected: key=${logValue(input.key)} engine=${logValue(result.engine)}${scannerDetailsForLog(result.details)}`);
1279
1306
  throw new StorageException(STORAGE_ERROR_CODES.STORAGE_SCAN_INCONCLUSIVE, void 0, {
1280
- engine: result.engine,
1281
- details: result.details
1307
+ engine: result.engine
1282
1308
  });
1283
1309
  }
1284
1310
  this.logger.warn(`Inconclusive scan result accepted: key=${logValue(input.key)} engine=${logValue(result.engine)}`);
@@ -1705,6 +1731,24 @@ function boundStreamSize(body, declaredSize, options) {
1705
1731
  }
1706
1732
  return withSizeLimit(body, limit, declaredSize === void 0 ? "max" : "declared");
1707
1733
  }
1734
+ async function bufferStreamForScan(body, finalKey, maxSizeBytes) {
1735
+ if (maxSizeBytes === void 0) {
1736
+ destroyStream(body);
1737
+ throw new StorageException(STORAGE_ERROR_CODES.STORAGE_VALIDATION_FAILED, void 0, {
1738
+ key: finalKey,
1739
+ reason: "Pre-upload scanning of a stream needs validation.maxSizeBytes to bound the buffer; set it or use scanner mode post-upload"
1740
+ });
1741
+ }
1742
+ const buffered = await readStreamUpTo(body, maxSizeBytes);
1743
+ if (buffered === void 0) {
1744
+ throw new StorageException(STORAGE_ERROR_CODES.STORAGE_VALIDATION_FAILED, void 0, {
1745
+ key: finalKey,
1746
+ maxSizeBytes,
1747
+ reason: "The stream is longer than validation.maxSizeBytes, so it cannot be scanned before upload"
1748
+ });
1749
+ }
1750
+ return buffered;
1751
+ }
1708
1752
 
1709
1753
  // src/server/utils/download-body.ts
1710
1754
  function guardDownloadBody(body, idleMs, context, signal) {
@@ -1899,7 +1943,8 @@ exports.StorageService = class StorageService {
1899
1943
  }
1900
1944
  const finalKey = this.keyResolver.normalize(options.key);
1901
1945
  const bucket = this.resolveBucket(options.bucket);
1902
- throwIfAborted(options.abortSignal, { key: finalKey, bucket, op: "upload" });
1946
+ const context = { key: finalKey, bucket, op: "upload" };
1947
+ throwIfAborted(options.abortSignal, context);
1903
1948
  if (options.idempotencyKey) {
1904
1949
  const cacheKey = this.idempotencyCache.computeKey(options.idempotencyKey, finalKey);
1905
1950
  const cached = this.idempotencyCache.get(cacheKey);
@@ -1909,7 +1954,25 @@ exports.StorageService = class StorageService {
1909
1954
  return { ...cached, fromIdempotencyCache: true };
1910
1955
  }
1911
1956
  }
1912
- const context = { key: finalKey, bucket, op: "upload" };
1957
+ const validatedOptions = await this.validateAndScan(options, finalKey, bucket, context);
1958
+ throwIfAborted(options.abortSignal, context);
1959
+ const strategy = pickUploadStrategy(
1960
+ validatedOptions.body,
1961
+ validatedOptions.size,
1962
+ this.options.multipart.thresholdBytes
1963
+ );
1964
+ const result = strategy === "multipart" ? await this.uploadMultipart(validatedOptions, finalKey, bucket) : await this.uploadSingleShot(validatedOptions, finalKey, bucket);
1965
+ const stored = { ...context, stored: true };
1966
+ await abortable(this.runPostUploadScan(finalKey, bucket, options), options.abortSignal, stored);
1967
+ this.rememberUpload(options, finalKey, result);
1968
+ return result;
1969
+ }
1970
+ /**
1971
+ * Validates the upload and runs the pre-upload scan, returning the options with the body to send.
1972
+ * Reading the body (a validator peeking at it, the scan buffering it) happens before any request, so
1973
+ * the signal is watched here: a silent stream must not hold the call.
1974
+ */
1975
+ async validateAndScan(options, finalKey, bucket, context) {
1913
1976
  const signal = options.abortSignal;
1914
1977
  const input = validationInput(options, finalKey);
1915
1978
  const validated = await abortable(this.validation.validate(input), signal, context);
@@ -1921,17 +1984,7 @@ exports.StorageService = class StorageService {
1921
1984
  const body = boundStreamSize(scanned, options.size, this.options);
1922
1985
  const validatedOptions = { ...options, body };
1923
1986
  await abortable(this.runPreUploadScan(body, finalKey, bucket, options), signal, context);
1924
- throwIfAborted(signal, context);
1925
- const strategy = pickUploadStrategy(
1926
- validatedOptions.body,
1927
- validatedOptions.size,
1928
- this.options.multipart.thresholdBytes
1929
- );
1930
- const result = strategy === "multipart" ? await this.uploadMultipart(validatedOptions, finalKey, bucket) : await this.uploadSingleShot(validatedOptions, finalKey, bucket);
1931
- const stored = { ...context, stored: true };
1932
- await abortable(this.runPostUploadScan(finalKey, bucket, options), signal, stored);
1933
- this.rememberUpload(options, finalKey, result);
1934
- return result;
1987
+ return validatedOptions;
1935
1988
  }
1936
1989
  /**
1937
1990
  * In pre-upload scan mode a stream body is read into one `Buffer`, so the scanner
@@ -1944,23 +1997,7 @@ exports.StorageService = class StorageService {
1944
1997
  if (!this.scanner.isEnabled() || this.scanner.getMode() !== "pre-upload" || isBufferLike(body)) {
1945
1998
  return body;
1946
1999
  }
1947
- const maxSizeBytes = this.options.validation?.maxSizeBytes;
1948
- if (maxSizeBytes === void 0) {
1949
- destroyStream(body);
1950
- throw new StorageException(STORAGE_ERROR_CODES.STORAGE_VALIDATION_FAILED, void 0, {
1951
- key: finalKey,
1952
- reason: "Pre-upload scanning of a stream needs validation.maxSizeBytes to bound the buffer; set it or use scanner mode post-upload"
1953
- });
1954
- }
1955
- const buffered = await readStreamUpTo(body, maxSizeBytes);
1956
- if (buffered === void 0) {
1957
- throw new StorageException(STORAGE_ERROR_CODES.STORAGE_VALIDATION_FAILED, void 0, {
1958
- key: finalKey,
1959
- maxSizeBytes,
1960
- reason: "The stream is longer than validation.maxSizeBytes, so it cannot be scanned before upload"
1961
- });
1962
- }
1963
- return buffered;
2000
+ return bufferStreamForScan(body, finalKey, this.options.validation?.maxSizeBytes);
1964
2001
  }
1965
2002
  /** Runs a pre-upload scan when configured; throws on infected. */
1966
2003
  async runPreUploadScan(body, finalKey, bucket, options) {
@@ -70,6 +70,7 @@ interface FileScanResult {
70
70
  engine: string;
71
71
  /** Threat name when `status === 'infected'`. */
72
72
  threat?: string;
73
+ /** Free-form scanner text. It is logged, escaped and cut at 300 characters, and is never put in an error body. */
73
74
  details?: Record<string, unknown>;
74
75
  }
75
76
 
@@ -380,10 +381,11 @@ interface DownloadOptions {
380
381
  /**
381
382
  * Ends the call when it aborts: the request is dropped and the call rejects
382
383
  * `STORAGE_REQUEST_ABORTED` with `details.reason` set to the signal's reason name. A signal that is
383
- * already aborted makes no request. A body stream already returned errors too: as
384
- * `STORAGE_REQUEST_ABORTED` while the idle guard is on (the default `bodyIdleTimeoutMs`), as the
385
- * raw `AbortError` when `bodyIdleTimeoutMs` is `0`. The library keeps no listener on the signal
386
- * after the call.
384
+ * already aborted makes no request. It also ends a body that is still being read, in
385
+ * `downloadBuffer()` and in a `download()` stream while the idle guard is on (the default
386
+ * `bodyIdleTimeoutMs`): both fail `STORAGE_REQUEST_ABORTED`. With `bodyIdleTimeoutMs` set to `0`,
387
+ * a `download()` stream is the SDK's own and errors with the SDK's error, which is not a
388
+ * `StorageException`. The library keeps no listener on the signal after the call.
387
389
  */
388
390
  abortSignal?: AbortSignal;
389
391
  }
@@ -805,6 +807,12 @@ declare class StorageService {
805
807
  upload(options: UploadOptions): Promise<UploadResult>;
806
808
  /** The upload itself; `upload()` destroys a stream body when this rejects. */
807
809
  private uploadOwningBody;
810
+ /**
811
+ * Validates the upload and runs the pre-upload scan, returning the options with the body to send.
812
+ * Reading the body (a validator peeking at it, the scan buffering it) happens before any request, so
813
+ * the signal is watched here: a silent stream must not hold the call.
814
+ */
815
+ private validateAndScan;
808
816
  /**
809
817
  * In pre-upload scan mode a stream body is read into one `Buffer`, so the scanner
810
818
  * and the upload see the same bytes; a stream is single-use, and one the scanner
@@ -70,6 +70,7 @@ interface FileScanResult {
70
70
  engine: string;
71
71
  /** Threat name when `status === 'infected'`. */
72
72
  threat?: string;
73
+ /** Free-form scanner text. It is logged, escaped and cut at 300 characters, and is never put in an error body. */
73
74
  details?: Record<string, unknown>;
74
75
  }
75
76
 
@@ -380,10 +381,11 @@ interface DownloadOptions {
380
381
  /**
381
382
  * Ends the call when it aborts: the request is dropped and the call rejects
382
383
  * `STORAGE_REQUEST_ABORTED` with `details.reason` set to the signal's reason name. A signal that is
383
- * already aborted makes no request. A body stream already returned errors too: as
384
- * `STORAGE_REQUEST_ABORTED` while the idle guard is on (the default `bodyIdleTimeoutMs`), as the
385
- * raw `AbortError` when `bodyIdleTimeoutMs` is `0`. The library keeps no listener on the signal
386
- * after the call.
384
+ * already aborted makes no request. It also ends a body that is still being read, in
385
+ * `downloadBuffer()` and in a `download()` stream while the idle guard is on (the default
386
+ * `bodyIdleTimeoutMs`): both fail `STORAGE_REQUEST_ABORTED`. With `bodyIdleTimeoutMs` set to `0`,
387
+ * a `download()` stream is the SDK's own and errors with the SDK's error, which is not a
388
+ * `StorageException`. The library keeps no listener on the signal after the call.
387
389
  */
388
390
  abortSignal?: AbortSignal;
389
391
  }
@@ -805,6 +807,12 @@ declare class StorageService {
805
807
  upload(options: UploadOptions): Promise<UploadResult>;
806
808
  /** The upload itself; `upload()` destroys a stream body when this rejects. */
807
809
  private uploadOwningBody;
810
+ /**
811
+ * Validates the upload and runs the pre-upload scan, returning the options with the body to send.
812
+ * Reading the body (a validator peeking at it, the scan buffering it) happens before any request, so
813
+ * the signal is watched here: a silent stream must not hold the call.
814
+ */
815
+ private validateAndScan;
808
816
  /**
809
817
  * In pre-upload scan mode a stream body is read into one `Buffer`, so the scanner
810
818
  * and the upload see the same bytes; a stream is single-use, and one the scanner
@@ -213,28 +213,7 @@ function assertTimerMs(options, name, min) {
213
213
  );
214
214
  }
215
215
  }
216
- function validateOptions(options) {
217
- if (!isObject(options)) {
218
- throw invalid("options object is required");
219
- }
220
- if (!isNonEmptyString(options.endpoint)) {
221
- throw invalid("options.endpoint must be a non-empty string");
222
- }
223
- for (const name of ["endpoint", "publicBaseUrl", "cdnBaseUrl"]) {
224
- const value = options[name];
225
- if (typeof value === "string" && urlCarriesCredentials(value)) {
226
- throw invalid(`options.${name} must not carry credentials; pass them in options.credentials`);
227
- }
228
- }
229
- if (!isNonEmptyString(options.region)) {
230
- throw invalid("options.region must be a non-empty string");
231
- }
232
- if (!isNonEmptyString(options.bucket)) {
233
- throw invalid("options.bucket must be a non-empty string");
234
- }
235
- if (!isObject(options.credentials)) {
236
- throw invalid("options.credentials is required");
237
- }
216
+ function assertLimitsAndEncryption(options) {
238
217
  const signedUrls = options.signedUrls;
239
218
  if (isObject(signedUrls) && typeof signedUrls.maxTtlSeconds === "number" && signedUrls.maxTtlSeconds <= 0) {
240
219
  throw invalid("signedUrls.maxTtlSeconds must be > 0");
@@ -259,6 +238,30 @@ function validateOptions(options) {
259
238
  }
260
239
  }
261
240
  }
241
+ function validateOptions(options) {
242
+ if (!isObject(options)) {
243
+ throw invalid("options object is required");
244
+ }
245
+ if (!isNonEmptyString(options.endpoint)) {
246
+ throw invalid("options.endpoint must be a non-empty string");
247
+ }
248
+ for (const name of ["endpoint", "publicBaseUrl", "cdnBaseUrl"]) {
249
+ const value = options[name];
250
+ if (typeof value === "string" && urlCarriesCredentials(value)) {
251
+ throw invalid(`options.${name} must not carry credentials; pass them in options.credentials`);
252
+ }
253
+ }
254
+ if (!isNonEmptyString(options.region)) {
255
+ throw invalid("options.region must be a non-empty string");
256
+ }
257
+ if (!isNonEmptyString(options.bucket)) {
258
+ throw invalid("options.bucket must be a non-empty string");
259
+ }
260
+ if (!isObject(options.credentials)) {
261
+ throw invalid("options.credentials is required");
262
+ }
263
+ assertLimitsAndEncryption(options);
264
+ }
262
265
 
263
266
  // src/server/utils/trim-trailing-slashes.ts
264
267
  var SLASH = "/";
@@ -304,6 +307,13 @@ function resolveSignedUrls(configured) {
304
307
  const merged = { ...DEFAULT_SIGNED_URLS, ...configured ?? {} };
305
308
  return { ...merged, maxTtlSeconds: Math.min(merged.maxTtlSeconds, MAX_SIGNED_URL_TTL_SECONDS) };
306
309
  }
310
+ function attachCredentials(resolved, credentials) {
311
+ Object.defineProperty(resolved, "credentials", {
312
+ get: () => credentials,
313
+ enumerable: false,
314
+ configurable: false
315
+ });
316
+ }
307
317
  function applyDefaults(options) {
308
318
  const hasCredentials = Boolean(options.credentials.accessKeyId) && Boolean(options.credentials.secretAccessKey);
309
319
  const publicBaseUrl = options.publicBaseUrl ?? `${trimTrailingSlashes(options.endpoint)}/${options.bucket}`;
@@ -334,11 +344,7 @@ function applyDefaults(options) {
334
344
  bodyIdleTimeoutMs: options.bodyIdleTimeoutMs ?? requestTimeoutMs,
335
345
  hasCredentials
336
346
  };
337
- Object.defineProperty(resolved, "credentials", {
338
- get: () => credentials,
339
- enumerable: false,
340
- configurable: false
341
- });
347
+ attachCredentials(resolved, credentials);
342
348
  return resolved;
343
349
  }
344
350
 
@@ -639,6 +645,31 @@ function awsCodeOf(err) {
639
645
  function isNoSuchBucket(err) {
640
646
  return awsCodeOf(err) === "NoSuchBucket";
641
647
  }
648
+ function mapAnsweredStatus(e, details) {
649
+ const status = e.$metadata?.httpStatusCode;
650
+ if (e.name === "NotFound" || status === 404) {
651
+ return new StorageException(
652
+ STORAGE_ERROR_CODES.STORAGE_OBJECT_NOT_FOUND,
653
+ HttpStatus.NOT_FOUND,
654
+ details
655
+ );
656
+ }
657
+ if (status === 304) {
658
+ return new StorageException(
659
+ STORAGE_ERROR_CODES.STORAGE_NOT_MODIFIED,
660
+ HttpStatus.NOT_MODIFIED,
661
+ details
662
+ );
663
+ }
664
+ if (status === 412) {
665
+ return new StorageException(
666
+ STORAGE_ERROR_CODES.STORAGE_PRECONDITION_FAILED,
667
+ HttpStatus.PRECONDITION_FAILED,
668
+ details
669
+ );
670
+ }
671
+ return void 0;
672
+ }
642
673
  function mapAwsError(err, context) {
643
674
  const e = err ?? {};
644
675
  const httpStatus = e.$metadata?.httpStatusCode;
@@ -659,27 +690,8 @@ function mapAwsError(err, context) {
659
690
  details
660
691
  );
661
692
  }
662
- if (e.name === "NotFound" || httpStatus === 404) {
663
- return new StorageException(
664
- STORAGE_ERROR_CODES.STORAGE_OBJECT_NOT_FOUND,
665
- HttpStatus.NOT_FOUND,
666
- details
667
- );
668
- }
669
- if (httpStatus === 304) {
670
- return new StorageException(
671
- STORAGE_ERROR_CODES.STORAGE_NOT_MODIFIED,
672
- HttpStatus.NOT_MODIFIED,
673
- details
674
- );
675
- }
676
- if (httpStatus === 412) {
677
- return new StorageException(
678
- STORAGE_ERROR_CODES.STORAGE_PRECONDITION_FAILED,
679
- HttpStatus.PRECONDITION_FAILED,
680
- details
681
- );
682
- }
693
+ const answered = mapAnsweredStatus(e, details);
694
+ if (answered) return answered;
683
695
  if (e.name === "TimeoutError") {
684
696
  logProviderFailure(err, context);
685
697
  return new StorageException(STORAGE_ERROR_CODES.STORAGE_TIMEOUT, void 0, details);
@@ -1214,6 +1226,21 @@ ValidationService = __decorateClass([
1214
1226
  __decorateParam(0, Inject(BYMAX_STORAGE_OPTIONS)),
1215
1227
  __decorateParam(1, Inject(BYMAX_STORAGE_UPLOAD_VALIDATORS))
1216
1228
  ], ValidationService);
1229
+ var UNSERIALISABLE = "[unserialisable]";
1230
+ var MAX_SCANNER_DETAILS_LENGTH = 300;
1231
+ function toJson(value) {
1232
+ return JSON.stringify(value);
1233
+ }
1234
+ function scannerDetailsForLog(details) {
1235
+ if (details === void 0) return "";
1236
+ let text;
1237
+ try {
1238
+ text = toJson(details) ?? UNSERIALISABLE;
1239
+ } catch {
1240
+ text = UNSERIALISABLE;
1241
+ }
1242
+ return ` details=${logValue(text.slice(0, MAX_SCANNER_DETAILS_LENGTH))}`;
1243
+ }
1217
1244
  var FileScannerService = class {
1218
1245
  constructor(options, scanner) {
1219
1246
  this.options = options;
@@ -1265,18 +1292,17 @@ var FileScannerService = class {
1265
1292
  }
1266
1293
  const result = await this.scanner.scan(input);
1267
1294
  if (result.status === "infected") {
1268
- this.logger.warn(`Infected file detected: key=${logValue(input.key)} engine=${logValue(result.engine)} threat=${logValue(result.threat ?? "unknown")}`);
1295
+ this.logger.warn(`Infected file detected: key=${logValue(input.key)} engine=${logValue(result.engine)} threat=${logValue(result.threat ?? "unknown")}${scannerDetailsForLog(result.details)}`);
1269
1296
  throw new StorageException(STORAGE_ERROR_CODES.STORAGE_SCAN_INFECTED, void 0, {
1270
1297
  engine: result.engine,
1271
- threat: result.threat,
1272
- details: result.details
1298
+ threat: result.threat
1273
1299
  });
1274
1300
  }
1275
1301
  if (result.status === "unknown") {
1276
1302
  if (this.options.scanner?.rejectOnUnknown) {
1303
+ this.logger.warn(`Inconclusive scan result rejected: key=${logValue(input.key)} engine=${logValue(result.engine)}${scannerDetailsForLog(result.details)}`);
1277
1304
  throw new StorageException(STORAGE_ERROR_CODES.STORAGE_SCAN_INCONCLUSIVE, void 0, {
1278
- engine: result.engine,
1279
- details: result.details
1305
+ engine: result.engine
1280
1306
  });
1281
1307
  }
1282
1308
  this.logger.warn(`Inconclusive scan result accepted: key=${logValue(input.key)} engine=${logValue(result.engine)}`);
@@ -1703,6 +1729,24 @@ function boundStreamSize(body, declaredSize, options) {
1703
1729
  }
1704
1730
  return withSizeLimit(body, limit, declaredSize === void 0 ? "max" : "declared");
1705
1731
  }
1732
+ async function bufferStreamForScan(body, finalKey, maxSizeBytes) {
1733
+ if (maxSizeBytes === void 0) {
1734
+ destroyStream(body);
1735
+ throw new StorageException(STORAGE_ERROR_CODES.STORAGE_VALIDATION_FAILED, void 0, {
1736
+ key: finalKey,
1737
+ reason: "Pre-upload scanning of a stream needs validation.maxSizeBytes to bound the buffer; set it or use scanner mode post-upload"
1738
+ });
1739
+ }
1740
+ const buffered = await readStreamUpTo(body, maxSizeBytes);
1741
+ if (buffered === void 0) {
1742
+ throw new StorageException(STORAGE_ERROR_CODES.STORAGE_VALIDATION_FAILED, void 0, {
1743
+ key: finalKey,
1744
+ maxSizeBytes,
1745
+ reason: "The stream is longer than validation.maxSizeBytes, so it cannot be scanned before upload"
1746
+ });
1747
+ }
1748
+ return buffered;
1749
+ }
1706
1750
 
1707
1751
  // src/server/utils/download-body.ts
1708
1752
  function guardDownloadBody(body, idleMs, context, signal) {
@@ -1897,7 +1941,8 @@ var StorageService = class {
1897
1941
  }
1898
1942
  const finalKey = this.keyResolver.normalize(options.key);
1899
1943
  const bucket = this.resolveBucket(options.bucket);
1900
- throwIfAborted(options.abortSignal, { key: finalKey, bucket, op: "upload" });
1944
+ const context = { key: finalKey, bucket, op: "upload" };
1945
+ throwIfAborted(options.abortSignal, context);
1901
1946
  if (options.idempotencyKey) {
1902
1947
  const cacheKey = this.idempotencyCache.computeKey(options.idempotencyKey, finalKey);
1903
1948
  const cached = this.idempotencyCache.get(cacheKey);
@@ -1907,7 +1952,25 @@ var StorageService = class {
1907
1952
  return { ...cached, fromIdempotencyCache: true };
1908
1953
  }
1909
1954
  }
1910
- const context = { key: finalKey, bucket, op: "upload" };
1955
+ const validatedOptions = await this.validateAndScan(options, finalKey, bucket, context);
1956
+ throwIfAborted(options.abortSignal, context);
1957
+ const strategy = pickUploadStrategy(
1958
+ validatedOptions.body,
1959
+ validatedOptions.size,
1960
+ this.options.multipart.thresholdBytes
1961
+ );
1962
+ const result = strategy === "multipart" ? await this.uploadMultipart(validatedOptions, finalKey, bucket) : await this.uploadSingleShot(validatedOptions, finalKey, bucket);
1963
+ const stored = { ...context, stored: true };
1964
+ await abortable(this.runPostUploadScan(finalKey, bucket, options), options.abortSignal, stored);
1965
+ this.rememberUpload(options, finalKey, result);
1966
+ return result;
1967
+ }
1968
+ /**
1969
+ * Validates the upload and runs the pre-upload scan, returning the options with the body to send.
1970
+ * Reading the body (a validator peeking at it, the scan buffering it) happens before any request, so
1971
+ * the signal is watched here: a silent stream must not hold the call.
1972
+ */
1973
+ async validateAndScan(options, finalKey, bucket, context) {
1911
1974
  const signal = options.abortSignal;
1912
1975
  const input = validationInput(options, finalKey);
1913
1976
  const validated = await abortable(this.validation.validate(input), signal, context);
@@ -1919,17 +1982,7 @@ var StorageService = class {
1919
1982
  const body = boundStreamSize(scanned, options.size, this.options);
1920
1983
  const validatedOptions = { ...options, body };
1921
1984
  await abortable(this.runPreUploadScan(body, finalKey, bucket, options), signal, context);
1922
- throwIfAborted(signal, context);
1923
- const strategy = pickUploadStrategy(
1924
- validatedOptions.body,
1925
- validatedOptions.size,
1926
- this.options.multipart.thresholdBytes
1927
- );
1928
- const result = strategy === "multipart" ? await this.uploadMultipart(validatedOptions, finalKey, bucket) : await this.uploadSingleShot(validatedOptions, finalKey, bucket);
1929
- const stored = { ...context, stored: true };
1930
- await abortable(this.runPostUploadScan(finalKey, bucket, options), signal, stored);
1931
- this.rememberUpload(options, finalKey, result);
1932
- return result;
1985
+ return validatedOptions;
1933
1986
  }
1934
1987
  /**
1935
1988
  * In pre-upload scan mode a stream body is read into one `Buffer`, so the scanner
@@ -1942,23 +1995,7 @@ var StorageService = class {
1942
1995
  if (!this.scanner.isEnabled() || this.scanner.getMode() !== "pre-upload" || isBufferLike(body)) {
1943
1996
  return body;
1944
1997
  }
1945
- const maxSizeBytes = this.options.validation?.maxSizeBytes;
1946
- if (maxSizeBytes === void 0) {
1947
- destroyStream(body);
1948
- throw new StorageException(STORAGE_ERROR_CODES.STORAGE_VALIDATION_FAILED, void 0, {
1949
- key: finalKey,
1950
- reason: "Pre-upload scanning of a stream needs validation.maxSizeBytes to bound the buffer; set it or use scanner mode post-upload"
1951
- });
1952
- }
1953
- const buffered = await readStreamUpTo(body, maxSizeBytes);
1954
- if (buffered === void 0) {
1955
- throw new StorageException(STORAGE_ERROR_CODES.STORAGE_VALIDATION_FAILED, void 0, {
1956
- key: finalKey,
1957
- maxSizeBytes,
1958
- reason: "The stream is longer than validation.maxSizeBytes, so it cannot be scanned before upload"
1959
- });
1960
- }
1961
- return buffered;
1998
+ return bufferStreamForScan(body, finalKey, this.options.validation?.maxSizeBytes);
1962
1999
  }
1963
2000
  /** Runs a pre-upload scan when configured; throws on infected. */
1964
2001
  async runPreUploadScan(body, finalKey, bucket, options) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bymax-one/nest-storage",
3
- "version": "1.1.15",
3
+ "version": "1.1.16",
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",
@@ -49,6 +49,8 @@
49
49
  "check:exports": "attw --pack . --profile strict",
50
50
  "check:mutants": "node scripts/check-mutation-directives.mjs",
51
51
  "check:file-length": "node scripts/check-file-length.mjs",
52
+ "check:spec-headers": "node scripts/check-spec-headers.mjs",
53
+ "check:function-length": "node scripts/check-function-length.mjs",
52
54
  "check:published": "node scripts/check-published-surface.mjs",
53
55
  "check:runtime": "node scripts/check-consumer-runtime.mjs",
54
56
  "clean": "rm -rf dist coverage",