@strapi/provider-upload-aws-s3 5.12.1 → 5.12.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.
package/dist/index.js CHANGED
@@ -4,98 +4,7 @@ var fp = require('lodash/fp');
4
4
  var clientS3 = require('@aws-sdk/client-s3');
5
5
  var s3RequestPresigner = require('@aws-sdk/s3-request-presigner');
6
6
  var libStorage = require('@aws-sdk/lib-storage');
7
-
8
- const ENDPOINT_PATTERN = /^(.+\.)?s3[.-]([a-z0-9-]+)\./;
9
- function isUrlFromBucket(fileUrl, bucketName, baseUrl = '') {
10
- const url = new URL(fileUrl);
11
- // Check if the file URL is using a base URL (e.g. a CDN).
12
- // In this case do not sign the URL.
13
- if (baseUrl) {
14
- return false;
15
- }
16
- const { bucket } = getBucketFromAwsUrl(fileUrl);
17
- if (bucket) {
18
- return bucket === bucketName;
19
- }
20
- // File URL might be of an S3-compatible provider. (or an invalid URL)
21
- // In this case, check if the bucket name appears in the URL host or path.
22
- // e.g. https://minio.example.com/bucket-name/object-key
23
- // e.g. https://bucket.nyc3.digitaloceanspaces.com/folder/img.png
24
- return url.host.startsWith(`${bucketName}.`) || url.pathname.includes(`/${bucketName}/`);
25
- }
26
- /**
27
- * Parse the bucket name from a URL.
28
- * See all URL formats in https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-bucket-intro.html
29
- *
30
- * @param {string} fileUrl - the URL to parse
31
- * @returns {object} result
32
- * @returns {string} result.bucket - the bucket name
33
- * @returns {string} result.err - if any
34
- */ function getBucketFromAwsUrl(fileUrl) {
35
- const url = new URL(fileUrl);
36
- // S3://<bucket-name>/<key>
37
- if (url.protocol === 's3:') {
38
- const bucket = url.host;
39
- if (!bucket) {
40
- return {
41
- err: `Invalid S3 url: no bucket: ${url}`
42
- };
43
- }
44
- return {
45
- bucket
46
- };
47
- }
48
- if (!url.host) {
49
- return {
50
- err: `Invalid S3 url: no hostname: ${url}`
51
- };
52
- }
53
- const matches = url.host.match(ENDPOINT_PATTERN);
54
- if (!matches) {
55
- return {
56
- err: `Invalid S3 url: hostname does not appear to be a valid S3 endpoint: ${url}`
57
- };
58
- }
59
- const prefix = matches[1];
60
- // https://s3.amazonaws.com/<bucket-name>
61
- if (!prefix) {
62
- if (url.pathname === '/') {
63
- return {
64
- bucket: null
65
- };
66
- }
67
- const index = url.pathname.indexOf('/', 1);
68
- // https://s3.amazonaws.com/<bucket-name>
69
- if (index === -1) {
70
- return {
71
- bucket: url.pathname.substring(1)
72
- };
73
- }
74
- // https://s3.amazonaws.com/<bucket-name>/
75
- if (index === url.pathname.length - 1) {
76
- return {
77
- bucket: url.pathname.substring(1, index)
78
- };
79
- }
80
- // https://s3.amazonaws.com/<bucket-name>/key
81
- return {
82
- bucket: url.pathname.substring(1, index)
83
- };
84
- }
85
- // https://<bucket-name>.s3.amazonaws.com/
86
- return {
87
- bucket: prefix.substring(0, prefix.length - 1)
88
- };
89
- }
90
- const extractCredentials = (options)=>{
91
- if (options.s3Options?.credentials) {
92
- return {
93
- accessKeyId: options.s3Options.credentials.accessKeyId,
94
- secretAccessKey: options.s3Options.credentials.secretAccessKey
95
- };
96
- }
97
- return null;
98
- };
7
+ var utils = require('./utils.js');
99
8
 
100
9
  const assertUrlProtocol = (url)=>{
101
10
  // Regex to test protocol like "http://", "https://"
@@ -105,7 +14,7 @@ const getConfig = ({ baseUrl, rootPath, s3Options, ...legacyS3Options })=>{
105
14
  if (Object.keys(legacyS3Options).length > 0) {
106
15
  process.emitWarning("S3 configuration options passed at root level of the plugin's providerOptions is deprecated and will be removed in a future release. Please wrap them inside the 's3Options:{}' property.");
107
16
  }
108
- const credentials = extractCredentials({
17
+ const credentials = utils.extractCredentials({
109
18
  s3Options,
110
19
  ...legacyS3Options
111
20
  });
@@ -164,7 +73,7 @@ var index = {
164
73
  },
165
74
  async getSignedUrl (file, customParams) {
166
75
  // Do not sign the url if it does not come from the same bucket.
167
- if (!isUrlFromBucket(file.url, config.params.Bucket, baseUrl)) {
76
+ if (!utils.isUrlFromBucket(file.url, config.params.Bucket, baseUrl)) {
168
77
  return {
169
78
  url: file.url
170
79
  };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sources":["../src/utils.ts","../src/index.ts"],"sourcesContent":["import type { AwsCredentialIdentity } from '@aws-sdk/types';\nimport type { InitOptions } from '.';\n\nconst ENDPOINT_PATTERN = /^(.+\\.)?s3[.-]([a-z0-9-]+)\\./;\n\ninterface BucketInfo {\n bucket?: string | null;\n err?: string;\n}\n\nexport function isUrlFromBucket(fileUrl: string, bucketName: string, baseUrl = ''): boolean {\n const url = new URL(fileUrl);\n\n // Check if the file URL is using a base URL (e.g. a CDN).\n // In this case do not sign the URL.\n if (baseUrl) {\n return false;\n }\n\n const { bucket } = getBucketFromAwsUrl(fileUrl);\n\n if (bucket) {\n return bucket === bucketName;\n }\n\n // File URL might be of an S3-compatible provider. (or an invalid URL)\n // In this case, check if the bucket name appears in the URL host or path.\n // e.g. https://minio.example.com/bucket-name/object-key\n // e.g. https://bucket.nyc3.digitaloceanspaces.com/folder/img.png\n return url.host.startsWith(`${bucketName}.`) || url.pathname.includes(`/${bucketName}/`);\n}\n\n/**\n * Parse the bucket name from a URL.\n * See all URL formats in https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-bucket-intro.html\n *\n * @param {string} fileUrl - the URL to parse\n * @returns {object} result\n * @returns {string} result.bucket - the bucket name\n * @returns {string} result.err - if any\n */\nfunction getBucketFromAwsUrl(fileUrl: string): BucketInfo {\n const url = new URL(fileUrl);\n\n // S3://<bucket-name>/<key>\n if (url.protocol === 's3:') {\n const bucket = url.host;\n\n if (!bucket) {\n return { err: `Invalid S3 url: no bucket: ${url}` };\n }\n return { bucket };\n }\n\n if (!url.host) {\n return { err: `Invalid S3 url: no hostname: ${url}` };\n }\n\n const matches = url.host.match(ENDPOINT_PATTERN);\n if (!matches) {\n return { err: `Invalid S3 url: hostname does not appear to be a valid S3 endpoint: ${url}` };\n }\n\n const prefix = matches[1];\n // https://s3.amazonaws.com/<bucket-name>\n if (!prefix) {\n if (url.pathname === '/') {\n return { bucket: null };\n }\n\n const index = url.pathname.indexOf('/', 1);\n\n // https://s3.amazonaws.com/<bucket-name>\n if (index === -1) {\n return { bucket: url.pathname.substring(1) };\n }\n\n // https://s3.amazonaws.com/<bucket-name>/\n if (index === url.pathname.length - 1) {\n return { bucket: url.pathname.substring(1, index) };\n }\n\n // https://s3.amazonaws.com/<bucket-name>/key\n return { bucket: url.pathname.substring(1, index) };\n }\n\n // https://<bucket-name>.s3.amazonaws.com/\n return { bucket: prefix.substring(0, prefix.length - 1) };\n}\n\nexport const extractCredentials = (options: InitOptions): AwsCredentialIdentity | null => {\n if (options.s3Options?.credentials) {\n return {\n accessKeyId: options.s3Options.credentials.accessKeyId,\n secretAccessKey: options.s3Options.credentials.secretAccessKey,\n };\n }\n return null;\n};\n","import type { ReadStream } from 'node:fs';\nimport { getOr } from 'lodash/fp';\nimport {\n S3Client,\n GetObjectCommand,\n DeleteObjectCommand,\n DeleteObjectCommandOutput,\n PutObjectCommandInput,\n CompleteMultipartUploadCommandOutput,\n AbortMultipartUploadCommandOutput,\n S3ClientConfig,\n ObjectCannedACL,\n} from '@aws-sdk/client-s3';\nimport type { AwsCredentialIdentity } from '@aws-sdk/types';\nimport { getSignedUrl } from '@aws-sdk/s3-request-presigner';\nimport { Upload } from '@aws-sdk/lib-storage';\nimport { extractCredentials, isUrlFromBucket } from './utils';\n\nexport interface File {\n name: string;\n alternativeText?: string;\n caption?: string;\n width?: number;\n height?: number;\n formats?: Record<string, unknown>;\n hash: string;\n ext?: string;\n mime: string;\n size: number;\n sizeInBytes: number;\n url: string;\n previewUrl?: string;\n path?: string;\n provider?: string;\n provider_metadata?: Record<string, unknown>;\n stream?: ReadStream;\n buffer?: Buffer;\n}\n\nexport type UploadCommandOutput = (\n | CompleteMultipartUploadCommandOutput\n | AbortMultipartUploadCommandOutput\n) & {\n Location: string;\n};\n\nexport interface AWSParams {\n Bucket: string; // making it required\n ACL?: ObjectCannedACL;\n signedUrlExpires?: number;\n}\n\nexport interface DefaultOptions extends S3ClientConfig {\n // TODO Remove this in V5\n accessKeyId?: AwsCredentialIdentity['accessKeyId'];\n secretAccessKey?: AwsCredentialIdentity['secretAccessKey'];\n // Keep this for V5\n credentials?: AwsCredentialIdentity;\n params?: AWSParams;\n [k: string]: any;\n}\n\nexport type InitOptions = (DefaultOptions | { s3Options: DefaultOptions }) & {\n baseUrl?: string;\n rootPath?: string;\n [k: string]: any;\n};\n\nconst assertUrlProtocol = (url: string) => {\n // Regex to test protocol like \"http://\", \"https://\"\n return /^\\w*:\\/\\//.test(url);\n};\n\nconst getConfig = ({ baseUrl, rootPath, s3Options, ...legacyS3Options }: InitOptions) => {\n if (Object.keys(legacyS3Options).length > 0) {\n process.emitWarning(\n \"S3 configuration options passed at root level of the plugin's providerOptions is deprecated and will be removed in a future release. Please wrap them inside the 's3Options:{}' property.\"\n );\n }\n const credentials = extractCredentials({ s3Options, ...legacyS3Options });\n const config = {\n ...s3Options,\n ...legacyS3Options,\n ...(credentials ? { credentials } : {}),\n };\n\n config.params.ACL = getOr(ObjectCannedACL.public_read, ['params', 'ACL'], config);\n\n return config;\n};\n\nexport default {\n init({ baseUrl, rootPath, s3Options, ...legacyS3Options }: InitOptions) {\n // TODO V5 change config structure to avoid having to do this\n const config = getConfig({ baseUrl, rootPath, s3Options, ...legacyS3Options });\n const s3Client = new S3Client(config);\n const filePrefix = rootPath ? `${rootPath.replace(/\\/+$/, '')}/` : '';\n\n const getFileKey = (file: File) => {\n const path = file.path ? `${file.path}/` : '';\n return `${filePrefix}${path}${file.hash}${file.ext}`;\n };\n\n const upload = async (file: File, customParams: Partial<PutObjectCommandInput> = {}) => {\n const fileKey = getFileKey(file);\n const uploadObj = new Upload({\n client: s3Client,\n params: {\n Bucket: config.params.Bucket,\n Key: fileKey,\n Body: file.stream || Buffer.from(file.buffer as any, 'binary'),\n ACL: config.params.ACL,\n ContentType: file.mime,\n ...customParams,\n },\n });\n\n const upload = (await uploadObj.done()) as UploadCommandOutput;\n\n if (assertUrlProtocol(upload.Location)) {\n file.url = baseUrl ? `${baseUrl}/${fileKey}` : upload.Location;\n } else {\n // Default protocol to https protocol\n file.url = `https://${upload.Location}`;\n }\n };\n\n return {\n isPrivate() {\n return config.params.ACL === 'private';\n },\n\n async getSignedUrl(file: File, customParams: any): Promise<{ url: string }> {\n // Do not sign the url if it does not come from the same bucket.\n if (!isUrlFromBucket(file.url, config.params.Bucket, baseUrl)) {\n return { url: file.url };\n }\n const fileKey = getFileKey(file);\n\n const url = await getSignedUrl(\n // @ts-expect-error - TODO fix client type\n s3Client,\n new GetObjectCommand({\n Bucket: config.params.Bucket,\n Key: fileKey,\n ...customParams,\n }),\n {\n expiresIn: getOr(15 * 60, ['params', 'signedUrlExpires'], config),\n }\n );\n\n return { url };\n },\n uploadStream(file: File, customParams = {}) {\n return upload(file, customParams);\n },\n upload(file: File, customParams = {}) {\n return upload(file, customParams);\n },\n delete(file: File, customParams = {}): Promise<DeleteObjectCommandOutput> {\n const command = new DeleteObjectCommand({\n Bucket: config.params.Bucket,\n Key: getFileKey(file),\n ...customParams,\n });\n return s3Client.send(command);\n },\n };\n },\n};\n"],"names":["ENDPOINT_PATTERN","isUrlFromBucket","fileUrl","bucketName","baseUrl","url","URL","bucket","getBucketFromAwsUrl","host","startsWith","pathname","includes","protocol","err","matches","match","prefix","index","indexOf","substring","length","extractCredentials","options","s3Options","credentials","accessKeyId","secretAccessKey","assertUrlProtocol","test","getConfig","rootPath","legacyS3Options","Object","keys","process","emitWarning","config","params","ACL","getOr","ObjectCannedACL","public_read","init","s3Client","S3Client","filePrefix","replace","getFileKey","file","path","hash","ext","upload","customParams","fileKey","uploadObj","Upload","client","Bucket","Key","Body","stream","Buffer","from","buffer","ContentType","mime","done","Location","isPrivate","getSignedUrl","GetObjectCommand","expiresIn","uploadStream","delete","command","DeleteObjectCommand","send"],"mappings":";;;;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AOD,OAAOJ,IAAMK,EAAAA,YAAAA,CAAAA;AACtB,aAAA;AACAqB,YAAAA,MAAAA,CAAAA,CAAO1B,IAAU,EAAEK,YAAe,GAAA,EAAE,EAAA;gBAClC,MAAMsB,OAAAA,GAAU,IAAIC,4BAAoB,CAAA;oBACtClB,MAAQtB,EAAAA,MAAAA,CAAOC,MAAM,CAACqB,MAAM;AAC5BC,oBAAAA,GAAAA,EAAKZ,UAAWC,CAAAA,IAAAA,CAAAA;AAChB,oBAAA,GAAGK;AACL,iBAAA,CAAA;gBACA,OAAOV,QAAAA,CAASkC,IAAI,CAACF,OAAAA,CAAAA;AACvB;AACF,SAAA;AACF;AACF,CAAE;;;;"}
1
+ {"version":3,"file":"index.js","sources":["../src/index.ts"],"sourcesContent":["import type { ReadStream } from 'node:fs';\nimport { getOr } from 'lodash/fp';\nimport {\n S3Client,\n GetObjectCommand,\n DeleteObjectCommand,\n DeleteObjectCommandOutput,\n PutObjectCommandInput,\n CompleteMultipartUploadCommandOutput,\n AbortMultipartUploadCommandOutput,\n S3ClientConfig,\n ObjectCannedACL,\n} from '@aws-sdk/client-s3';\nimport type { AwsCredentialIdentity } from '@aws-sdk/types';\nimport { getSignedUrl } from '@aws-sdk/s3-request-presigner';\nimport { Upload } from '@aws-sdk/lib-storage';\nimport { extractCredentials, isUrlFromBucket } from './utils';\n\nexport interface File {\n name: string;\n alternativeText?: string;\n caption?: string;\n width?: number;\n height?: number;\n formats?: Record<string, unknown>;\n hash: string;\n ext?: string;\n mime: string;\n size: number;\n sizeInBytes: number;\n url: string;\n previewUrl?: string;\n path?: string;\n provider?: string;\n provider_metadata?: Record<string, unknown>;\n stream?: ReadStream;\n buffer?: Buffer;\n}\n\nexport type UploadCommandOutput = (\n | CompleteMultipartUploadCommandOutput\n | AbortMultipartUploadCommandOutput\n) & {\n Location: string;\n};\n\nexport interface AWSParams {\n Bucket: string; // making it required\n ACL?: ObjectCannedACL;\n signedUrlExpires?: number;\n}\n\nexport interface DefaultOptions extends S3ClientConfig {\n // TODO Remove this in V5\n accessKeyId?: AwsCredentialIdentity['accessKeyId'];\n secretAccessKey?: AwsCredentialIdentity['secretAccessKey'];\n // Keep this for V5\n credentials?: AwsCredentialIdentity;\n params?: AWSParams;\n [k: string]: any;\n}\n\nexport type InitOptions = (DefaultOptions | { s3Options: DefaultOptions }) & {\n baseUrl?: string;\n rootPath?: string;\n [k: string]: any;\n};\n\nconst assertUrlProtocol = (url: string) => {\n // Regex to test protocol like \"http://\", \"https://\"\n return /^\\w*:\\/\\//.test(url);\n};\n\nconst getConfig = ({ baseUrl, rootPath, s3Options, ...legacyS3Options }: InitOptions) => {\n if (Object.keys(legacyS3Options).length > 0) {\n process.emitWarning(\n \"S3 configuration options passed at root level of the plugin's providerOptions is deprecated and will be removed in a future release. Please wrap them inside the 's3Options:{}' property.\"\n );\n }\n const credentials = extractCredentials({ s3Options, ...legacyS3Options });\n const config = {\n ...s3Options,\n ...legacyS3Options,\n ...(credentials ? { credentials } : {}),\n };\n\n config.params.ACL = getOr(ObjectCannedACL.public_read, ['params', 'ACL'], config);\n\n return config;\n};\n\nexport default {\n init({ baseUrl, rootPath, s3Options, ...legacyS3Options }: InitOptions) {\n // TODO V5 change config structure to avoid having to do this\n const config = getConfig({ baseUrl, rootPath, s3Options, ...legacyS3Options });\n const s3Client = new S3Client(config);\n const filePrefix = rootPath ? `${rootPath.replace(/\\/+$/, '')}/` : '';\n\n const getFileKey = (file: File) => {\n const path = file.path ? `${file.path}/` : '';\n return `${filePrefix}${path}${file.hash}${file.ext}`;\n };\n\n const upload = async (file: File, customParams: Partial<PutObjectCommandInput> = {}) => {\n const fileKey = getFileKey(file);\n const uploadObj = new Upload({\n client: s3Client,\n params: {\n Bucket: config.params.Bucket,\n Key: fileKey,\n Body: file.stream || Buffer.from(file.buffer as any, 'binary'),\n ACL: config.params.ACL,\n ContentType: file.mime,\n ...customParams,\n },\n });\n\n const upload = (await uploadObj.done()) as UploadCommandOutput;\n\n if (assertUrlProtocol(upload.Location)) {\n file.url = baseUrl ? `${baseUrl}/${fileKey}` : upload.Location;\n } else {\n // Default protocol to https protocol\n file.url = `https://${upload.Location}`;\n }\n };\n\n return {\n isPrivate() {\n return config.params.ACL === 'private';\n },\n\n async getSignedUrl(file: File, customParams: any): Promise<{ url: string }> {\n // Do not sign the url if it does not come from the same bucket.\n if (!isUrlFromBucket(file.url, config.params.Bucket, baseUrl)) {\n return { url: file.url };\n }\n const fileKey = getFileKey(file);\n\n const url = await getSignedUrl(\n // @ts-expect-error - TODO fix client type\n s3Client,\n new GetObjectCommand({\n Bucket: config.params.Bucket,\n Key: fileKey,\n ...customParams,\n }),\n {\n expiresIn: getOr(15 * 60, ['params', 'signedUrlExpires'], config),\n }\n );\n\n return { url };\n },\n uploadStream(file: File, customParams = {}) {\n return upload(file, customParams);\n },\n upload(file: File, customParams = {}) {\n return upload(file, customParams);\n },\n delete(file: File, customParams = {}): Promise<DeleteObjectCommandOutput> {\n const command = new DeleteObjectCommand({\n Bucket: config.params.Bucket,\n Key: getFileKey(file),\n ...customParams,\n });\n return s3Client.send(command);\n },\n };\n },\n};\n"],"names":["assertUrlProtocol","url","test","getConfig","baseUrl","rootPath","s3Options","legacyS3Options","Object","keys","length","process","emitWarning","credentials","extractCredentials","config","params","ACL","getOr","ObjectCannedACL","public_read","init","s3Client","S3Client","filePrefix","replace","getFileKey","file","path","hash","ext","upload","customParams","fileKey","uploadObj","Upload","client","Bucket","Key","Body","stream","Buffer","from","buffer","ContentType","mime","done","Location","isPrivate","getSignedUrl","isUrlFromBucket","GetObjectCommand","expiresIn","uploadStream","delete","command","DeleteObjectCommand","send"],"mappings":";;;;;;;;AAoEA,MAAMA,oBAAoB,CAACC,GAAAA,GAAAA;;IAEzB,OAAO,WAAA,CAAYC,IAAI,CAACD,GAAAA,CAAAA;AAC1B,CAAA;AAEA,MAAME,SAAAA,GAAY,CAAC,EAAEC,OAAO,EAAEC,QAAQ,EAAEC,SAAS,EAAE,GAAGC,eAA8B,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A,GAAAA,EAAKZ,UAAWC,CAAAA,IAAAA,CAAAA;AAChB,oBAAA,GAAGK;AACL,iBAAA,CAAA;gBACA,OAAOV,QAAAA,CAASmC,IAAI,CAACF,OAAAA,CAAAA;AACvB;AACF,SAAA;AACF;AACF,CAAE;;;;"}
package/dist/index.mjs CHANGED
@@ -2,98 +2,7 @@ import { getOr } from 'lodash/fp';
2
2
  import { S3Client, GetObjectCommand, DeleteObjectCommand, ObjectCannedACL } from '@aws-sdk/client-s3';
3
3
  import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
4
4
  import { Upload } from '@aws-sdk/lib-storage';
5
-
6
- const ENDPOINT_PATTERN = /^(.+\.)?s3[.-]([a-z0-9-]+)\./;
7
- function isUrlFromBucket(fileUrl, bucketName, baseUrl = '') {
8
- const url = new URL(fileUrl);
9
- // Check if the file URL is using a base URL (e.g. a CDN).
10
- // In this case do not sign the URL.
11
- if (baseUrl) {
12
- return false;
13
- }
14
- const { bucket } = getBucketFromAwsUrl(fileUrl);
15
- if (bucket) {
16
- return bucket === bucketName;
17
- }
18
- // File URL might be of an S3-compatible provider. (or an invalid URL)
19
- // In this case, check if the bucket name appears in the URL host or path.
20
- // e.g. https://minio.example.com/bucket-name/object-key
21
- // e.g. https://bucket.nyc3.digitaloceanspaces.com/folder/img.png
22
- return url.host.startsWith(`${bucketName}.`) || url.pathname.includes(`/${bucketName}/`);
23
- }
24
- /**
25
- * Parse the bucket name from a URL.
26
- * See all URL formats in https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-bucket-intro.html
27
- *
28
- * @param {string} fileUrl - the URL to parse
29
- * @returns {object} result
30
- * @returns {string} result.bucket - the bucket name
31
- * @returns {string} result.err - if any
32
- */ function getBucketFromAwsUrl(fileUrl) {
33
- const url = new URL(fileUrl);
34
- // S3://<bucket-name>/<key>
35
- if (url.protocol === 's3:') {
36
- const bucket = url.host;
37
- if (!bucket) {
38
- return {
39
- err: `Invalid S3 url: no bucket: ${url}`
40
- };
41
- }
42
- return {
43
- bucket
44
- };
45
- }
46
- if (!url.host) {
47
- return {
48
- err: `Invalid S3 url: no hostname: ${url}`
49
- };
50
- }
51
- const matches = url.host.match(ENDPOINT_PATTERN);
52
- if (!matches) {
53
- return {
54
- err: `Invalid S3 url: hostname does not appear to be a valid S3 endpoint: ${url}`
55
- };
56
- }
57
- const prefix = matches[1];
58
- // https://s3.amazonaws.com/<bucket-name>
59
- if (!prefix) {
60
- if (url.pathname === '/') {
61
- return {
62
- bucket: null
63
- };
64
- }
65
- const index = url.pathname.indexOf('/', 1);
66
- // https://s3.amazonaws.com/<bucket-name>
67
- if (index === -1) {
68
- return {
69
- bucket: url.pathname.substring(1)
70
- };
71
- }
72
- // https://s3.amazonaws.com/<bucket-name>/
73
- if (index === url.pathname.length - 1) {
74
- return {
75
- bucket: url.pathname.substring(1, index)
76
- };
77
- }
78
- // https://s3.amazonaws.com/<bucket-name>/key
79
- return {
80
- bucket: url.pathname.substring(1, index)
81
- };
82
- }
83
- // https://<bucket-name>.s3.amazonaws.com/
84
- return {
85
- bucket: prefix.substring(0, prefix.length - 1)
86
- };
87
- }
88
- const extractCredentials = (options)=>{
89
- if (options.s3Options?.credentials) {
90
- return {
91
- accessKeyId: options.s3Options.credentials.accessKeyId,
92
- secretAccessKey: options.s3Options.credentials.secretAccessKey
93
- };
94
- }
95
- return null;
96
- };
5
+ import { isUrlFromBucket, extractCredentials } from './utils.mjs';
97
6
 
98
7
  const assertUrlProtocol = (url)=>{
99
8
  // Regex to test protocol like "http://", "https://"
@@ -1 +1 @@
1
- {"version":3,"file":"index.mjs","sources":["../src/utils.ts","../src/index.ts"],"sourcesContent":["import type { AwsCredentialIdentity } from '@aws-sdk/types';\nimport type { InitOptions } from '.';\n\nconst ENDPOINT_PATTERN = /^(.+\\.)?s3[.-]([a-z0-9-]+)\\./;\n\ninterface BucketInfo {\n bucket?: string | null;\n err?: string;\n}\n\nexport function isUrlFromBucket(fileUrl: string, bucketName: string, baseUrl = ''): boolean {\n const url = new URL(fileUrl);\n\n // Check if the file URL is using a base URL (e.g. a CDN).\n // In this case do not sign the URL.\n if (baseUrl) {\n return false;\n }\n\n const { bucket } = getBucketFromAwsUrl(fileUrl);\n\n if (bucket) {\n return bucket === bucketName;\n }\n\n // File URL might be of an S3-compatible provider. (or an invalid URL)\n // In this case, check if the bucket name appears in the URL host or path.\n // e.g. https://minio.example.com/bucket-name/object-key\n // e.g. https://bucket.nyc3.digitaloceanspaces.com/folder/img.png\n return url.host.startsWith(`${bucketName}.`) || url.pathname.includes(`/${bucketName}/`);\n}\n\n/**\n * Parse the bucket name from a URL.\n * See all URL formats in https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-bucket-intro.html\n *\n * @param {string} fileUrl - the URL to parse\n * @returns {object} result\n * @returns {string} result.bucket - the bucket name\n * @returns {string} result.err - if any\n */\nfunction getBucketFromAwsUrl(fileUrl: string): BucketInfo {\n const url = new URL(fileUrl);\n\n // S3://<bucket-name>/<key>\n if (url.protocol === 's3:') {\n const bucket = url.host;\n\n if (!bucket) {\n return { err: `Invalid S3 url: no bucket: ${url}` };\n }\n return { bucket };\n }\n\n if (!url.host) {\n return { err: `Invalid S3 url: no hostname: ${url}` };\n }\n\n const matches = url.host.match(ENDPOINT_PATTERN);\n if (!matches) {\n return { err: `Invalid S3 url: hostname does not appear to be a valid S3 endpoint: ${url}` };\n }\n\n const prefix = matches[1];\n // https://s3.amazonaws.com/<bucket-name>\n if (!prefix) {\n if (url.pathname === '/') {\n return { bucket: null };\n }\n\n const index = url.pathname.indexOf('/', 1);\n\n // https://s3.amazonaws.com/<bucket-name>\n if (index === -1) {\n return { bucket: url.pathname.substring(1) };\n }\n\n // https://s3.amazonaws.com/<bucket-name>/\n if (index === url.pathname.length - 1) {\n return { bucket: url.pathname.substring(1, index) };\n }\n\n // https://s3.amazonaws.com/<bucket-name>/key\n return { bucket: url.pathname.substring(1, index) };\n }\n\n // https://<bucket-name>.s3.amazonaws.com/\n return { bucket: prefix.substring(0, prefix.length - 1) };\n}\n\nexport const extractCredentials = (options: InitOptions): AwsCredentialIdentity | null => {\n if (options.s3Options?.credentials) {\n return {\n accessKeyId: options.s3Options.credentials.accessKeyId,\n secretAccessKey: options.s3Options.credentials.secretAccessKey,\n };\n }\n return null;\n};\n","import type { ReadStream } from 'node:fs';\nimport { getOr } from 'lodash/fp';\nimport {\n S3Client,\n GetObjectCommand,\n DeleteObjectCommand,\n DeleteObjectCommandOutput,\n PutObjectCommandInput,\n CompleteMultipartUploadCommandOutput,\n AbortMultipartUploadCommandOutput,\n S3ClientConfig,\n ObjectCannedACL,\n} from '@aws-sdk/client-s3';\nimport type { AwsCredentialIdentity } from '@aws-sdk/types';\nimport { getSignedUrl } from '@aws-sdk/s3-request-presigner';\nimport { Upload } from '@aws-sdk/lib-storage';\nimport { extractCredentials, isUrlFromBucket } from './utils';\n\nexport interface File {\n name: string;\n alternativeText?: string;\n caption?: string;\n width?: number;\n height?: number;\n formats?: Record<string, unknown>;\n hash: string;\n ext?: string;\n mime: string;\n size: number;\n sizeInBytes: number;\n url: string;\n previewUrl?: string;\n path?: string;\n provider?: string;\n provider_metadata?: Record<string, unknown>;\n stream?: ReadStream;\n buffer?: Buffer;\n}\n\nexport type UploadCommandOutput = (\n | CompleteMultipartUploadCommandOutput\n | AbortMultipartUploadCommandOutput\n) & {\n Location: string;\n};\n\nexport interface AWSParams {\n Bucket: string; // making it required\n ACL?: ObjectCannedACL;\n signedUrlExpires?: number;\n}\n\nexport interface DefaultOptions extends S3ClientConfig {\n // TODO Remove this in V5\n accessKeyId?: AwsCredentialIdentity['accessKeyId'];\n secretAccessKey?: AwsCredentialIdentity['secretAccessKey'];\n // Keep this for V5\n credentials?: AwsCredentialIdentity;\n params?: AWSParams;\n [k: string]: any;\n}\n\nexport type InitOptions = (DefaultOptions | { s3Options: DefaultOptions }) & {\n baseUrl?: string;\n rootPath?: string;\n [k: string]: any;\n};\n\nconst assertUrlProtocol = (url: string) => {\n // Regex to test protocol like \"http://\", \"https://\"\n return /^\\w*:\\/\\//.test(url);\n};\n\nconst getConfig = ({ baseUrl, rootPath, s3Options, ...legacyS3Options }: InitOptions) => {\n if (Object.keys(legacyS3Options).length > 0) {\n process.emitWarning(\n \"S3 configuration options passed at root level of the plugin's providerOptions is deprecated and will be removed in a future release. Please wrap them inside the 's3Options:{}' property.\"\n );\n }\n const credentials = extractCredentials({ s3Options, ...legacyS3Options });\n const config = {\n ...s3Options,\n ...legacyS3Options,\n ...(credentials ? { credentials } : {}),\n };\n\n config.params.ACL = getOr(ObjectCannedACL.public_read, ['params', 'ACL'], config);\n\n return config;\n};\n\nexport default {\n init({ baseUrl, rootPath, s3Options, ...legacyS3Options }: InitOptions) {\n // TODO V5 change config structure to avoid having to do this\n const config = getConfig({ baseUrl, rootPath, s3Options, ...legacyS3Options });\n const s3Client = new S3Client(config);\n const filePrefix = rootPath ? `${rootPath.replace(/\\/+$/, '')}/` : '';\n\n const getFileKey = (file: File) => {\n const path = file.path ? `${file.path}/` : '';\n return `${filePrefix}${path}${file.hash}${file.ext}`;\n };\n\n const upload = async (file: File, customParams: Partial<PutObjectCommandInput> = {}) => {\n const fileKey = getFileKey(file);\n const uploadObj = new Upload({\n client: s3Client,\n params: {\n Bucket: config.params.Bucket,\n Key: fileKey,\n Body: file.stream || Buffer.from(file.buffer as any, 'binary'),\n ACL: config.params.ACL,\n ContentType: file.mime,\n ...customParams,\n },\n });\n\n const upload = (await uploadObj.done()) as UploadCommandOutput;\n\n if (assertUrlProtocol(upload.Location)) {\n file.url = baseUrl ? `${baseUrl}/${fileKey}` : upload.Location;\n } else {\n // Default protocol to https protocol\n file.url = `https://${upload.Location}`;\n }\n };\n\n return {\n isPrivate() {\n return config.params.ACL === 'private';\n },\n\n async getSignedUrl(file: File, customParams: any): Promise<{ url: string }> {\n // Do not sign the url if it does not come from the same bucket.\n if (!isUrlFromBucket(file.url, config.params.Bucket, baseUrl)) {\n return { url: file.url };\n }\n const fileKey = getFileKey(file);\n\n const url = await getSignedUrl(\n // @ts-expect-error - TODO fix client type\n s3Client,\n new GetObjectCommand({\n Bucket: config.params.Bucket,\n Key: fileKey,\n ...customParams,\n }),\n {\n expiresIn: getOr(15 * 60, ['params', 'signedUrlExpires'], config),\n }\n );\n\n return { url };\n },\n uploadStream(file: File, customParams = {}) {\n return upload(file, customParams);\n },\n upload(file: File, customParams = {}) {\n return upload(file, customParams);\n },\n delete(file: File, customParams = {}): Promise<DeleteObjectCommandOutput> {\n const command = new DeleteObjectCommand({\n Bucket: config.params.Bucket,\n Key: getFileKey(file),\n ...customParams,\n });\n return s3Client.send(command);\n },\n };\n },\n};\n"],"names":["ENDPOINT_PATTERN","isUrlFromBucket","fileUrl","bucketName","baseUrl","url","URL","bucket","getBucketFromAwsUrl","host","startsWith","pathname","includes","protocol","err","matches","match","prefix","index","indexOf","substring","length","extractCredentials","options","s3Options","credentials","accessKeyId","secretAccessKey","assertUrlProtocol","test","getConfig","rootPath","legacyS3Options","Object","keys","process","emitWarning","config","params","ACL","getOr","ObjectCannedACL","public_read","init","s3Client","S3Client","filePrefix","replace","getFileKey","file","path","hash","ext","upload","customParams","fileKey","uploadObj","Upload","client","Bucket","Key","Body","stream","Buffer","from","buffer","ContentType","mime","done","Location","isPrivate","getSignedUrl","GetObjectCommand","expiresIn","uploadStream","delete","command","DeleteObjectCommand","send"],"mappings":";;;;;AAGA,MAAMA,gBAAmB,GAAA,8BAAA;AAOlB,SAASC,eAAgBC,CAAAA,OAAe,EAAEC,UAAkB,EAAEC,UAAU,EAAE,EAAA;IAC/E,MAAMC,GAAAA,GAAM,IAAIC,GAAIJ,CAAAA,OAAAA,CAAAA;;;AAIpB,IAAA,IAAIE,OAAS,EAAA;QACX,OAAO,KAAA;AACT;AAEA,IAAA,MAAM,EAAEG,MAAM,EAAE,GAAGC,mBAAoBN,CAAAA,OAAAA,CAAAA;AAEvC,IAAA,IAAIK,MAAQ,EAAA;AACV,QAAA,OAAOA,MAAWJ,KAAAA,UAAAA;AACpB;;;;;IA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AAA;AACF;AACF,CAAE;;;;"}
1
+ {"version":3,"file":"index.mjs","sources":["../src/index.ts"],"sourcesContent":["import type { ReadStream } from 'node:fs';\nimport { getOr } from 'lodash/fp';\nimport {\n S3Client,\n GetObjectCommand,\n DeleteObjectCommand,\n DeleteObjectCommandOutput,\n PutObjectCommandInput,\n CompleteMultipartUploadCommandOutput,\n AbortMultipartUploadCommandOutput,\n S3ClientConfig,\n ObjectCannedACL,\n} from '@aws-sdk/client-s3';\nimport type { AwsCredentialIdentity } from '@aws-sdk/types';\nimport { getSignedUrl } from '@aws-sdk/s3-request-presigner';\nimport { Upload } from '@aws-sdk/lib-storage';\nimport { extractCredentials, isUrlFromBucket } from './utils';\n\nexport interface File {\n name: string;\n alternativeText?: string;\n caption?: string;\n width?: number;\n height?: number;\n formats?: Record<string, unknown>;\n hash: string;\n ext?: string;\n mime: string;\n size: number;\n sizeInBytes: number;\n url: string;\n previewUrl?: string;\n path?: string;\n provider?: string;\n provider_metadata?: Record<string, unknown>;\n stream?: ReadStream;\n buffer?: Buffer;\n}\n\nexport type UploadCommandOutput = (\n | CompleteMultipartUploadCommandOutput\n | AbortMultipartUploadCommandOutput\n) & {\n Location: string;\n};\n\nexport interface AWSParams {\n Bucket: string; // making it required\n ACL?: ObjectCannedACL;\n signedUrlExpires?: number;\n}\n\nexport interface DefaultOptions extends S3ClientConfig {\n // TODO Remove this in V5\n accessKeyId?: AwsCredentialIdentity['accessKeyId'];\n secretAccessKey?: AwsCredentialIdentity['secretAccessKey'];\n // Keep this for V5\n credentials?: AwsCredentialIdentity;\n params?: AWSParams;\n [k: string]: any;\n}\n\nexport type InitOptions = (DefaultOptions | { s3Options: DefaultOptions }) & {\n baseUrl?: string;\n rootPath?: string;\n [k: string]: any;\n};\n\nconst assertUrlProtocol = (url: string) => {\n // Regex to test protocol like \"http://\", \"https://\"\n return /^\\w*:\\/\\//.test(url);\n};\n\nconst getConfig = ({ baseUrl, rootPath, s3Options, ...legacyS3Options }: InitOptions) => {\n if (Object.keys(legacyS3Options).length > 0) {\n process.emitWarning(\n \"S3 configuration options passed at root level of the plugin's providerOptions is deprecated and will be removed in a future release. Please wrap them inside the 's3Options:{}' property.\"\n );\n }\n const credentials = extractCredentials({ s3Options, ...legacyS3Options });\n const config = {\n ...s3Options,\n ...legacyS3Options,\n ...(credentials ? { credentials } : {}),\n };\n\n config.params.ACL = getOr(ObjectCannedACL.public_read, ['params', 'ACL'], config);\n\n return config;\n};\n\nexport default {\n init({ baseUrl, rootPath, s3Options, ...legacyS3Options }: InitOptions) {\n // TODO V5 change config structure to avoid having to do this\n const config = getConfig({ baseUrl, rootPath, s3Options, ...legacyS3Options });\n const s3Client = new S3Client(config);\n const filePrefix = rootPath ? `${rootPath.replace(/\\/+$/, '')}/` : '';\n\n const getFileKey = (file: File) => {\n const path = file.path ? `${file.path}/` : '';\n return `${filePrefix}${path}${file.hash}${file.ext}`;\n };\n\n const upload = async (file: File, customParams: Partial<PutObjectCommandInput> = {}) => {\n const fileKey = getFileKey(file);\n const uploadObj = new Upload({\n client: s3Client,\n params: {\n Bucket: config.params.Bucket,\n Key: fileKey,\n Body: file.stream || Buffer.from(file.buffer as any, 'binary'),\n ACL: config.params.ACL,\n ContentType: file.mime,\n ...customParams,\n },\n });\n\n const upload = (await uploadObj.done()) as UploadCommandOutput;\n\n if (assertUrlProtocol(upload.Location)) {\n file.url = baseUrl ? `${baseUrl}/${fileKey}` : upload.Location;\n } else {\n // Default protocol to https protocol\n file.url = `https://${upload.Location}`;\n }\n };\n\n return {\n isPrivate() {\n return config.params.ACL === 'private';\n },\n\n async getSignedUrl(file: File, customParams: any): Promise<{ url: string }> {\n // Do not sign the url if it does not come from the same bucket.\n if (!isUrlFromBucket(file.url, config.params.Bucket, baseUrl)) {\n return { url: file.url };\n }\n const fileKey = getFileKey(file);\n\n const url = await getSignedUrl(\n // @ts-expect-error - TODO fix client type\n s3Client,\n new GetObjectCommand({\n Bucket: config.params.Bucket,\n Key: fileKey,\n ...customParams,\n }),\n {\n expiresIn: getOr(15 * 60, ['params', 'signedUrlExpires'], config),\n }\n );\n\n return { url };\n },\n uploadStream(file: File, customParams = {}) {\n return upload(file, customParams);\n },\n upload(file: File, customParams = {}) {\n return upload(file, customParams);\n },\n delete(file: File, customParams = {}): Promise<DeleteObjectCommandOutput> {\n const command = new DeleteObjectCommand({\n Bucket: config.params.Bucket,\n Key: getFileKey(file),\n ...customParams,\n });\n return s3Client.send(command);\n },\n };\n },\n};\n"],"names":["assertUrlProtocol","url","test","getConfig","baseUrl","rootPath","s3Options","legacyS3Options","Object","keys","length","process","emitWarning","credentials","extractCredentials","config","params","ACL","getOr","ObjectCannedACL","public_read","init","s3Client","S3Client","filePrefix","replace","getFileKey","file","path","hash","ext","upload","customParams","fileKey","uploadObj","Upload","client","Bucket","Key","Body","stream","Buffer","from","buffer","ContentType","mime","done","Location","isPrivate","getSignedUrl","isUrlFromBucket","GetObjectCommand","expiresIn","uploadStream","delete","command","DeleteObjectCommand","send"],"mappings":";;;;;;AAoEA,MAAMA,oBAAoB,CAACC,GAAAA,GAAAA;;IAEzB,OAAO,WAAA,CAAYC,IAAI,CAACD,GAAAA,CAAAA;AAC1B,CAAA;AAEA,MAAME,SAAAA,GAAY,CAAC,EAAEC,OAAO,EAAEC,QAAQ,EAAEC,SAAS,EAAE,GAAGC,eAA8B,EAAA,GAAA;AAClF,IAAA,IAAIC,OAAOC,IAAI,CAACF,eAAiBG,CAAAA,CAAAA,MAAM,GAAG,CAAG,EAAA;AAC3CC,QAAAA,OAAAA,CAAQC,WAAW,CACjB,2LAAA,CAAA;AAEJ;AACA,IAAA,MAAMC,cAAcC,kBAAmB,CAAA;AAAER,QAAAA,SAAAA;AAAW,QAAA,GAAGC;AAAgB,KAAA,CAAA;AACvE,IAAA,MAAMQ,MAAS,GAAA;AACb,QAAA,GAAGT,SAAS;AACZ,QAAA,GAAGC,eAAe;AAClB,QAAA,GAAIM,WAAc,GAAA;AAAEA,YAAAA;AAAY,SAAA,GAAI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A,IAAI6B,gBAAiB,CAAA;oBACnBd,MAAQtB,EAAAA,MAAAA,CAAOC,MAAM,CAACqB,MAAM;oBAC5BC,GAAKL,EAAAA,OAAAA;AACL,oBAAA,GAAGD;iBAEL,CAAA,EAAA;oBACEoB,SAAWlC,EAAAA,KAAAA,CAAM,KAAK,EAAI,EAAA;AAAC,wBAAA,QAAA;AAAU,wBAAA;qBAAmB,EAAEH,MAAAA;AAC5D,iBAAA,CAAA;gBAGF,OAAO;AAAEd,oBAAAA;AAAI,iBAAA;AACf,aAAA;AACAoD,YAAAA,YAAAA,CAAAA,CAAa1B,IAAU,EAAEK,YAAe,GAAA,EAAE,EAAA;AACxC,gBAAA,OAAOD,OAAOJ,IAAMK,EAAAA,YAAAA,CAAAA;AACtB,aAAA;AACAD,YAAAA,MAAAA,CAAAA,CAAOJ,IAAU,EAAEK,YAAe,GAAA,EAAE,EAAA;AAClC,gBAAA,OAAOD,OAAOJ,IAAMK,EAAAA,YAAAA,CAAAA;AACtB,aAAA;AACAsB,YAAAA,MAAAA,CAAAA,CAAO3B,IAAU,EAAEK,YAAe,GAAA,EAAE,EAAA;gBAClC,MAAMuB,OAAAA,GAAU,IAAIC,mBAAoB,CAAA;oBACtCnB,MAAQtB,EAAAA,MAAAA,CAAOC,MAAM,CAACqB,MAAM;AAC5BC,oBAAAA,GAAAA,EAAKZ,UAAWC,CAAAA,IAAAA,CAAAA;AAChB,oBAAA,GAAGK;AACL,iBAAA,CAAA;gBACA,OAAOV,QAAAA,CAASmC,IAAI,CAACF,OAAAA,CAAAA;AACvB;AACF,SAAA;AACF;AACF,CAAE;;;;"}
package/dist/utils.js ADDED
@@ -0,0 +1,97 @@
1
+ 'use strict';
2
+
3
+ const ENDPOINT_PATTERN = /^(.+\.)?s3[.-]([a-z0-9-]+)\./;
4
+ function isUrlFromBucket(fileUrl, bucketName, baseUrl = '') {
5
+ const url = new URL(fileUrl);
6
+ // Check if the file URL is using a base URL (e.g. a CDN).
7
+ // In this case do not sign the URL.
8
+ if (baseUrl) {
9
+ return false;
10
+ }
11
+ const { bucket } = getBucketFromAwsUrl(fileUrl);
12
+ if (bucket) {
13
+ return bucket === bucketName;
14
+ }
15
+ // File URL might be of an S3-compatible provider. (or an invalid URL)
16
+ // In this case, check if the bucket name appears in the URL host or path.
17
+ // e.g. https://minio.example.com/bucket-name/object-key
18
+ // e.g. https://bucket.nyc3.digitaloceanspaces.com/folder/img.png
19
+ return url.host.startsWith(`${bucketName}.`) || url.pathname.includes(`/${bucketName}/`);
20
+ }
21
+ /**
22
+ * Parse the bucket name from a URL.
23
+ * See all URL formats in https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-bucket-intro.html
24
+ *
25
+ * @param {string} fileUrl - the URL to parse
26
+ * @returns {object} result
27
+ * @returns {string} result.bucket - the bucket name
28
+ * @returns {string} result.err - if any
29
+ */ function getBucketFromAwsUrl(fileUrl) {
30
+ const url = new URL(fileUrl);
31
+ // S3://<bucket-name>/<key>
32
+ if (url.protocol === 's3:') {
33
+ const bucket = url.host;
34
+ if (!bucket) {
35
+ return {
36
+ err: `Invalid S3 url: no bucket: ${url}`
37
+ };
38
+ }
39
+ return {
40
+ bucket
41
+ };
42
+ }
43
+ if (!url.host) {
44
+ return {
45
+ err: `Invalid S3 url: no hostname: ${url}`
46
+ };
47
+ }
48
+ const matches = url.host.match(ENDPOINT_PATTERN);
49
+ if (!matches) {
50
+ return {
51
+ err: `Invalid S3 url: hostname does not appear to be a valid S3 endpoint: ${url}`
52
+ };
53
+ }
54
+ const prefix = matches[1];
55
+ // https://s3.amazonaws.com/<bucket-name>
56
+ if (!prefix) {
57
+ if (url.pathname === '/') {
58
+ return {
59
+ bucket: null
60
+ };
61
+ }
62
+ const index = url.pathname.indexOf('/', 1);
63
+ // https://s3.amazonaws.com/<bucket-name>
64
+ if (index === -1) {
65
+ return {
66
+ bucket: url.pathname.substring(1)
67
+ };
68
+ }
69
+ // https://s3.amazonaws.com/<bucket-name>/
70
+ if (index === url.pathname.length - 1) {
71
+ return {
72
+ bucket: url.pathname.substring(1, index)
73
+ };
74
+ }
75
+ // https://s3.amazonaws.com/<bucket-name>/key
76
+ return {
77
+ bucket: url.pathname.substring(1, index)
78
+ };
79
+ }
80
+ // https://<bucket-name>.s3.amazonaws.com/
81
+ return {
82
+ bucket: prefix.substring(0, prefix.length - 1)
83
+ };
84
+ }
85
+ const extractCredentials = (options)=>{
86
+ if (options.s3Options?.credentials) {
87
+ return {
88
+ accessKeyId: options.s3Options.credentials.accessKeyId,
89
+ secretAccessKey: options.s3Options.credentials.secretAccessKey
90
+ };
91
+ }
92
+ return null;
93
+ };
94
+
95
+ exports.extractCredentials = extractCredentials;
96
+ exports.isUrlFromBucket = isUrlFromBucket;
97
+ //# sourceMappingURL=utils.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.js","sources":["../src/utils.ts"],"sourcesContent":["import type { AwsCredentialIdentity } from '@aws-sdk/types';\nimport type { InitOptions } from '.';\n\nconst ENDPOINT_PATTERN = /^(.+\\.)?s3[.-]([a-z0-9-]+)\\./;\n\ninterface BucketInfo {\n bucket?: string | null;\n err?: string;\n}\n\nexport function isUrlFromBucket(fileUrl: string, bucketName: string, baseUrl = ''): boolean {\n const url = new URL(fileUrl);\n\n // Check if the file URL is using a base URL (e.g. a CDN).\n // In this case do not sign the URL.\n if (baseUrl) {\n return false;\n }\n\n const { bucket } = getBucketFromAwsUrl(fileUrl);\n\n if (bucket) {\n return bucket === bucketName;\n }\n\n // File URL might be of an S3-compatible provider. (or an invalid URL)\n // In this case, check if the bucket name appears in the URL host or path.\n // e.g. https://minio.example.com/bucket-name/object-key\n // e.g. https://bucket.nyc3.digitaloceanspaces.com/folder/img.png\n return url.host.startsWith(`${bucketName}.`) || url.pathname.includes(`/${bucketName}/`);\n}\n\n/**\n * Parse the bucket name from a URL.\n * See all URL formats in https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-bucket-intro.html\n *\n * @param {string} fileUrl - the URL to parse\n * @returns {object} result\n * @returns {string} result.bucket - the bucket name\n * @returns {string} result.err - if any\n */\nfunction getBucketFromAwsUrl(fileUrl: string): BucketInfo {\n const url = new URL(fileUrl);\n\n // S3://<bucket-name>/<key>\n if (url.protocol === 's3:') {\n const bucket = url.host;\n\n if (!bucket) {\n return { err: `Invalid S3 url: no bucket: ${url}` };\n }\n return { bucket };\n }\n\n if (!url.host) {\n return { err: `Invalid S3 url: no hostname: ${url}` };\n }\n\n const matches = url.host.match(ENDPOINT_PATTERN);\n if (!matches) {\n return { err: `Invalid S3 url: hostname does not appear to be a valid S3 endpoint: ${url}` };\n }\n\n const prefix = matches[1];\n // https://s3.amazonaws.com/<bucket-name>\n if (!prefix) {\n if (url.pathname === '/') {\n return { bucket: null };\n }\n\n const index = url.pathname.indexOf('/', 1);\n\n // https://s3.amazonaws.com/<bucket-name>\n if (index === -1) {\n return { bucket: url.pathname.substring(1) };\n }\n\n // https://s3.amazonaws.com/<bucket-name>/\n if (index === url.pathname.length - 1) {\n return { bucket: url.pathname.substring(1, index) };\n }\n\n // https://s3.amazonaws.com/<bucket-name>/key\n return { bucket: url.pathname.substring(1, index) };\n }\n\n // https://<bucket-name>.s3.amazonaws.com/\n return { bucket: prefix.substring(0, prefix.length - 1) };\n}\n\nexport const extractCredentials = (options: InitOptions): AwsCredentialIdentity | null => {\n if (options.s3Options?.credentials) {\n return {\n accessKeyId: options.s3Options.credentials.accessKeyId,\n secretAccessKey: options.s3Options.credentials.secretAccessKey,\n };\n }\n return null;\n};\n"],"names":["ENDPOINT_PATTERN","isUrlFromBucket","fileUrl","bucketName","baseUrl","url","URL","bucket","getBucketFromAwsUrl","host","startsWith","pathname","includes","protocol","err","matches","match","prefix","index","indexOf","substring","length","extractCredentials","options","s3Options","credentials","accessKeyId","secretAccessKey"],"mappings":";;AAGA,MAAMA,gBAAmB,GAAA,8BAAA;AAOlB,SAASC,eAAgBC,CAAAA,OAAe,EAAEC,UAAkB,EAAEC,UAAU,EAAE,EAAA;IAC/E,MAAMC,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./;
2
+ function isUrlFromBucket(fileUrl, bucketName, baseUrl = '') {
3
+ const url = new URL(fileUrl);
4
+ // Check if the file URL is using a base URL (e.g. a CDN).
5
+ // In this case do not sign the URL.
6
+ if (baseUrl) {
7
+ return false;
8
+ }
9
+ const { bucket } = getBucketFromAwsUrl(fileUrl);
10
+ if (bucket) {
11
+ return bucket === bucketName;
12
+ }
13
+ // File URL might be of an S3-compatible provider. (or an invalid URL)
14
+ // In this case, check if the bucket name appears in the URL host or path.
15
+ // e.g. https://minio.example.com/bucket-name/object-key
16
+ // e.g. https://bucket.nyc3.digitaloceanspaces.com/folder/img.png
17
+ return url.host.startsWith(`${bucketName}.`) || url.pathname.includes(`/${bucketName}/`);
18
+ }
19
+ /**
20
+ * Parse the bucket name from a URL.
21
+ * See all URL formats in https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-bucket-intro.html
22
+ *
23
+ * @param {string} fileUrl - the URL to parse
24
+ * @returns {object} result
25
+ * @returns {string} result.bucket - the bucket name
26
+ * @returns {string} result.err - if any
27
+ */ function getBucketFromAwsUrl(fileUrl) {
28
+ const url = new URL(fileUrl);
29
+ // S3://<bucket-name>/<key>
30
+ if (url.protocol === 's3:') {
31
+ const bucket = url.host;
32
+ if (!bucket) {
33
+ return {
34
+ err: `Invalid S3 url: no bucket: ${url}`
35
+ };
36
+ }
37
+ return {
38
+ bucket
39
+ };
40
+ }
41
+ if (!url.host) {
42
+ return {
43
+ err: `Invalid S3 url: no hostname: ${url}`
44
+ };
45
+ }
46
+ const matches = url.host.match(ENDPOINT_PATTERN);
47
+ if (!matches) {
48
+ return {
49
+ err: `Invalid S3 url: hostname does not appear to be a valid S3 endpoint: ${url}`
50
+ };
51
+ }
52
+ const prefix = matches[1];
53
+ // https://s3.amazonaws.com/<bucket-name>
54
+ if (!prefix) {
55
+ if (url.pathname === '/') {
56
+ return {
57
+ bucket: null
58
+ };
59
+ }
60
+ const index = url.pathname.indexOf('/', 1);
61
+ // https://s3.amazonaws.com/<bucket-name>
62
+ if (index === -1) {
63
+ return {
64
+ bucket: url.pathname.substring(1)
65
+ };
66
+ }
67
+ // https://s3.amazonaws.com/<bucket-name>/
68
+ if (index === url.pathname.length - 1) {
69
+ return {
70
+ bucket: url.pathname.substring(1, index)
71
+ };
72
+ }
73
+ // https://s3.amazonaws.com/<bucket-name>/key
74
+ return {
75
+ bucket: url.pathname.substring(1, index)
76
+ };
77
+ }
78
+ // https://<bucket-name>.s3.amazonaws.com/
79
+ return {
80
+ bucket: prefix.substring(0, prefix.length - 1)
81
+ };
82
+ }
83
+ const extractCredentials = (options)=>{
84
+ if (options.s3Options?.credentials) {
85
+ return {
86
+ accessKeyId: options.s3Options.credentials.accessKeyId,
87
+ secretAccessKey: options.s3Options.credentials.secretAccessKey
88
+ };
89
+ }
90
+ return null;
91
+ };
92
+
93
+ export { extractCredentials, isUrlFromBucket };
94
+ //# sourceMappingURL=utils.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"utils.mjs","sources":["../src/utils.ts"],"sourcesContent":["import type { AwsCredentialIdentity } from '@aws-sdk/types';\nimport type { InitOptions } from '.';\n\nconst ENDPOINT_PATTERN = /^(.+\\.)?s3[.-]([a-z0-9-]+)\\./;\n\ninterface BucketInfo {\n bucket?: string | null;\n err?: string;\n}\n\nexport function isUrlFromBucket(fileUrl: string, bucketName: string, baseUrl = ''): boolean {\n const url = new URL(fileUrl);\n\n // Check if the file URL is using a base URL (e.g. a CDN).\n // In this case do not sign the URL.\n if (baseUrl) {\n return false;\n }\n\n const { bucket } = getBucketFromAwsUrl(fileUrl);\n\n if (bucket) {\n return bucket === bucketName;\n }\n\n // File URL might be of an S3-compatible provider. (or an invalid URL)\n // In this case, check if the bucket name appears in the URL host or path.\n // e.g. https://minio.example.com/bucket-name/object-key\n // e.g. https://bucket.nyc3.digitaloceanspaces.com/folder/img.png\n return url.host.startsWith(`${bucketName}.`) || url.pathname.includes(`/${bucketName}/`);\n}\n\n/**\n * Parse the bucket name from a URL.\n * See all URL formats in https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-bucket-intro.html\n *\n * @param {string} fileUrl - the URL to parse\n * @returns {object} result\n * @returns {string} result.bucket - the bucket name\n * @returns {string} result.err - if any\n */\nfunction getBucketFromAwsUrl(fileUrl: string): BucketInfo {\n const url = new URL(fileUrl);\n\n // S3://<bucket-name>/<key>\n if (url.protocol === 's3:') {\n const bucket = url.host;\n\n if (!bucket) {\n return { err: `Invalid S3 url: no bucket: ${url}` };\n }\n return { bucket };\n }\n\n if (!url.host) {\n return { err: `Invalid S3 url: no hostname: ${url}` };\n }\n\n const matches = url.host.match(ENDPOINT_PATTERN);\n if (!matches) {\n return { err: `Invalid S3 url: hostname does not appear to be a valid S3 endpoint: ${url}` };\n }\n\n const prefix = matches[1];\n // https://s3.amazonaws.com/<bucket-name>\n if (!prefix) {\n if (url.pathname === '/') {\n return { bucket: null };\n }\n\n const index = url.pathname.indexOf('/', 1);\n\n // https://s3.amazonaws.com/<bucket-name>\n if (index === -1) {\n return { bucket: url.pathname.substring(1) };\n }\n\n // https://s3.amazonaws.com/<bucket-name>/\n if (index === url.pathname.length - 1) {\n return { bucket: url.pathname.substring(1, index) };\n }\n\n // https://s3.amazonaws.com/<bucket-name>/key\n return { bucket: url.pathname.substring(1, index) };\n }\n\n // https://<bucket-name>.s3.amazonaws.com/\n return { bucket: prefix.substring(0, prefix.length - 1) };\n}\n\nexport const extractCredentials = (options: InitOptions): AwsCredentialIdentity | null => {\n if (options.s3Options?.credentials) {\n return {\n accessKeyId: options.s3Options.credentials.accessKeyId,\n secretAccessKey: options.s3Options.credentials.secretAccessKey,\n };\n }\n return null;\n};\n"],"names":["ENDPOINT_PATTERN","isUrlFromBucket","fileUrl","bucketName","baseUrl","url","URL","bucket","getBucketFromAwsUrl","host","startsWith","pathname","includes","protocol","err","matches","match","prefix","index","indexOf","substring","length","extractCredentials","options","s3Options","credentials","accessKeyId","secretAccessKey"],"mappings":"AAGA,MAAMA,gBAAmB,GAAA,8BA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package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@strapi/provider-upload-aws-s3",
3
- "version": "5.12.1",
3
+ "version": "5.12.2",
4
4
  "description": "AWS S3 provider for strapi upload",
5
5
  "keywords": [
6
6
  "upload",
@@ -55,8 +55,8 @@
55
55
  },
56
56
  "devDependencies": {
57
57
  "@types/jest": "29.5.2",
58
- "eslint-config-custom": "5.12.1",
59
- "tsconfig": "5.12.1"
58
+ "eslint-config-custom": "5.12.2",
59
+ "tsconfig": "5.12.2"
60
60
  },
61
61
  "engines": {
62
62
  "node": ">=18.0.0 <=22.x.x",