@dimah-s3/server 1.5.11 → 1.7.0

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/dist/api/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { createMiddleware, createEndpoint } from 'better-call';
2
2
  import * as z from 'zod';
3
- import { S3_API_ROUTES, isAPIError, APIError, S3_ERROR_CODES, confirmBodySchema, deleteQuerySchema, deleteBatchBodySchema, downloadQuerySchema, fileQuerySchema, multipartAbortBodySchema, multipartCompleteBodySchema, multipartInitBodySchema, multipartListPartsQuerySchema, multipartSignPartBodySchema, uploadBodySchema, S3_MAX_EXPIRES_IN, buildContentDisposition, S3_MAX_POST_OBJECT_BYTES, resolveStoredFileName, S3_DEFAULT_EXPIRES_IN, matchesFileTypes, normalizeObjectKey, sanitizeFileName } from '@dimah-s3/core';
4
- import { DeleteObjectCommand, GetObjectCommand, CreateMultipartUploadCommand, UploadPartCommand, PutObjectCommand, ListPartsCommand, AbortMultipartUploadCommand, CompleteMultipartUploadCommand, HeadObjectCommand } from '@aws-sdk/client-s3';
3
+ import { S3_API_ROUTES, isAPIError, APIError, S3_ERROR_CODES, confirmBodySchema, deleteQuerySchema, deleteBatchBodySchema, downloadQuerySchema, fileQuerySchema, multipartAbortBodySchema, multipartCompleteBodySchema, multipartInitBodySchema, multipartListPartsQuerySchema, multipartSignPartBodySchema, uploadBodySchema, buildContentDisposition, S3_MAX_EXPIRES_IN, S3_MAX_POST_OBJECT_BYTES, resolveStoredFileName, resolveInlineDisposition, fileNameFromKey, S3_DEFAULT_EXPIRES_IN, matchesFileTypes, normalizeObjectKey, sanitizeFileName } from '@dimah-s3/core';
4
+ import { DeleteObjectCommand, GetObjectCommand, CreateMultipartUploadCommand, UploadPartCommand, PutObjectCommand, HeadObjectCommand, ListPartsCommand, AbortMultipartUploadCommand, CompleteMultipartUploadCommand } from '@aws-sdk/client-s3';
5
5
  import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
6
6
  import { createPresignedPost } from '@aws-sdk/s3-presigned-post';
7
7
 
@@ -102,6 +102,15 @@ function normalizeExpiresIn(value, maxExpiresIn = S3_MAX_EXPIRES_IN) {
102
102
  const max = Number.isFinite(maxExpiresIn) && maxExpiresIn > 0 ? Math.floor(maxExpiresIn) : S3_MAX_EXPIRES_IN;
103
103
  return Math.min(expires, max);
104
104
  }
105
+ function clampDownloadExpiresIn(options) {
106
+ const max = options.maxExpiresIn;
107
+ if (options.resolvedExpiresIn != null) {
108
+ return normalizeExpiresIn(options.resolvedExpiresIn, max);
109
+ }
110
+ const cap = normalizeExpiresIn(options.routeExpiresIn, max);
111
+ if (options.requested == null) return cap;
112
+ return Math.min(normalizeExpiresIn(options.requested, max), cap);
113
+ }
105
114
 
106
115
  // src/helpers/logger.ts
107
116
  var defaultLogger = {
@@ -398,6 +407,15 @@ async function openStoredTarget(config, input, request, feature) {
398
407
  stored: storedObjectContext(request, route, target.key)
399
408
  };
400
409
  }
410
+ async function objectExists(client, bucket, key) {
411
+ try {
412
+ await client.send(new HeadObjectCommand({ Bucket: bucket, Key: key }));
413
+ return true;
414
+ } catch (err) {
415
+ if (isAwsNotFound(err)) return false;
416
+ throw err;
417
+ }
418
+ }
401
419
  async function headObjectOrNotFound(client, bucket, key) {
402
420
  return sendOrObjectNotFound(
403
421
  () => client.send(new HeadObjectCommand({ Bucket: bucket, Key: key }))
@@ -451,6 +469,15 @@ function listedPartsByteSize(parts, excludePartNumber) {
451
469
  }
452
470
  return total;
453
471
  }
472
+ function applyInlineTypes(inlineTypes, input) {
473
+ if (!inlineTypes) return { disposition: input.disposition };
474
+ return resolveInlineDisposition({
475
+ contentType: input.contentType,
476
+ fileName: input.fileName ?? fileNameFromKey(input.key),
477
+ allow: inlineTypes,
478
+ requested: input.disposition
479
+ });
480
+ }
454
481
  async function finalizeConfirmedObject(client, bucket, key, input) {
455
482
  const { config, route, stored, head, uploadId, acl } = input;
456
483
  const rawMetadata = head.Metadata ?? {};
@@ -585,7 +612,7 @@ var confirm = createS3Endpoint(
585
612
  return handleConfirm(ctx.context.config, ctx.body, ctx.context.request);
586
613
  }
587
614
  );
588
- async function handleDelete(config, input, request) {
615
+ async function deleteStoredObject(config, input, request) {
589
616
  const { route, key, bucket, stored } = await openStoredTarget(
590
617
  config,
591
618
  input,
@@ -593,34 +620,30 @@ async function handleDelete(config, input, request) {
593
620
  "delete"
594
621
  );
595
622
  await runHook(route.delete.guard, stored);
596
- await headObjectOrNotFound(route.client, bucket, key);
597
- await route.client.send(
598
- new DeleteObjectCommand({ Bucket: bucket, Key: key })
623
+ const existed = await objectExists(route.client, bucket, key);
624
+ if (existed) {
625
+ await route.client.send(
626
+ new DeleteObjectCommand({ Bucket: bucket, Key: key })
627
+ );
628
+ }
629
+ await runLifecycleHook(
630
+ route.delete.onDeleted,
631
+ { ...stored, existed },
632
+ config
599
633
  );
600
- await runLifecycleHook(route.delete.onDeleted, stored, config);
601
- return { success: true, bucket, key };
634
+ return { success: true, bucket, key, existed };
602
635
  }
603
636
  var deleteObject = createS3Endpoint(
604
637
  S3_API_ROUTES.delete,
605
638
  { method: "DELETE", query: deleteQuerySchema },
606
639
  async (ctx) => {
607
- return handleDelete(ctx.context.config, ctx.query, ctx.context.request);
640
+ return deleteStoredObject(
641
+ ctx.context.config,
642
+ ctx.query,
643
+ ctx.context.request
644
+ );
608
645
  }
609
646
  );
610
- async function deleteOne(config, routeName, key, request) {
611
- const { route, bucket, stored } = await openStoredTarget(
612
- config,
613
- { route: routeName, key },
614
- request,
615
- "delete"
616
- );
617
- await runHook(route.delete.guard, stored);
618
- await headObjectOrNotFound(route.client, bucket, stored.key);
619
- await route.client.send(
620
- new DeleteObjectCommand({ Bucket: bucket, Key: stored.key })
621
- );
622
- await runLifecycleHook(route.delete.onDeleted, stored, config);
623
- }
624
647
  var deleteBatch = createS3Endpoint(
625
648
  S3_API_ROUTES.deleteBatch,
626
649
  { method: "POST", body: deleteBatchBodySchema },
@@ -630,8 +653,12 @@ var deleteBatch = createS3Endpoint(
630
653
  const results = [];
631
654
  for (const key of ctx.body.keys) {
632
655
  try {
633
- await deleteOne(config, ctx.body.route, key, request);
634
- results.push({ key, success: true });
656
+ const { existed } = await deleteStoredObject(
657
+ config,
658
+ { route: ctx.body.route, key },
659
+ request
660
+ );
661
+ results.push({ key, success: true, existed });
635
662
  } catch (err) {
636
663
  results.push({
637
664
  key,
@@ -664,33 +691,44 @@ async function handleDownload(config, input, request) {
664
691
  const resolved = await route.download.resolve?.({
665
692
  ...stored,
666
693
  fileName: input.fileName,
667
- disposition: input.disposition ?? route.download.disposition
694
+ disposition: input.disposition ?? route.download.disposition,
695
+ expiresIn: input.expiresIn
668
696
  });
669
697
  const fileName = resolved?.fileName ?? input.fileName;
670
698
  const disposition = resolved?.disposition ?? input.disposition ?? route.download.disposition ?? "attachment";
671
- const expiresIn = normalizeExpiresIn(
672
- resolved?.expiresIn ?? route.download.expiresIn,
673
- config.maxExpiresIn
674
- );
699
+ const mode = route.download.mode ?? "presign";
700
+ const expiresIn = mode === "proxy" ? 0 : clampDownloadExpiresIn({
701
+ requested: input.expiresIn,
702
+ routeExpiresIn: route.download.expiresIn,
703
+ resolvedExpiresIn: resolved?.expiresIn,
704
+ maxExpiresIn: config.maxExpiresIn
705
+ });
675
706
  await runHook(route.download.guard, {
676
707
  ...stored,
677
708
  fileName,
678
- disposition
709
+ disposition,
710
+ expiresIn
679
711
  });
680
- await headObjectOrNotFound(route.client, bucket, key);
681
- const mode = route.download.mode ?? "presign";
682
- const contentDisposition = fileName ? buildContentDisposition(fileName, disposition) : disposition;
712
+ const head = await headObjectOrNotFound(route.client, bucket, key);
713
+ const signed = applyInlineTypes(route.download.inlineTypes, {
714
+ key,
715
+ fileName,
716
+ disposition,
717
+ contentType: head.ContentType
718
+ });
719
+ const contentDisposition = fileName ? buildContentDisposition(fileName, signed.disposition) : signed.disposition;
683
720
  const url = mode === "proxy" ? fileUrl(request, config.basePath ?? "/api/s3", {
684
721
  route: input.route,
685
722
  key,
686
723
  fileName,
687
- disposition
724
+ disposition: signed.disposition
688
725
  }) : await getSignedUrl(
689
726
  route.client,
690
727
  new GetObjectCommand({
691
728
  Bucket: bucket,
692
729
  Key: key,
693
- ResponseContentDisposition: contentDisposition
730
+ ResponseContentDisposition: contentDisposition,
731
+ ResponseContentType: signed.contentType
694
732
  }),
695
733
  { expiresIn }
696
734
  );
@@ -700,7 +738,7 @@ async function handleDownload(config, input, request) {
700
738
  ...stored,
701
739
  fileName,
702
740
  url,
703
- expiresIn: mode === "proxy" ? 0 : expiresIn
741
+ expiresIn
704
742
  },
705
743
  config
706
744
  );
@@ -708,9 +746,9 @@ async function handleDownload(config, input, request) {
708
746
  bucket,
709
747
  key,
710
748
  url,
711
- expiresIn: mode === "proxy" ? 0 : expiresIn,
749
+ expiresIn,
712
750
  mode,
713
- disposition
751
+ disposition: signed.disposition
714
752
  };
715
753
  }
716
754
  var download = createS3Endpoint(
@@ -731,11 +769,13 @@ function catalogUpload(upload2) {
731
769
  ...upload2.replace ? { replace: upload2.replace } : {}
732
770
  };
733
771
  }
734
- function catalogDownload(download2) {
772
+ function catalogDownload(download2, maxExpiresIn) {
735
773
  if (!isEnabled(download2)) return { enabled: false };
736
774
  return {
737
775
  enabled: true,
776
+ expiresIn: normalizeExpiresIn(download2.expiresIn, maxExpiresIn),
738
777
  ...download2.disposition ? { disposition: download2.disposition } : {},
778
+ ...download2.inlineTypes ? { inlineTypes: [...download2.inlineTypes] } : {},
739
779
  ...download2.mode ? { mode: download2.mode } : {}
740
780
  };
741
781
  }
@@ -744,7 +784,7 @@ function buildRouteCatalog(config) {
744
784
  for (const [name, route] of Object.entries(config.routes)) {
745
785
  routes[name] = {
746
786
  upload: catalogUpload(route.upload),
747
- download: catalogDownload(route.download),
787
+ download: catalogDownload(route.download, config.maxExpiresIn),
748
788
  delete: isEnabled(route.delete) ? { enabled: true } : { enabled: false }
749
789
  };
750
790
  }
@@ -776,13 +816,20 @@ async function handleFile(config, input, request) {
776
816
  fileName,
777
817
  disposition
778
818
  });
779
- await headObjectOrNotFound(route.client, bucket, key);
819
+ const head = await headObjectOrNotFound(route.client, bucket, key);
820
+ const signed = applyInlineTypes(route.download.inlineTypes, {
821
+ key,
822
+ fileName,
823
+ disposition,
824
+ contentType: head.ContentType
825
+ });
826
+ const contentDisposition = fileName ? buildContentDisposition(fileName, signed.disposition) : signed.disposition;
780
827
  const result = await sendOrObjectNotFound(
781
828
  () => route.client.send(
782
829
  new GetObjectCommand({
783
830
  Bucket: bucket,
784
831
  Key: key,
785
- ResponseContentDisposition: fileName ? buildContentDisposition(fileName, disposition) : disposition
832
+ ResponseContentDisposition: contentDisposition
786
833
  })
787
834
  )
788
835
  );
@@ -790,11 +837,12 @@ async function handleFile(config, input, request) {
790
837
  if (!body) throw errors.objectNotFound();
791
838
  const stream = "transformToWebStream" in body && typeof body.transformToWebStream === "function" ? body.transformToWebStream() : body;
792
839
  const headers = new Headers();
793
- headers.set("Content-Type", result.ContentType ?? "application/octet-stream");
794
840
  headers.set(
795
- "Content-Disposition",
796
- fileName ? buildContentDisposition(fileName, disposition) : disposition
841
+ "Content-Type",
842
+ signed.contentType ?? result.ContentType ?? "application/octet-stream"
797
843
  );
844
+ headers.set("Content-Disposition", contentDisposition);
845
+ headers.set("X-Content-Type-Options", "nosniff");
798
846
  if (typeof result.ContentLength === "number") {
799
847
  headers.set("Content-Length", String(result.ContentLength));
800
848
  }