@bymax-one/nest-storage 1.1.1 → 1.1.2

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.
@@ -1,5 +1,5 @@
1
1
  import { HttpStatus, Injectable, Inject, Global, Module, Logger, HttpException } from '@nestjs/common';
2
- import { S3Client, HeadObjectCommand, GetObjectCommand, DeleteObjectCommand, PutObjectCommand, ListObjectsV2Command, CopyObjectCommand, DeleteObjectsCommand, CreateMultipartUploadCommand, UploadPartCommand, CompleteMultipartUploadCommand } from '@aws-sdk/client-s3';
2
+ import { S3Client, GetBucketLifecycleConfigurationCommand, DeleteBucketLifecycleCommand, PutBucketLifecycleConfigurationCommand, HeadObjectCommand, GetObjectCommand, DeleteObjectCommand, PutObjectCommand, ListObjectsV2Command, CopyObjectCommand, DeleteObjectsCommand, CreateMultipartUploadCommand, UploadPartCommand, CompleteMultipartUploadCommand } from '@aws-sdk/client-s3';
3
3
  import { Upload } from '@aws-sdk/lib-storage';
4
4
  import { PassThrough } from 'stream';
5
5
  import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
@@ -36,12 +36,19 @@ var STORAGE_ERROR_CODES = {
36
36
  STORAGE_OBJECT_NOT_FOUND: "STORAGE_OBJECT_NOT_FOUND",
37
37
  STORAGE_PROVIDER_ERROR: "STORAGE_PROVIDER_ERROR",
38
38
  STORAGE_SIGNED_URL_TTL_INVALID: "STORAGE_SIGNED_URL_TTL_INVALID",
39
+ // Reserved: kept so the code keeps its place in this frozen contract. Nothing throws it today;
40
+ // a `multipart.partSizeBytes` under the S3 minimum fails at init as STORAGE_INVALID_CONFIG.
39
41
  STORAGE_PART_TOO_SMALL: "STORAGE_PART_TOO_SMALL",
40
42
  STORAGE_INVALID_PART_COUNT: "STORAGE_INVALID_PART_COUNT",
41
43
  STORAGE_BUCKET_UNDEFINED: "STORAGE_BUCKET_UNDEFINED",
42
44
  STORAGE_MULTIPART_ABORTED: "STORAGE_MULTIPART_ABORTED",
43
45
  STORAGE_INVALID_CONFIG: "STORAGE_INVALID_CONFIG",
44
- STORAGE_TIMEOUT: "STORAGE_TIMEOUT"
46
+ STORAGE_TIMEOUT: "STORAGE_TIMEOUT",
47
+ STORAGE_LIFECYCLE_RULE_INVALID: "STORAGE_LIFECYCLE_RULE_INVALID",
48
+ STORAGE_LIFECYCLE_UNSUPPORTED: "STORAGE_LIFECYCLE_UNSUPPORTED",
49
+ STORAGE_LIFECYCLE_REJECTED: "STORAGE_LIFECYCLE_REJECTED",
50
+ STORAGE_NOT_MODIFIED: "STORAGE_NOT_MODIFIED",
51
+ STORAGE_PRECONDITION_FAILED: "STORAGE_PRECONDITION_FAILED"
45
52
  };
46
53
 
47
54
  // src/server/errors/storage-error-messages.ts
@@ -59,11 +66,16 @@ var STORAGE_ERROR_MESSAGES = {
59
66
  [STORAGE_ERROR_CODES.STORAGE_PROVIDER_ERROR]: "Storage provider returned an error",
60
67
  [STORAGE_ERROR_CODES.STORAGE_SIGNED_URL_TTL_INVALID]: "Signed URL TTL is invalid",
61
68
  [STORAGE_ERROR_CODES.STORAGE_PART_TOO_SMALL]: "Multipart part size is below the 5 MB minimum",
62
- [STORAGE_ERROR_CODES.STORAGE_INVALID_PART_COUNT]: "Multipart part count is invalid (must be a positive integer)",
69
+ [STORAGE_ERROR_CODES.STORAGE_INVALID_PART_COUNT]: "Multipart part count is invalid (must be an integer from 1 to 10000)",
63
70
  [STORAGE_ERROR_CODES.STORAGE_BUCKET_UNDEFINED]: "Bucket is undefined (no default configured and none provided per call)",
64
71
  [STORAGE_ERROR_CODES.STORAGE_MULTIPART_ABORTED]: "Multipart upload was aborted",
65
72
  [STORAGE_ERROR_CODES.STORAGE_INVALID_CONFIG]: "Module configuration is invalid",
66
- [STORAGE_ERROR_CODES.STORAGE_TIMEOUT]: "Storage request timed out"
73
+ [STORAGE_ERROR_CODES.STORAGE_TIMEOUT]: "Storage request timed out",
74
+ [STORAGE_ERROR_CODES.STORAGE_LIFECYCLE_RULE_INVALID]: "Lifecycle rule input is invalid",
75
+ [STORAGE_ERROR_CODES.STORAGE_LIFECYCLE_UNSUPPORTED]: "The storage provider does not support bucket lifecycle configuration",
76
+ [STORAGE_ERROR_CODES.STORAGE_LIFECYCLE_REJECTED]: "The storage provider rejected the lifecycle configuration",
77
+ [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"
67
79
  };
68
80
  var STORAGE_ERROR_STATUS = {
69
81
  [STORAGE_ERROR_CODES.STORAGE_NOT_CONFIGURED]: HttpStatus.SERVICE_UNAVAILABLE,
@@ -83,7 +95,12 @@ var STORAGE_ERROR_STATUS = {
83
95
  [STORAGE_ERROR_CODES.STORAGE_BUCKET_UNDEFINED]: HttpStatus.BAD_REQUEST,
84
96
  [STORAGE_ERROR_CODES.STORAGE_MULTIPART_ABORTED]: HttpStatus.INTERNAL_SERVER_ERROR,
85
97
  [STORAGE_ERROR_CODES.STORAGE_INVALID_CONFIG]: HttpStatus.INTERNAL_SERVER_ERROR,
86
- [STORAGE_ERROR_CODES.STORAGE_TIMEOUT]: HttpStatus.GATEWAY_TIMEOUT
98
+ [STORAGE_ERROR_CODES.STORAGE_TIMEOUT]: HttpStatus.GATEWAY_TIMEOUT,
99
+ [STORAGE_ERROR_CODES.STORAGE_LIFECYCLE_RULE_INVALID]: HttpStatus.BAD_REQUEST,
100
+ [STORAGE_ERROR_CODES.STORAGE_LIFECYCLE_UNSUPPORTED]: HttpStatus.NOT_IMPLEMENTED,
101
+ [STORAGE_ERROR_CODES.STORAGE_LIFECYCLE_REJECTED]: HttpStatus.UNPROCESSABLE_ENTITY,
102
+ [STORAGE_ERROR_CODES.STORAGE_NOT_MODIFIED]: HttpStatus.NOT_MODIFIED,
103
+ [STORAGE_ERROR_CODES.STORAGE_PRECONDITION_FAILED]: HttpStatus.PRECONDITION_FAILED
87
104
  };
88
105
 
89
106
  // src/server/errors/storage-exception.ts
@@ -186,6 +203,10 @@ var DEFAULT_IDEMPOTENCY_CACHE_MAX_ENTRIES = 1e3;
186
203
  var DEFAULT_IDEMPOTENCY_CACHE_TTL_MS = 864e5;
187
204
 
188
205
  // src/server/config/apply-defaults.ts
206
+ function resolveSignedUrls(configured) {
207
+ const merged = { ...DEFAULT_SIGNED_URLS, ...configured ?? {} };
208
+ return { ...merged, maxTtlSeconds: Math.min(merged.maxTtlSeconds, MAX_SIGNED_URL_TTL_SECONDS) };
209
+ }
189
210
  function applyDefaults(options) {
190
211
  const hasCredentials = Boolean(options.credentials.accessKeyId) && Boolean(options.credentials.secretAccessKey);
191
212
  const publicBaseUrl = options.publicBaseUrl ?? `${trimTrailingSlashes(options.endpoint)}/${options.bucket}`;
@@ -201,7 +222,7 @@ function applyDefaults(options) {
201
222
  keyPrefix: options.keyPrefix ?? "",
202
223
  defaultCacheControl: options.defaultCacheControl ?? DEFAULT_CACHE_CONTROL,
203
224
  defaultContentDisposition: options.defaultContentDisposition ?? DEFAULT_CONTENT_DISPOSITION,
204
- signedUrls: { ...DEFAULT_SIGNED_URLS, ...options.signedUrls ?? {} },
225
+ signedUrls: resolveSignedUrls(options.signedUrls),
205
226
  multipart: { ...DEFAULT_MULTIPART, ...options.multipart ?? {} },
206
227
  ...options.validation !== void 0 ? { validation: options.validation } : {},
207
228
  ...options.scanner !== void 0 ? { scanner: options.scanner } : {},
@@ -291,6 +312,13 @@ var S3ClientProvider = class {
291
312
  ...this.options.credentials.sessionToken ? { sessionToken: this.options.credentials.sessionToken } : {}
292
313
  },
293
314
  maxAttempts: this.options.maxAttempts,
315
+ // `requestTimeout` bounds one attempt, from sending the request until the response
316
+ // headers arrive; the SDK only throws a `TimeoutError` (mapped to
317
+ // `STORAGE_TIMEOUT`) when `throwOnRequestTimeout` is set, otherwise it logs a warning.
318
+ requestHandler: {
319
+ requestTimeout: this.options.requestTimeoutMs,
320
+ throwOnRequestTimeout: true
321
+ },
294
322
  // Data-integrity checksums: AWS SDK v3 defaults to 'WHEN_SUPPORTED' (CRC32
295
323
  // headers), which non-AWS S3-compatible providers reject. Provider recipes
296
324
  // pass 'WHEN_REQUIRED'.
@@ -367,6 +395,316 @@ KeyResolverService = __decorateClass([
367
395
  Injectable(),
368
396
  __decorateParam(0, Inject(BYMAX_STORAGE_OPTIONS))
369
397
  ], KeyResolverService);
398
+ function mapAwsError(err, context) {
399
+ const e = err ?? {};
400
+ const httpStatus = e.$metadata?.httpStatusCode;
401
+ const awsCode = e.Code ?? e.name;
402
+ const requestId = e.$metadata?.requestId;
403
+ const details = {
404
+ ...context ?? {},
405
+ awsCode,
406
+ httpStatus,
407
+ requestId,
408
+ awsMessage: e.message
409
+ };
410
+ if (e.name === "NotFound" || httpStatus === 404) {
411
+ return new StorageException(
412
+ STORAGE_ERROR_CODES.STORAGE_OBJECT_NOT_FOUND,
413
+ HttpStatus.NOT_FOUND,
414
+ details
415
+ );
416
+ }
417
+ if (httpStatus === 304) {
418
+ return new StorageException(STORAGE_ERROR_CODES.STORAGE_NOT_MODIFIED, HttpStatus.NOT_MODIFIED, details);
419
+ }
420
+ if (httpStatus === 412) {
421
+ return new StorageException(
422
+ STORAGE_ERROR_CODES.STORAGE_PRECONDITION_FAILED,
423
+ HttpStatus.PRECONDITION_FAILED,
424
+ details
425
+ );
426
+ }
427
+ if (e.name === "TimeoutError") {
428
+ return new StorageException(STORAGE_ERROR_CODES.STORAGE_TIMEOUT, HttpStatus.GATEWAY_TIMEOUT, details);
429
+ }
430
+ return new StorageException(
431
+ STORAGE_ERROR_CODES.STORAGE_PROVIDER_ERROR,
432
+ HttpStatus.BAD_GATEWAY,
433
+ details
434
+ );
435
+ }
436
+
437
+ // src/server/errors/lifecycle-error-mapper.ts
438
+ var UNSUPPORTED_NAMES = /* @__PURE__ */ new Set([
439
+ "NotImplemented",
440
+ "XNotImplemented",
441
+ "MethodNotAllowed"
442
+ ]);
443
+ var REJECTED_NAMES = /* @__PURE__ */ new Set([
444
+ "MalformedXML",
445
+ "InvalidArgument",
446
+ "InvalidRequest",
447
+ "BadRequest"
448
+ ]);
449
+ var UNSUPPORTED_STATUSES = /* @__PURE__ */ new Set([405, 501]);
450
+ function isNoLifecycleConfiguration(err) {
451
+ const e = err ?? {};
452
+ return (e.Code ?? e.name) === "NoSuchLifecycleConfiguration";
453
+ }
454
+ function mapLifecycleError(err, context) {
455
+ const mapped = mapAwsError(err, context);
456
+ const e = err ?? {};
457
+ const name = e.Code ?? e.name;
458
+ const status = e.$metadata?.httpStatusCode ?? 0;
459
+ const details = mapped.getResponse().error.details;
460
+ if (UNSUPPORTED_NAMES.has(name) || UNSUPPORTED_STATUSES.has(status)) {
461
+ return new StorageException(STORAGE_ERROR_CODES.STORAGE_LIFECYCLE_UNSUPPORTED, void 0, details);
462
+ }
463
+ if (REJECTED_NAMES.has(name)) {
464
+ return new StorageException(STORAGE_ERROR_CODES.STORAGE_LIFECYCLE_REJECTED, void 0, details);
465
+ }
466
+ return mapped;
467
+ }
468
+
469
+ // src/server/services/bucket-lifecycle.service.ts
470
+ var LEGACY_PREFIX_KEY = "Prefix";
471
+ function legacyPrefix(rule) {
472
+ const value = new Map(Object.entries(rule)).get(LEGACY_PREFIX_KEY);
473
+ return typeof value === "string" ? value : void 0;
474
+ }
475
+ var MAX_RULE_ID_LENGTH = 255;
476
+ function ruleInvalid(reason) {
477
+ return new StorageException(STORAGE_ERROR_CODES.STORAGE_LIFECYCLE_RULE_INVALID, void 0, {
478
+ reason
479
+ });
480
+ }
481
+ function assertDays(field, value) {
482
+ if (!Number.isInteger(value) || value < 1) {
483
+ throw ruleInvalid(`${field} must be an integer of at least 1`);
484
+ }
485
+ }
486
+ var BucketLifecycleService = class {
487
+ constructor(options, s3Provider, keyResolver) {
488
+ this.options = options;
489
+ this.s3Provider = s3Provider;
490
+ this.keyResolver = keyResolver;
491
+ }
492
+ options;
493
+ s3Provider;
494
+ keyResolver;
495
+ /**
496
+ * Returns the bucket's lifecycle rules. A bucket with no lifecycle configuration
497
+ * yields an empty array. Key prefixes inside the module's `keyPrefix` come back
498
+ * relative to it, as `list()` returns keys, so a prefix read here can be passed
499
+ * straight to `upsert()` without being prefixed twice. A rule that is not confined
500
+ * to `keyPrefix` is returned exactly as stored, flagged `isOutsideKeyPrefix: true`;
501
+ * everything else about a rule is returned as the provider stores it.
502
+ *
503
+ * @param options - Optional per-call bucket override.
504
+ * @returns Every rule in the bucket.
505
+ * @throws StorageException for missing configuration, an unsupported provider, or a provider error.
506
+ */
507
+ async get(options) {
508
+ this.assertConfigured();
509
+ const bucket = this.resolveBucket(options?.bucket);
510
+ return (await this.read(bucket)).rules.map((rule) => this.toView(rule));
511
+ }
512
+ /**
513
+ * Adds the expiration or multipart-abort rule, or replaces the rule with the same id, and writes
514
+ * the full set back. Rules with other ids are sent exactly as they were read.
515
+ *
516
+ * @param rule - The rule id, key prefix and either `expirationDays` or `abortIncompleteMultipartDays`.
517
+ * @param options - Optional per-call bucket override.
518
+ * @throws StorageException `STORAGE_LIFECYCLE_RULE_INVALID` for a bad id, prefix or day count, or an id
519
+ * that names a rule outside `keyPrefix`;
520
+ * `STORAGE_LIFECYCLE_UNSUPPORTED` / `STORAGE_LIFECYCLE_REJECTED` from the provider.
521
+ * @example
522
+ * await lifecycle.upsert({ id: 'expire-tmp', prefix: 'expiring/', expirationDays: 7 })
523
+ */
524
+ async upsert(rule, options) {
525
+ this.assertConfigured();
526
+ const owned = this.toRule(rule);
527
+ const bucket = this.resolveBucket(options?.bucket);
528
+ const snapshot = await this.read(bucket);
529
+ const index = snapshot.rules.findIndex((existing) => existing.ID === owned.ID);
530
+ this.assertOwnable(snapshot.rules[index]);
531
+ const rules = [...snapshot.rules];
532
+ if (index === -1) {
533
+ rules.push(owned);
534
+ } else {
535
+ rules[index] = owned;
536
+ }
537
+ await this.write(bucket, rules, snapshot, "upsert");
538
+ }
539
+ /**
540
+ * Removes the rule with this id. When it was the last rule the configuration is
541
+ * deleted, because S3 rejects a write with no rules. An unknown id changes nothing.
542
+ *
543
+ * @param id - The rule id.
544
+ * @param options - Optional per-call bucket override.
545
+ * @returns `true` when a rule was removed, `false` when no rule had that id.
546
+ * @throws StorageException `STORAGE_LIFECYCLE_RULE_INVALID` for a bad id or an id that names a rule
547
+ * outside `keyPrefix`; a provider failure otherwise.
548
+ */
549
+ async remove(id, options) {
550
+ this.assertConfigured();
551
+ this.assertRuleId(id);
552
+ const bucket = this.resolveBucket(options?.bucket);
553
+ const snapshot = await this.read(bucket);
554
+ const target = snapshot.rules.find((existing) => existing.ID === id);
555
+ if (target === void 0) {
556
+ return false;
557
+ }
558
+ this.assertOwnable(target);
559
+ const rules = snapshot.rules.filter((existing) => existing.ID !== id);
560
+ await this.write(bucket, rules, snapshot, "remove");
561
+ return true;
562
+ }
563
+ /**
564
+ * Whether the rule is confined to this module's `keyPrefix`: its filter prefix starts
565
+ * with it. Without a `keyPrefix` every rule is in scope. A rule with no prefix at all
566
+ * (tag-only, or the whole bucket) reaches beyond the namespace, so it is not confined.
567
+ */
568
+ isWithinKeyPrefix(rule) {
569
+ const keyPrefix = this.keyResolver.getPrefix();
570
+ if (keyPrefix === "") {
571
+ return true;
572
+ }
573
+ const prefix = rule.Filter?.Prefix ?? rule.Filter?.And?.Prefix ?? legacyPrefix(rule);
574
+ return prefix?.startsWith(keyPrefix) === true;
575
+ }
576
+ /** The caller's view of a rule: prefixes relative to `keyPrefix`, or as stored and flagged when outside it. */
577
+ toView(rule) {
578
+ if (this.isWithinKeyPrefix(rule)) {
579
+ return this.stripRulePrefixes(rule);
580
+ }
581
+ return { ...rule, isOutsideKeyPrefix: true };
582
+ }
583
+ /** Refuses to replace or remove a rule this module's `keyPrefix` does not confine. */
584
+ assertOwnable(existing) {
585
+ if (existing === void 0) {
586
+ return;
587
+ }
588
+ if (!this.isWithinKeyPrefix(existing)) {
589
+ throw ruleInvalid("A rule with this id exists outside the module keyPrefix and is not changed");
590
+ }
591
+ }
592
+ /**
593
+ * Returns a copy of the rule with `keyPrefix` removed from each filter prefix that
594
+ * carries it (`Filter.Prefix`, `Filter.And.Prefix` and the deprecated rule-level
595
+ * `Prefix`). Prefixes outside the namespace are left alone. The stored rule is never touched.
596
+ */
597
+ stripRulePrefixes(rule) {
598
+ const strip = (prefix) => this.keyResolver.stripPrefix(prefix);
599
+ const { Filter: filter, ...rest } = rule;
600
+ const legacy = legacyPrefix(rule);
601
+ return {
602
+ ...rest,
603
+ ...legacy !== void 0 ? { [LEGACY_PREFIX_KEY]: strip(legacy) } : {},
604
+ ...filter !== void 0 ? {
605
+ Filter: {
606
+ ...filter,
607
+ ...filter.Prefix !== void 0 ? { Prefix: strip(filter.Prefix) } : {},
608
+ ...filter.And?.Prefix !== void 0 ? { And: { ...filter.And, Prefix: strip(filter.And.Prefix) } } : {}
609
+ }
610
+ } : {}
611
+ };
612
+ }
613
+ /** Reads the configuration; "none yet" is an empty snapshot. */
614
+ async read(bucket) {
615
+ try {
616
+ const response = await this.s3Provider.getClient().send(new GetBucketLifecycleConfigurationCommand({ Bucket: bucket }));
617
+ return {
618
+ rules: response.Rules ?? [],
619
+ transitionDefaultMinimumObjectSize: response.TransitionDefaultMinimumObjectSize
620
+ };
621
+ } catch (err) {
622
+ if (isNoLifecycleConfiguration(err)) {
623
+ return { rules: [], transitionDefaultMinimumObjectSize: void 0 };
624
+ }
625
+ throw mapLifecycleError(err, { bucket, op: "lifecycle.get" });
626
+ }
627
+ }
628
+ /**
629
+ * Writes the rule set. An empty set is a `DeleteBucketLifecycle`, since S3
630
+ * requires at least one rule on a put. The default-minimum-object-size setting
631
+ * read earlier is sent back so a write does not silently change transition behaviour.
632
+ */
633
+ async write(bucket, rules, snapshot, op) {
634
+ const client = this.s3Provider.getClient();
635
+ try {
636
+ if (rules.length === 0) {
637
+ await client.send(new DeleteBucketLifecycleCommand({ Bucket: bucket }));
638
+ return;
639
+ }
640
+ await client.send(
641
+ new PutBucketLifecycleConfigurationCommand({
642
+ Bucket: bucket,
643
+ LifecycleConfiguration: { Rules: rules },
644
+ ...snapshot.transitionDefaultMinimumObjectSize !== void 0 ? { TransitionDefaultMinimumObjectSize: snapshot.transitionDefaultMinimumObjectSize } : {}
645
+ })
646
+ );
647
+ } catch (err) {
648
+ throw mapLifecycleError(err, { bucket, op: `lifecycle.${op}` });
649
+ }
650
+ }
651
+ /** Validates the input and builds the rule, an expiration or a multipart-abort rule. */
652
+ toRule(rule) {
653
+ this.assertRuleId(rule.id);
654
+ if (rule.abortIncompleteMultipartDays !== void 0) {
655
+ assertDays("abortIncompleteMultipartDays", rule.abortIncompleteMultipartDays);
656
+ if (rule.expirationDays !== void 0) {
657
+ throw ruleInvalid("Give exactly one of expirationDays and abortIncompleteMultipartDays");
658
+ }
659
+ if (typeof rule.prefix !== "string") {
660
+ throw ruleInvalid("Prefix must be a string");
661
+ }
662
+ const prefix = rule.prefix === "" ? this.keyResolver.getPrefix() : this.keyResolver.normalize(rule.prefix);
663
+ return {
664
+ ID: rule.id,
665
+ Status: "Enabled",
666
+ Filter: { Prefix: prefix },
667
+ AbortIncompleteMultipartUpload: { DaysAfterInitiation: rule.abortIncompleteMultipartDays }
668
+ };
669
+ }
670
+ if (typeof rule.prefix !== "string" || rule.prefix.length === 0) {
671
+ throw ruleInvalid("Prefix must be a non-empty string");
672
+ }
673
+ assertDays("expirationDays", rule.expirationDays);
674
+ return {
675
+ ID: rule.id,
676
+ Status: "Enabled",
677
+ Filter: { Prefix: this.keyResolver.normalize(rule.prefix) },
678
+ Expiration: { Days: rule.expirationDays }
679
+ };
680
+ }
681
+ assertRuleId(id) {
682
+ if (typeof id !== "string" || id.length === 0) {
683
+ throw ruleInvalid("Rule id must be a non-empty string");
684
+ }
685
+ if (id.length > MAX_RULE_ID_LENGTH) {
686
+ throw ruleInvalid(`Rule id must be at most ${String(MAX_RULE_ID_LENGTH)} characters`);
687
+ }
688
+ }
689
+ assertConfigured() {
690
+ if (!this.s3Provider.isConfigured()) {
691
+ throw new StorageException(STORAGE_ERROR_CODES.STORAGE_NOT_CONFIGURED);
692
+ }
693
+ }
694
+ resolveBucket(perCall) {
695
+ const bucket = perCall ?? this.options.bucket;
696
+ if (!bucket) {
697
+ throw new StorageException(STORAGE_ERROR_CODES.STORAGE_BUCKET_UNDEFINED);
698
+ }
699
+ return bucket;
700
+ }
701
+ };
702
+ BucketLifecycleService = __decorateClass([
703
+ Injectable(),
704
+ __decorateParam(0, Inject(BYMAX_STORAGE_OPTIONS)),
705
+ __decorateParam(1, Inject(S3ClientProvider)),
706
+ __decorateParam(2, Inject(KeyResolverService))
707
+ ], BucketLifecycleService);
370
708
  function isBufferLike(body) {
371
709
  return body instanceof Uint8Array;
372
710
  }
@@ -383,6 +721,21 @@ async function peekFirstBytes(body, maxBytes) {
383
721
  }
384
722
  return teeAndPeek(body, maxBytes);
385
723
  }
724
+ function destroyStream(stream) {
725
+ const target = stream;
726
+ if (!target) {
727
+ return;
728
+ }
729
+ target.once?.("error", () => void 0);
730
+ target.destroy?.();
731
+ }
732
+ function releaseSourceOnEarlyClose(source, replacement, sourceEnded) {
733
+ replacement.once("close", () => {
734
+ if (!sourceEnded()) {
735
+ destroyStream(source);
736
+ }
737
+ });
738
+ }
386
739
  async function teeAndPeek(source, maxBytes) {
387
740
  const peekPT = new PassThrough();
388
741
  const uploadPT = new PassThrough();
@@ -410,12 +763,16 @@ async function teeAndPeek(source, maxBytes) {
410
763
  uploadPT.once("drain", () => source.resume());
411
764
  }
412
765
  });
766
+ let sourceEnded = false;
413
767
  source.on("end", () => {
768
+ sourceEnded = true;
414
769
  closePeek();
415
770
  uploadPT.end();
416
771
  });
772
+ releaseSourceOnEarlyClose(source, uploadPT, () => sourceEnded);
417
773
  source.on("error", (err) => {
418
774
  closePeek();
775
+ uploadPT.once("error", () => void 0);
419
776
  uploadPT.destroy(err);
420
777
  });
421
778
  const head = await collectStream(peekPT);
@@ -428,6 +785,19 @@ async function collectStream(stream) {
428
785
  }
429
786
  return Buffer.concat(chunks);
430
787
  }
788
+ async function readStreamUpTo(source, maxBytes) {
789
+ const chunks = [];
790
+ let total = 0;
791
+ for await (const chunk of source) {
792
+ const buf = typeof chunk === "string" ? Buffer.from(chunk) : chunk;
793
+ total += buf.byteLength;
794
+ if (total > maxBytes) {
795
+ return void 0;
796
+ }
797
+ chunks.push(buf);
798
+ }
799
+ return Buffer.concat(chunks);
800
+ }
431
801
 
432
802
  // src/server/utils/mime-match.ts
433
803
  function mimeMatches(mime, whitelist) {
@@ -623,34 +993,6 @@ FileScannerService = __decorateClass([
623
993
  __decorateParam(0, Inject(BYMAX_STORAGE_OPTIONS)),
624
994
  __decorateParam(1, Inject(BYMAX_STORAGE_FILE_SCANNER))
625
995
  ], FileScannerService);
626
- function mapAwsError(err, context) {
627
- const e = err ?? {};
628
- const httpStatus = e.$metadata?.httpStatusCode;
629
- const awsCode = e.Code ?? e.name;
630
- const requestId = e.$metadata?.requestId;
631
- const details = {
632
- ...context ?? {},
633
- awsCode,
634
- httpStatus,
635
- requestId,
636
- awsMessage: e.message
637
- };
638
- if (e.name === "NotFound" || httpStatus === 404) {
639
- return new StorageException(
640
- STORAGE_ERROR_CODES.STORAGE_OBJECT_NOT_FOUND,
641
- HttpStatus.NOT_FOUND,
642
- details
643
- );
644
- }
645
- if (e.name === "TimeoutError") {
646
- return new StorageException(STORAGE_ERROR_CODES.STORAGE_TIMEOUT, HttpStatus.GATEWAY_TIMEOUT, details);
647
- }
648
- return new StorageException(
649
- STORAGE_ERROR_CODES.STORAGE_PROVIDER_ERROR,
650
- HttpStatus.BAD_GATEWAY,
651
- details
652
- );
653
- }
654
996
 
655
997
  // src/server/utils/header-utils.ts
656
998
  function buildContentDisposition(perCall, defaultValue) {
@@ -713,11 +1055,26 @@ var StorageService = class {
713
1055
  * `idempotencyKey` is supplied and a matching result is cached within the TTL
714
1056
  * window, the cached result is returned without re-uploading.
715
1057
  *
1058
+ * The library takes ownership of a `Readable` body, as `stream.pipeline` does: when the
1059
+ * upload is rejected for any reason (configuration, validation, scan, provider failure)
1060
+ * the stream is destroyed (without an error: the SDK forwards a stream's error to wrappers
1061
+ * that nothing listens to), which releases the file handle or socket behind it; a cache hit
1062
+ * destroys it unread. A stream consumed by a successful upload ends on its own.
1063
+ *
716
1064
  * @param options - The upload request.
717
1065
  * @returns The upload result.
718
1066
  * @throws StorageException for missing configuration, body, or content type.
719
1067
  */
720
1068
  async upload(options) {
1069
+ try {
1070
+ return await this.uploadOwningBody(options);
1071
+ } catch (err) {
1072
+ destroyStream(options.body);
1073
+ throw err;
1074
+ }
1075
+ }
1076
+ /** The upload itself; `upload()` destroys a stream body when this rejects. */
1077
+ async uploadOwningBody(options) {
721
1078
  this.assertConfigured();
722
1079
  const rawBody = options.body;
723
1080
  if (rawBody === void 0 || rawBody === null) {
@@ -732,6 +1089,7 @@ var StorageService = class {
732
1089
  const cacheKey = this.idempotencyCache.computeKey(options.idempotencyKey, finalKey);
733
1090
  const cached = this.idempotencyCache.get(cacheKey);
734
1091
  if (cached) {
1092
+ destroyStream(options.body);
735
1093
  return { ...cached, fromIdempotencyCache: true };
736
1094
  }
737
1095
  }
@@ -742,8 +1100,9 @@ var StorageService = class {
742
1100
  ...options.size !== void 0 ? { size: options.size } : {},
743
1101
  ...options.metadata !== void 0 ? { metadata: options.metadata } : {}
744
1102
  });
745
- const validatedOptions = { ...options, body: validated.body };
746
- await this.runPreUploadScan(validated.body, finalKey, bucket, options);
1103
+ const body = await this.bufferForPreUploadScan(validated.body, finalKey);
1104
+ const validatedOptions = { ...options, body };
1105
+ await this.runPreUploadScan(body, finalKey, bucket, options);
747
1106
  const strategy = pickUploadStrategy(
748
1107
  validatedOptions.body,
749
1108
  validatedOptions.size,
@@ -759,6 +1118,35 @@ var StorageService = class {
759
1118
  }
760
1119
  return result;
761
1120
  }
1121
+ /**
1122
+ * In pre-upload scan mode a stream body is read into one `Buffer`, so the scanner
1123
+ * and the upload see the same bytes; a stream is single-use, and one the scanner
1124
+ * had consumed would leave the upload with nothing to send. The read is bounded by
1125
+ * `validation.maxSizeBytes`, and a stream with no bound is refused rather than
1126
+ * buffered without limit. Other bodies and modes pass through unchanged.
1127
+ */
1128
+ async bufferForPreUploadScan(body, finalKey) {
1129
+ if (!this.scanner.isEnabled() || this.scanner.getMode() !== "pre-upload" || isBufferLike(body)) {
1130
+ return body;
1131
+ }
1132
+ const maxSizeBytes = this.options.validation?.maxSizeBytes;
1133
+ if (maxSizeBytes === void 0) {
1134
+ destroyStream(body);
1135
+ throw new StorageException(STORAGE_ERROR_CODES.STORAGE_VALIDATION_FAILED, void 0, {
1136
+ key: finalKey,
1137
+ reason: "Pre-upload scanning of a stream needs validation.maxSizeBytes to bound the buffer; set it or use scanner mode post-upload"
1138
+ });
1139
+ }
1140
+ const buffered = await readStreamUpTo(body, maxSizeBytes);
1141
+ if (buffered === void 0) {
1142
+ throw new StorageException(STORAGE_ERROR_CODES.STORAGE_VALIDATION_FAILED, void 0, {
1143
+ key: finalKey,
1144
+ maxSizeBytes,
1145
+ reason: "The stream is longer than validation.maxSizeBytes, so it cannot be scanned before upload"
1146
+ });
1147
+ }
1148
+ return buffered;
1149
+ }
762
1150
  /** Runs a pre-upload scan when configured; throws on infected. */
763
1151
  async runPreUploadScan(body, finalKey, bucket, options) {
764
1152
  if (!this.scanner.isEnabled() || this.scanner.getMode() !== "pre-upload") {
@@ -774,15 +1162,12 @@ var StorageService = class {
774
1162
  });
775
1163
  }
776
1164
  /**
777
- * Coerces a buffer-like scan body (`Buffer` or `Uint8Array`) to a `Buffer` so
778
- * the scanner always receives its declared contract type; streams pass through
779
- * unchanged.
1165
+ * Coerces the scan body to a `Buffer` so the scanner always receives its declared
1166
+ * contract type. In pre-upload mode a stream has already been buffered by
1167
+ * {@link bufferForPreUploadScan}, so only `Buffer` and `Uint8Array` arrive here.
780
1168
  */
781
1169
  normalizeScanBody(body) {
782
- if (isBufferLike(body)) {
783
- return Buffer.isBuffer(body) ? body : Buffer.from(body);
784
- }
785
- return body;
1170
+ return Buffer.isBuffer(body) ? body : Buffer.from(body);
786
1171
  }
787
1172
  /**
788
1173
  * Runs a post-upload scan. On infection, deletes the just-uploaded object
@@ -971,7 +1356,7 @@ var StorageService = class {
971
1356
  /** Maps an S3 metadata response onto the public `ObjectMetadata` shape. */
972
1357
  toObjectMetadata(response, finalKey, bucket) {
973
1358
  return {
974
- key: finalKey,
1359
+ key: this.keyResolver.stripPrefix(finalKey),
975
1360
  bucket,
976
1361
  size: response.ContentLength ?? 0,
977
1362
  contentType: response.ContentType ?? "application/octet-stream",
@@ -1082,7 +1467,7 @@ var StorageService = class {
1082
1467
  /** Assembles an `UploadResult`, omitting optional fields that are absent. */
1083
1468
  buildUploadResult(params) {
1084
1469
  return {
1085
- key: params.finalKey,
1470
+ key: this.keyResolver.stripPrefix(params.finalKey),
1086
1471
  bucket: params.bucket,
1087
1472
  etag: params.etag ?? "",
1088
1473
  contentType: params.contentType,
@@ -1268,6 +1653,7 @@ function clampTtl(ttlSeconds, defaultTtl, maxTtl) {
1268
1653
  }
1269
1654
 
1270
1655
  // src/server/services/signed-url.service.ts
1656
+ var MAX_MULTIPART_PARTS = 1e4;
1271
1657
  var SignedUrlService = class {
1272
1658
  constructor(options, s3Provider, keyResolver) {
1273
1659
  this.options = options;
@@ -1393,14 +1779,15 @@ var SignedUrlService = class {
1393
1779
  * @param options - The multipart URL options.
1394
1780
  * @returns `uploadId`, `partUrls`, and `completeUrl`.
1395
1781
  * @throws StorageException `STORAGE_NOT_CONFIGURED` when the client is absent.
1782
+ * @throws StorageException `STORAGE_INVALID_PART_COUNT` when `parts` is not an integer from 1 to 10 000.
1396
1783
  * @throws StorageException `STORAGE_SIGNED_URL_TTL_INVALID` for non-positive TTL.
1397
1784
  * @throws StorageException `STORAGE_PROVIDER_ERROR` when no `UploadId` is returned.
1398
1785
  */
1399
1786
  async getMultipartUploadUrls(options) {
1400
1787
  this.assertConfigured();
1401
- if (options.parts <= 0) {
1788
+ if (!Number.isInteger(options.parts) || options.parts < 1 || options.parts > MAX_MULTIPART_PARTS) {
1402
1789
  throw new StorageException(STORAGE_ERROR_CODES.STORAGE_INVALID_PART_COUNT, void 0, {
1403
- reason: "parts must be a positive integer",
1790
+ reason: `parts must be an integer from 1 to ${String(MAX_MULTIPART_PARTS)}`,
1404
1791
  provided: options.parts
1405
1792
  });
1406
1793
  }
@@ -1556,7 +1943,14 @@ var IdempotencyCache = class {
1556
1943
  // src/server/bymax-storage.module.ts
1557
1944
  function resolveAsyncOptions(options) {
1558
1945
  validateOptions(options);
1559
- return applyDefaults(options);
1946
+ const resolved = applyDefaults(options);
1947
+ const configured = options.signedUrls?.maxTtlSeconds;
1948
+ if (configured !== void 0 && configured > resolved.signedUrls.maxTtlSeconds) {
1949
+ new Logger(BymaxStorageModule.name).warn(
1950
+ `signedUrls.maxTtlSeconds=${String(configured)} exceeds the SigV4 presigned-URL limit; using ${String(resolved.signedUrls.maxTtlSeconds)} seconds (7 days) instead.`
1951
+ );
1952
+ }
1953
+ return resolved;
1560
1954
  }
1561
1955
  var BymaxStorageModule = class {
1562
1956
  /**
@@ -1654,6 +2048,7 @@ var BymaxStorageModule = class {
1654
2048
  },
1655
2049
  StorageService,
1656
2050
  SignedUrlService,
2051
+ BucketLifecycleService,
1657
2052
  // ValidationService and FileScannerService are internal — consumed via
1658
2053
  // StorageService.upload() only, not exported from the module.
1659
2054
  ValidationService,
@@ -1676,6 +2071,7 @@ var BymaxStorageModule = class {
1676
2071
  return [
1677
2072
  StorageService,
1678
2073
  SignedUrlService,
2074
+ BucketLifecycleService,
1679
2075
  BYMAX_STORAGE_OPTIONS,
1680
2076
  BYMAX_STORAGE_S3_CLIENT,
1681
2077
  BYMAX_STORAGE_UPLOAD_VALIDATORS,
@@ -1838,4 +2234,4 @@ var providerRecipes = {
1838
2234
  }
1839
2235
  };
1840
2236
 
1841
- export { BYMAX_STORAGE_FILE_SCANNER, BYMAX_STORAGE_OPTIONS, BYMAX_STORAGE_S3_CLIENT, BYMAX_STORAGE_UPLOAD_VALIDATORS, BymaxStorageModule, NoOpFileScanner, NoOpUploadValidator, STORAGE_ERROR_CODES, SignedUrlService, StorageException, StorageService, providerRecipes };
2237
+ export { BYMAX_STORAGE_FILE_SCANNER, BYMAX_STORAGE_OPTIONS, BYMAX_STORAGE_S3_CLIENT, BYMAX_STORAGE_UPLOAD_VALIDATORS, BucketLifecycleService, BymaxStorageModule, NoOpFileScanner, NoOpUploadValidator, STORAGE_ERROR_CODES, SignedUrlService, StorageException, StorageService, providerRecipes };