|
1
|
import { |
|
2
|
DeleteObjectCommand, |
|
3
|
DeleteObjectsCommand, |
|
4
|
GetObjectCommand, |
|
5
|
ObjectCannedACL, |
|
6
|
PutObjectCommand, |
|
7
|
S3Client, |
|
8
|
S3ClientConfigType, |
|
9
|
} from "@aws-sdk/client-s3" |
|
10
|
import { Upload } from "@aws-sdk/lib-storage" |
|
11
|
import { getSignedUrl } from "@aws-sdk/s3-request-presigner" |
|
12
|
import { |
|
13
|
FileTypes, |
|
14
|
Logger, |
|
15
|
S3FileServiceOptions, |
|
16
|
} from "@medusajs/framework/types" |
|
17
|
import { |
|
18
|
AbstractFileProviderService, |
|
19
|
MedusaError, |
|
20
|
} from "@medusajs/framework/utils" |
|
21
|
import path from "path" |
|
22
|
import { PassThrough, Readable, Writable } from "stream" |
|
23
|
import { ulid } from "ulid" |
|
24
|
|
|
25
|
/** |
|
26
|
* Decodes the string `content` of an uploaded file into a Buffer. |
|
27
|
* |
|
28
|
* Upload inputs arrive as a string that may be base64, UTF-8 text (e.g. a CSV |
|
29
|
* with special characters, see #13649) or a binary/latin1 string (e.g. an image |
|
30
|
* produced via `buffer.toString("binary")`, as the upload docs instruct). |
|
31
|
* Decoding a binary string as UTF-8 corrupts every byte > 127 (a PNG's leading |
|
32
|
* `0x89` becomes `0xC2 0x89`), so the encoding is chosen from the file's MIME |
|
33
|
* type, defaulting to binary for non-text content. |
|
34
|
*/ |
|
35
|
function decodeFileContent(content: string, mimeType?: string): Buffer { |
|
36
|
const decodedBase64 = Buffer.from(content, "base64") |
|
37
|
if (decodedBase64.toString("base64") === content) { |
|
38
|
return decodedBase64 |
|
39
|
} |
|
40
|
|
|
41
|
const isTextContent = |
|
42
|
mimeType?.startsWith("text/") || |
|
43
|
mimeType?.includes("csv") || |
|
44
|
mimeType?.includes("json") || |
|
45
|
mimeType?.includes("xml") |
|
46
|
|
|
47
|
return isTextContent |
|
48
|
? Buffer.from(content, "utf8") |
|
49
|
: Buffer.from(content, "binary") |
|
50
|
} |
|
51
|
|
|
52
|
/** |
|
53
|
* Sanitizes a file path by: |
|
54
|
* - Normalizing slashes to posix format |
|
55
|
* - Stripping leading slashes |
|
56
|
* - Resolving relative path segments (.) |
|
57
|
* - Removing path traversal segments (..) |
|
58
|
*/ |
|
59
|
function sanitizeFilePath(filePath: string): string { |
|
60
|
const cleanPath = filePath.replace(/\\/g, "/").replace(/^\/+/, "") |
|
61
|
const normalizedPath = path.posix.normalize(cleanPath) |
|
62
|
return normalizedPath |
|
63
|
.split("/") |
|
64
|
.filter((segment) => segment !== ".." && segment !== ".") |
|
65
|
.join("/") |
|
66
|
} |
|
67
|
|
|
68
|
type InjectedDependencies = { |
|
69
|
logger: Logger |
|
70
|
} |
|
71
|
|
|
72
|
interface S3FileServiceConfig { |
|
73
|
fileUrl: string |
|
74
|
accessKeyId?: string |
|
75
|
secretAccessKey?: string |
|
76
|
sessionToken?: string |
|
77
|
authenticationMethod?: "access-key" | "s3-iam-role" |
|
78
|
region: string |
|
79
|
bucket: string |
|
80
|
prefix?: string |
|
81
|
endpoint?: string |
|
82
|
cacheControl?: string |
|
83
|
downloadFileDuration?: number |
|
84
|
additionalClientConfig?: Record<string, any> |
|
85
|
acl?: ObjectCannedACL | false |
|
86
|
} |
|
87
|
|
|
88
|
const DEFAULT_UPLOAD_EXPIRATION_DURATION_SECONDS = 60 * 60 |
|
89
|
|
|
90
|
export class S3FileService extends AbstractFileProviderService { |
|
91
|
static identifier = "s3" |
|
92
|
protected config_: S3FileServiceConfig |
|
93
|
protected logger_: Logger |
|
94
|
protected client_: S3Client |
|
95
|
|
|
96
|
constructor({ logger }: InjectedDependencies, options: S3FileServiceOptions) { |
|
97
|
super() |
|
98
|
|
|
99
|
const authenticationMethod = options.authentication_method ?? "access-key" |
|
100
|
|
|
101
|
if ( |
|
102
|
authenticationMethod === "access-key" && |
|
103
|
(!options.access_key_id || !options.secret_access_key) |
|
104
|
) { |
|
105
|
throw new MedusaError( |
|
106
|
MedusaError.Types.INVALID_DATA, |
|
107
|
`Access key ID and secret access key are required when using access key authentication` |
|
108
|
) |
|
109
|
} |
|
110
|
|
|
111
|
this.config_ = { |
|
112
|
fileUrl: options.file_url, |
|
113
|
accessKeyId: options.access_key_id, |
|
114
|
secretAccessKey: options.secret_access_key, |
|
115
|
sessionToken: options.session_token, |
|
116
|
authenticationMethod: authenticationMethod, |
|
117
|
region: options.region, |
|
118
|
bucket: options.bucket, |
|
119
|
prefix: options.prefix ?? "", |
|
120
|
endpoint: options.endpoint, |
|
121
|
cacheControl: options.cache_control ?? "public, max-age=31536000", |
|
122
|
downloadFileDuration: options.download_file_duration ?? 60 * 60, |
|
123
|
additionalClientConfig: options.additional_client_config ?? {}, |
|
124
|
acl: options.acl ?? undefined, |
|
125
|
} |
|
126
|
this.logger_ = logger |
|
127
|
this.client_ = this.getClient() |
|
128
|
} |
|
129
|
|
|
130
|
protected getClient() { |
|
131
|
// If none is provided, the SDK will use the default credentials provider chain, see https://docs.aws.amazon.com/cli/v1/userguide/cli-configure-envvars.html |
|
132
|
const credentials = |
|
133
|
this.config_.authenticationMethod === "access-key" |
|
134
|
? { |
|
135
|
accessKeyId: this.config_.accessKeyId!, |
|
136
|
secretAccessKey: this.config_.secretAccessKey!, |
|
137
|
sessionToken: this.config_.sessionToken, |
|
138
|
} |
|
139
|
: undefined |
|
140
|
|
|
141
|
const config: S3ClientConfigType = { |
|
142
|
credentials, |
|
143
|
region: this.config_.region, |
|
144
|
endpoint: this.config_.endpoint, |
|
145
|
...this.config_.additionalClientConfig, |
|
146
|
} |
|
147
|
|
|
148
|
return new S3Client(config) |
|
149
|
} |
|
150
|
|
|
151
|
/** |
|
152
|
* Resolves the ACL to use for an upload. Returns undefined if ACLs are |
|
153
|
* disabled (config_.acl === false), which causes the SDK to omit the |
|
154
|
* ACL header entirely — required for buckets with BucketOwnerEnforced |
|
155
|
* Object Ownership or Block Public Access enabled. |
|
156
|
* |
|
157
|
* Note: getPresignedUploadUrl only calls this when `access` is explicitly |
|
158
|
* provided. When access is undefined, presigned uploads omit ACL entirely |
|
159
|
* (preserving original behaviour). The `acl` config option targets |
|
160
|
* server-side uploads (upload/getUploadStream) where we control the |
|
161
|
* PutObject call directly. |
|
162
|
*/ |
|
163
|
protected resolveAcl( |
|
164
|
access?: "public" | "private" |
|
165
|
): ObjectCannedACL | undefined { |
|
166
|
if (this.config_.acl === false) { |
|
167
|
return undefined |
|
168
|
} |
|
169
|
if (this.config_.acl) { |
|
170
|
return this.config_.acl |
|
171
|
} |
|
172
|
return access === "public" ? "public-read" : "private" |
|
173
|
} |
|
174
|
|
|
175
|
async upload( |
|
176
|
file: FileTypes.ProviderUploadFileDTO |
|
177
|
): Promise<FileTypes.ProviderFileResultDTO> { |
|
178
|
if (!file) { |
|
179
|
throw new MedusaError(MedusaError.Types.INVALID_DATA, `No file provided`) |
|
180
|
} |
|
181
|
|
|
182
|
if (!file.filename) { |
|
183
|
throw new MedusaError( |
|
184
|
MedusaError.Types.INVALID_DATA, |
|
185
|
`No filename provided` |
|
186
|
) |
|
187
|
} |
|
188
|
|
|
189
|
const sanitizedPath = sanitizeFilePath(file.filename) |
|
190
|
if (!sanitizedPath) { |
|
191
|
throw new MedusaError( |
|
192
|
MedusaError.Types.INVALID_DATA, |
|
193
|
`Invalid filename: ${file.filename}` |
|
194
|
) |
|
195
|
} |
|
196
|
const parsedFilename = path.posix.parse(sanitizedPath) |
|
197
|
|
|
198
|
const fileKey = `${this.config_.prefix}${ |
|
199
|
parsedFilename.dir ? `${parsedFilename.dir}/` : "" |
|
200
|
}${parsedFilename.name}-${ulid()}${parsedFilename.ext}` |
|
201
|
|
|
202
|
const content = decodeFileContent(file.content, file.mimeType) |
|
203
|
|
|
204
|
const command = new PutObjectCommand({ |
|
205
|
// We probably also want to support a separate bucket altogether for private files |
|
206
|
// protected private_bucket_: string |
|
207
|
// protected private_access_key_id_: string |
|
208
|
// protected private_secret_access_key_: string |
|
209
|
|
|
210
|
ACL: this.resolveAcl(file.access as "public" | "private"), |
|
211
|
Bucket: this.config_.bucket, |
|
212
|
Body: content, |
|
213
|
Key: fileKey, |
|
214
|
ContentType: file.mimeType, |
|
215
|
CacheControl: this.config_.cacheControl, |
|
216
|
// Note: We could potentially set the content disposition when uploading, |
|
217
|
// but storing the original filename as metadata should suffice. |
|
218
|
Metadata: { |
|
219
|
"original-filename": encodeURIComponent(file.filename), |
|
220
|
}, |
|
221
|
}) |
|
222
|
|
|
223
|
try { |
|
224
|
await this.client_.send(command) |
|
225
|
} catch (e) { |
|
226
|
this.logger_.error(e) |
|
227
|
throw e |
|
228
|
} |
|
229
|
|
|
230
|
const encodedKey = fileKey.split("/").map(encodeURIComponent).join("/") |
|
231
|
|
|
232
|
return { |
|
233
|
url: `${this.config_.fileUrl}/${encodedKey}`, |
|
234
|
key: fileKey, |
|
235
|
} |
|
236
|
} |
|
237
|
|
|
238
|
async getUploadStream(fileData: FileTypes.ProviderUploadStreamDTO): Promise<{ |
|
239
|
writeStream: Writable |
|
240
|
promise: Promise<FileTypes.ProviderFileResultDTO> |
|
241
|
url: string |
|
242
|
fileKey: string |
|
243
|
}> { |
|
244
|
if (!fileData.filename) { |
|
245
|
throw new MedusaError( |
|
246
|
MedusaError.Types.INVALID_DATA, |
|
247
|
`No filename provided` |
|
248
|
) |
|
249
|
} |
|
250
|
|
|
251
|
const sanitizedPath = sanitizeFilePath(fileData.filename) |
|
252
|
if (!sanitizedPath) { |
|
253
|
throw new MedusaError( |
|
254
|
MedusaError.Types.INVALID_DATA, |
|
255
|
`Invalid filename: ${fileData.filename}` |
|
256
|
) |
|
257
|
} |
|
258
|
const parsedFilename = path.posix.parse(sanitizedPath) |
|
259
|
const fileKey = `${this.config_.prefix}${ |
|
260
|
parsedFilename.dir ? `${parsedFilename.dir}/` : "" |
|
261
|
}${parsedFilename.name}-${ulid()}${parsedFilename.ext}` |
|
262
|
|
|
263
|
const pass = new PassThrough() |
|
264
|
const upload = new Upload({ |
|
265
|
client: this.client_, |
|
266
|
params: { |
|
267
|
ACL: this.resolveAcl(fileData.access as "public" | "private"), |
|
268
|
Bucket: this.config_.bucket, |
|
269
|
Key: fileKey, |
|
270
|
Body: pass, |
|
271
|
ContentType: fileData.mimeType, |
|
272
|
CacheControl: this.config_.cacheControl, |
|
273
|
Metadata: { |
|
274
|
"original-filename": encodeURIComponent(fileData.filename), |
|
275
|
}, |
|
276
|
}, |
|
277
|
}) |
|
278
|
|
|
279
|
const encodedKey = fileKey.split("/").map(encodeURIComponent).join("/") |
|
280
|
|
|
281
|
const promise = upload.done().then(() => ({ |
|
282
|
url: `${this.config_.fileUrl}/${encodedKey}`, |
|
283
|
key: fileKey, |
|
284
|
})) |
|
285
|
|
|
286
|
return { |
|
287
|
writeStream: pass, |
|
288
|
promise, |
|
289
|
url: `${this.config_.fileUrl}/${encodedKey}`, |
|
290
|
fileKey, |
|
291
|
} |
|
292
|
} |
|
293
|
|
|
294
|
async delete( |
|
295
|
files: FileTypes.ProviderDeleteFileDTO | FileTypes.ProviderDeleteFileDTO[] |
|
296
|
): Promise<void> { |
|
297
|
try { |
|
298
|
/** |
|
299
|
* Bulk delete files |
|
300
|
*/ |
|
301
|
if (Array.isArray(files)) { |
|
302
|
await this.client_.send( |
|
303
|
new DeleteObjectsCommand({ |
|
304
|
Bucket: this.config_.bucket, |
|
305
|
Delete: { |
|
306
|
Objects: files.map((file) => ({ |
|
307
|
Key: file.fileKey, |
|
308
|
})), |
|
309
|
Quiet: true, |
|
310
|
}, |
|
311
|
}) |
|
312
|
) |
|
313
|
} else { |
|
314
|
await this.client_.send( |
|
315
|
new DeleteObjectCommand({ |
|
316
|
Bucket: this.config_.bucket, |
|
317
|
Key: files.fileKey, |
|
318
|
}) |
|
319
|
) |
|
320
|
} |
|
321
|
} catch (e) { |
|
322
|
// TODO: Rethrow depending on the error (eg. a file not found error is fine, but a failed request should be rethrown) |
|
323
|
this.logger_.error(e) |
|
324
|
} |
|
325
|
} |
|
326
|
|
|
327
|
async getPresignedDownloadUrl( |
|
328
|
fileData: FileTypes.ProviderGetFileDTO |
|
329
|
): Promise<string> { |
|
330
|
// TODO: Allow passing content disposition when getting a presigned URL |
|
331
|
const command = new GetObjectCommand({ |
|
332
|
Bucket: this.config_.bucket, |
|
333
|
Key: `${fileData.fileKey}`, |
|
334
|
}) |
|
335
|
|
|
336
|
return await getSignedUrl(this.client_ as any, command as any, { |
|
337
|
expiresIn: this.config_.downloadFileDuration, |
|
338
|
}) |
|
339
|
} |
|
340
|
|
|
341
|
// Note: Some providers (eg. AWS S3) allows IAM policies to further restrict what can be uploaded. |
|
342
|
async getPresignedUploadUrl( |
|
343
|
fileData: FileTypes.ProviderGetPresignedUploadUrlDTO |
|
344
|
): Promise<FileTypes.ProviderFileResultDTO> { |
|
345
|
if (!fileData?.filename) { |
|
346
|
throw new MedusaError( |
|
347
|
MedusaError.Types.INVALID_DATA, |
|
348
|
`No filename provided` |
|
349
|
) |
|
350
|
} |
|
351
|
|
|
352
|
const sanitizedFilename = sanitizeFilePath(fileData.filename) |
|
353
|
if (!sanitizedFilename) { |
|
354
|
throw new MedusaError( |
|
355
|
MedusaError.Types.INVALID_DATA, |
|
356
|
`Invalid filename: ${fileData.filename}` |
|
357
|
) |
|
358
|
} |
|
359
|
const fileKey = `${this.config_.prefix}${sanitizedFilename}` |
|
360
|
|
|
361
|
const acl = fileData.access |
|
362
|
? this.resolveAcl(fileData.access as "public" | "private") |
|
363
|
: undefined |
|
364
|
|
|
365
|
// Using content-type, acl, etc. doesn't work with all providers, and some simply ignore it. |
|
366
|
const command = new PutObjectCommand({ |
|
367
|
Bucket: this.config_.bucket, |
|
368
|
ContentType: fileData.mimeType, |
|
369
|
ACL: acl, |
|
370
|
Key: fileKey, |
|
371
|
}) |
|
372
|
|
|
373
|
const signedUrl = await getSignedUrl(this.client_ as any, command as any, { |
|
374
|
expiresIn: |
|
375
|
fileData.expiresIn ?? DEFAULT_UPLOAD_EXPIRATION_DURATION_SECONDS, |
|
376
|
}) |
|
377
|
|
|
378
|
return { |
|
379
|
url: signedUrl, |
|
380
|
key: fileKey, |
|
381
|
} |
|
382
|
} |
|
383
|
|
|
384
|
async getDownloadStream( |
|
385
|
file: FileTypes.ProviderGetFileDTO |
|
386
|
): Promise<Readable> { |
|
387
|
if (!file?.fileKey) { |
|
388
|
throw new MedusaError( |
|
389
|
MedusaError.Types.INVALID_DATA, |
|
390
|
`No fileKey provided` |
|
391
|
) |
|
392
|
} |
|
393
|
|
|
394
|
const fileKey = file.fileKey |
|
395
|
const response = await this.client_.send( |
|
396
|
new GetObjectCommand({ |
|
397
|
Key: fileKey, |
|
398
|
Bucket: this.config_.bucket, |
|
399
|
}) |
|
400
|
) |
|
401
|
|
|
402
|
return response.Body! as Readable |
|
403
|
} |
|
404
|
|
|
405
|
async getAsBuffer(file: FileTypes.ProviderGetFileDTO): Promise<Buffer> { |
|
406
|
if (!file?.fileKey) { |
|
407
|
throw new MedusaError( |
|
408
|
MedusaError.Types.INVALID_DATA, |
|
409
|
`No fileKey provided` |
|
410
|
) |
|
411
|
} |
|
412
|
|
|
413
|
const fileKey = file.fileKey |
|
414
|
const response = await this.client_.send( |
|
415
|
new GetObjectCommand({ |
|
416
|
Key: fileKey, |
|
417
|
Bucket: this.config_.bucket, |
|
418
|
}) |
|
419
|
) |
|
420
|
|
|
421
|
return Buffer.from(await response.Body!.transformToByteArray()) |
|
422
|
} |
|
423
|
} |