@bymax-one/nest-storage 1.1.0 → 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';
@@ -20,7 +20,6 @@ var BYMAX_STORAGE_OPTIONS = /* @__PURE__ */ Symbol("BYMAX_STORAGE_OPTIONS");
20
20
  var BYMAX_STORAGE_S3_CLIENT = /* @__PURE__ */ Symbol("BYMAX_STORAGE_S3_CLIENT");
21
21
  var BYMAX_STORAGE_UPLOAD_VALIDATORS = /* @__PURE__ */ Symbol("BYMAX_STORAGE_UPLOAD_VALIDATORS");
22
22
  var BYMAX_STORAGE_FILE_SCANNER = /* @__PURE__ */ Symbol("BYMAX_STORAGE_FILE_SCANNER");
23
- var BYMAX_STORAGE_LOGGER = /* @__PURE__ */ Symbol("BYMAX_STORAGE_LOGGER");
24
23
  var BYMAX_STORAGE_IDEMPOTENCY_CACHE = /* @__PURE__ */ Symbol("BYMAX_STORAGE_IDEMPOTENCY_CACHE");
25
24
 
26
25
  // src/shared/constants/error-codes.constants.ts
@@ -37,12 +36,19 @@ var STORAGE_ERROR_CODES = {
37
36
  STORAGE_OBJECT_NOT_FOUND: "STORAGE_OBJECT_NOT_FOUND",
38
37
  STORAGE_PROVIDER_ERROR: "STORAGE_PROVIDER_ERROR",
39
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.
40
41
  STORAGE_PART_TOO_SMALL: "STORAGE_PART_TOO_SMALL",
41
42
  STORAGE_INVALID_PART_COUNT: "STORAGE_INVALID_PART_COUNT",
42
43
  STORAGE_BUCKET_UNDEFINED: "STORAGE_BUCKET_UNDEFINED",
43
44
  STORAGE_MULTIPART_ABORTED: "STORAGE_MULTIPART_ABORTED",
44
45
  STORAGE_INVALID_CONFIG: "STORAGE_INVALID_CONFIG",
45
- 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"
46
52
  };
47
53
 
48
54
  // src/server/errors/storage-error-messages.ts
@@ -60,11 +66,16 @@ var STORAGE_ERROR_MESSAGES = {
60
66
  [STORAGE_ERROR_CODES.STORAGE_PROVIDER_ERROR]: "Storage provider returned an error",
61
67
  [STORAGE_ERROR_CODES.STORAGE_SIGNED_URL_TTL_INVALID]: "Signed URL TTL is invalid",
62
68
  [STORAGE_ERROR_CODES.STORAGE_PART_TOO_SMALL]: "Multipart part size is below the 5 MB minimum",
63
- [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)",
64
70
  [STORAGE_ERROR_CODES.STORAGE_BUCKET_UNDEFINED]: "Bucket is undefined (no default configured and none provided per call)",
65
71
  [STORAGE_ERROR_CODES.STORAGE_MULTIPART_ABORTED]: "Multipart upload was aborted",
66
72
  [STORAGE_ERROR_CODES.STORAGE_INVALID_CONFIG]: "Module configuration is invalid",
67
- [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"
68
79
  };
69
80
  var STORAGE_ERROR_STATUS = {
70
81
  [STORAGE_ERROR_CODES.STORAGE_NOT_CONFIGURED]: HttpStatus.SERVICE_UNAVAILABLE,
@@ -84,7 +95,12 @@ var STORAGE_ERROR_STATUS = {
84
95
  [STORAGE_ERROR_CODES.STORAGE_BUCKET_UNDEFINED]: HttpStatus.BAD_REQUEST,
85
96
  [STORAGE_ERROR_CODES.STORAGE_MULTIPART_ABORTED]: HttpStatus.INTERNAL_SERVER_ERROR,
86
97
  [STORAGE_ERROR_CODES.STORAGE_INVALID_CONFIG]: HttpStatus.INTERNAL_SERVER_ERROR,
87
- [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
88
104
  };
89
105
 
90
106
  // src/server/errors/storage-exception.ts
@@ -187,6 +203,10 @@ var DEFAULT_IDEMPOTENCY_CACHE_MAX_ENTRIES = 1e3;
187
203
  var DEFAULT_IDEMPOTENCY_CACHE_TTL_MS = 864e5;
188
204
 
189
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
+ }
190
210
  function applyDefaults(options) {
191
211
  const hasCredentials = Boolean(options.credentials.accessKeyId) && Boolean(options.credentials.secretAccessKey);
192
212
  const publicBaseUrl = options.publicBaseUrl ?? `${trimTrailingSlashes(options.endpoint)}/${options.bucket}`;
@@ -202,7 +222,7 @@ function applyDefaults(options) {
202
222
  keyPrefix: options.keyPrefix ?? "",
203
223
  defaultCacheControl: options.defaultCacheControl ?? DEFAULT_CACHE_CONTROL,
204
224
  defaultContentDisposition: options.defaultContentDisposition ?? DEFAULT_CONTENT_DISPOSITION,
205
- signedUrls: { ...DEFAULT_SIGNED_URLS, ...options.signedUrls ?? {} },
225
+ signedUrls: resolveSignedUrls(options.signedUrls),
206
226
  multipart: { ...DEFAULT_MULTIPART, ...options.multipart ?? {} },
207
227
  ...options.validation !== void 0 ? { validation: options.validation } : {},
208
228
  ...options.scanner !== void 0 ? { scanner: options.scanner } : {},
@@ -292,6 +312,13 @@ var S3ClientProvider = class {
292
312
  ...this.options.credentials.sessionToken ? { sessionToken: this.options.credentials.sessionToken } : {}
293
313
  },
294
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
+ },
295
322
  // Data-integrity checksums: AWS SDK v3 defaults to 'WHEN_SUPPORTED' (CRC32
296
323
  // headers), which non-AWS S3-compatible providers reject. Provider recipes
297
324
  // pass 'WHEN_REQUIRED'.
@@ -368,6 +395,316 @@ KeyResolverService = __decorateClass([
368
395
  Injectable(),
369
396
  __decorateParam(0, Inject(BYMAX_STORAGE_OPTIONS))
370
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);
371
708
  function isBufferLike(body) {
372
709
  return body instanceof Uint8Array;
373
710
  }
@@ -384,6 +721,21 @@ async function peekFirstBytes(body, maxBytes) {
384
721
  }
385
722
  return teeAndPeek(body, maxBytes);
386
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
+ }
387
739
  async function teeAndPeek(source, maxBytes) {
388
740
  const peekPT = new PassThrough();
389
741
  const uploadPT = new PassThrough();
@@ -411,12 +763,16 @@ async function teeAndPeek(source, maxBytes) {
411
763
  uploadPT.once("drain", () => source.resume());
412
764
  }
413
765
  });
766
+ let sourceEnded = false;
414
767
  source.on("end", () => {
768
+ sourceEnded = true;
415
769
  closePeek();
416
770
  uploadPT.end();
417
771
  });
772
+ releaseSourceOnEarlyClose(source, uploadPT, () => sourceEnded);
418
773
  source.on("error", (err) => {
419
774
  closePeek();
775
+ uploadPT.once("error", () => void 0);
420
776
  uploadPT.destroy(err);
421
777
  });
422
778
  const head = await collectStream(peekPT);
@@ -429,6 +785,19 @@ async function collectStream(stream) {
429
785
  }
430
786
  return Buffer.concat(chunks);
431
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
+ }
432
801
 
433
802
  // src/server/utils/mime-match.ts
434
803
  function mimeMatches(mime, whitelist) {
@@ -624,34 +993,6 @@ FileScannerService = __decorateClass([
624
993
  __decorateParam(0, Inject(BYMAX_STORAGE_OPTIONS)),
625
994
  __decorateParam(1, Inject(BYMAX_STORAGE_FILE_SCANNER))
626
995
  ], FileScannerService);
627
- function mapAwsError(err, context) {
628
- const e = err ?? {};
629
- const httpStatus = e.$metadata?.httpStatusCode;
630
- const awsCode = e.Code ?? e.name;
631
- const requestId = e.$metadata?.requestId;
632
- const details = {
633
- ...context ?? {},
634
- awsCode,
635
- httpStatus,
636
- requestId,
637
- awsMessage: e.message
638
- };
639
- if (e.name === "NotFound" || httpStatus === 404) {
640
- return new StorageException(
641
- STORAGE_ERROR_CODES.STORAGE_OBJECT_NOT_FOUND,
642
- HttpStatus.NOT_FOUND,
643
- details
644
- );
645
- }
646
- if (e.name === "TimeoutError") {
647
- return new StorageException(STORAGE_ERROR_CODES.STORAGE_TIMEOUT, HttpStatus.GATEWAY_TIMEOUT, details);
648
- }
649
- return new StorageException(
650
- STORAGE_ERROR_CODES.STORAGE_PROVIDER_ERROR,
651
- HttpStatus.BAD_GATEWAY,
652
- details
653
- );
654
- }
655
996
 
656
997
  // src/server/utils/header-utils.ts
657
998
  function buildContentDisposition(perCall, defaultValue) {
@@ -714,11 +1055,26 @@ var StorageService = class {
714
1055
  * `idempotencyKey` is supplied and a matching result is cached within the TTL
715
1056
  * window, the cached result is returned without re-uploading.
716
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
+ *
717
1064
  * @param options - The upload request.
718
1065
  * @returns The upload result.
719
1066
  * @throws StorageException for missing configuration, body, or content type.
720
1067
  */
721
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) {
722
1078
  this.assertConfigured();
723
1079
  const rawBody = options.body;
724
1080
  if (rawBody === void 0 || rawBody === null) {
@@ -733,6 +1089,7 @@ var StorageService = class {
733
1089
  const cacheKey = this.idempotencyCache.computeKey(options.idempotencyKey, finalKey);
734
1090
  const cached = this.idempotencyCache.get(cacheKey);
735
1091
  if (cached) {
1092
+ destroyStream(options.body);
736
1093
  return { ...cached, fromIdempotencyCache: true };
737
1094
  }
738
1095
  }
@@ -743,8 +1100,9 @@ var StorageService = class {
743
1100
  ...options.size !== void 0 ? { size: options.size } : {},
744
1101
  ...options.metadata !== void 0 ? { metadata: options.metadata } : {}
745
1102
  });
746
- const validatedOptions = { ...options, body: validated.body };
747
- 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);
748
1106
  const strategy = pickUploadStrategy(
749
1107
  validatedOptions.body,
750
1108
  validatedOptions.size,
@@ -760,6 +1118,35 @@ var StorageService = class {
760
1118
  }
761
1119
  return result;
762
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
+ }
763
1150
  /** Runs a pre-upload scan when configured; throws on infected. */
764
1151
  async runPreUploadScan(body, finalKey, bucket, options) {
765
1152
  if (!this.scanner.isEnabled() || this.scanner.getMode() !== "pre-upload") {
@@ -775,15 +1162,12 @@ var StorageService = class {
775
1162
  });
776
1163
  }
777
1164
  /**
778
- * Coerces a buffer-like scan body (`Buffer` or `Uint8Array`) to a `Buffer` so
779
- * the scanner always receives its declared contract type; streams pass through
780
- * 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.
781
1168
  */
782
1169
  normalizeScanBody(body) {
783
- if (isBufferLike(body)) {
784
- return Buffer.isBuffer(body) ? body : Buffer.from(body);
785
- }
786
- return body;
1170
+ return Buffer.isBuffer(body) ? body : Buffer.from(body);
787
1171
  }
788
1172
  /**
789
1173
  * Runs a post-upload scan. On infection, deletes the just-uploaded object
@@ -972,7 +1356,7 @@ var StorageService = class {
972
1356
  /** Maps an S3 metadata response onto the public `ObjectMetadata` shape. */
973
1357
  toObjectMetadata(response, finalKey, bucket) {
974
1358
  return {
975
- key: finalKey,
1359
+ key: this.keyResolver.stripPrefix(finalKey),
976
1360
  bucket,
977
1361
  size: response.ContentLength ?? 0,
978
1362
  contentType: response.ContentType ?? "application/octet-stream",
@@ -1083,7 +1467,7 @@ var StorageService = class {
1083
1467
  /** Assembles an `UploadResult`, omitting optional fields that are absent. */
1084
1468
  buildUploadResult(params) {
1085
1469
  return {
1086
- key: params.finalKey,
1470
+ key: this.keyResolver.stripPrefix(params.finalKey),
1087
1471
  bucket: params.bucket,
1088
1472
  etag: params.etag ?? "",
1089
1473
  contentType: params.contentType,
@@ -1269,6 +1653,7 @@ function clampTtl(ttlSeconds, defaultTtl, maxTtl) {
1269
1653
  }
1270
1654
 
1271
1655
  // src/server/services/signed-url.service.ts
1656
+ var MAX_MULTIPART_PARTS = 1e4;
1272
1657
  var SignedUrlService = class {
1273
1658
  constructor(options, s3Provider, keyResolver) {
1274
1659
  this.options = options;
@@ -1394,14 +1779,15 @@ var SignedUrlService = class {
1394
1779
  * @param options - The multipart URL options.
1395
1780
  * @returns `uploadId`, `partUrls`, and `completeUrl`.
1396
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.
1397
1783
  * @throws StorageException `STORAGE_SIGNED_URL_TTL_INVALID` for non-positive TTL.
1398
1784
  * @throws StorageException `STORAGE_PROVIDER_ERROR` when no `UploadId` is returned.
1399
1785
  */
1400
1786
  async getMultipartUploadUrls(options) {
1401
1787
  this.assertConfigured();
1402
- if (options.parts <= 0) {
1788
+ if (!Number.isInteger(options.parts) || options.parts < 1 || options.parts > MAX_MULTIPART_PARTS) {
1403
1789
  throw new StorageException(STORAGE_ERROR_CODES.STORAGE_INVALID_PART_COUNT, void 0, {
1404
- reason: "parts must be a positive integer",
1790
+ reason: `parts must be an integer from 1 to ${String(MAX_MULTIPART_PARTS)}`,
1405
1791
  provided: options.parts
1406
1792
  });
1407
1793
  }
@@ -1557,7 +1943,14 @@ var IdempotencyCache = class {
1557
1943
  // src/server/bymax-storage.module.ts
1558
1944
  function resolveAsyncOptions(options) {
1559
1945
  validateOptions(options);
1560
- 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;
1561
1954
  }
1562
1955
  var BymaxStorageModule = class {
1563
1956
  /**
@@ -1655,6 +2048,7 @@ var BymaxStorageModule = class {
1655
2048
  },
1656
2049
  StorageService,
1657
2050
  SignedUrlService,
2051
+ BucketLifecycleService,
1658
2052
  // ValidationService and FileScannerService are internal — consumed via
1659
2053
  // StorageService.upload() only, not exported from the module.
1660
2054
  ValidationService,
@@ -1677,6 +2071,7 @@ var BymaxStorageModule = class {
1677
2071
  return [
1678
2072
  StorageService,
1679
2073
  SignedUrlService,
2074
+ BucketLifecycleService,
1680
2075
  BYMAX_STORAGE_OPTIONS,
1681
2076
  BYMAX_STORAGE_S3_CLIENT,
1682
2077
  BYMAX_STORAGE_UPLOAD_VALIDATORS,
@@ -1839,4 +2234,4 @@ var providerRecipes = {
1839
2234
  }
1840
2235
  };
1841
2236
 
1842
- export { BYMAX_STORAGE_FILE_SCANNER, BYMAX_STORAGE_IDEMPOTENCY_CACHE, BYMAX_STORAGE_LOGGER, 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 };