-
Notifications
You must be signed in to change notification settings - Fork 310
Expand file tree
/
Copy pathattachments.service.ts
More file actions
547 lines (493 loc) · 15 KB
/
attachments.service.ts
File metadata and controls
547 lines (493 loc) · 15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
import {
CopyObjectCommand,
DeleteObjectCommand,
GetObjectCommand,
PutObjectCommand,
S3Client,
} from '@aws-sdk/client-s3';
import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
import { AttachmentEntityType, AttachmentType, db } from '@db';
import {
BadRequestException,
Injectable,
InternalServerErrorException,
} from '@nestjs/common';
import { randomBytes } from 'crypto';
import { AttachmentResponseDto } from '../tasks/dto/task-responses.dto';
import { UploadAttachmentDto } from './upload-attachment.dto';
import { s3Client } from '@/app/s3';
import { validateFileContent } from '../utils/file-type-validation';
@Injectable()
export class AttachmentsService {
private s3Client: S3Client;
private bucketName: string;
private readonly MAX_FILE_SIZE_BYTES = 100 * 1024 * 1024; // 100MB
private readonly SIGNED_URL_EXPIRY = 900; // 15 minutes
constructor() {
// AWS configuration is validated at startup via ConfigModule
// Safe to access environment variables directly since they're validated
this.bucketName = process.env.APP_AWS_BUCKET_NAME!;
if (!s3Client) {
console.error(
'S3 Client is not initialized. Check AWS S3 configuration.',
);
throw new Error(
'S3 Client is not initialized. Check AWS S3 configuration.',
);
}
this.s3Client = s3Client;
}
/**
* Upload attachment to S3 and create database record
*/
async uploadAttachment(
organizationId: string,
entityId: string,
entityType: AttachmentEntityType,
uploadDto: UploadAttachmentDto,
userId?: string,
): Promise<AttachmentResponseDto> {
try {
// Blocked file extensions for security
const BLOCKED_EXTENSIONS = [
'exe',
'bat',
'cmd',
'com',
'scr',
'msi', // Windows executables
'js',
'vbs',
'vbe',
'wsf',
'wsh',
'ps1', // Scripts
'sh',
'bash',
'zsh', // Shell scripts
'dll',
'sys',
'drv', // System files
'app',
'deb',
'rpm', // Application packages
'jar', // Java archives (can execute)
'pif',
'lnk',
'cpl', // Shortcuts and control panel
'hta',
'reg', // HTML apps and registry
];
// Blocked MIME types for security
const BLOCKED_MIME_TYPES = [
'application/x-msdownload', // .exe
'application/x-msdos-program',
'application/x-executable',
'application/x-sh', // Shell scripts
'application/x-bat', // Batch files
'text/x-sh',
'text/x-python',
'text/x-perl',
'text/x-ruby',
'application/x-httpd-php', // PHP files
'application/x-javascript', // Executable JS (not JSON)
'application/javascript',
'text/javascript',
];
// Validate file extension
const fileExt = uploadDto.fileName.split('.').pop()?.toLowerCase();
if (fileExt && BLOCKED_EXTENSIONS.includes(fileExt)) {
throw new BadRequestException(
`File extension '.${fileExt}' is not allowed for security reasons`,
);
}
// Validate MIME type
if (BLOCKED_MIME_TYPES.includes(uploadDto.fileType.toLowerCase())) {
throw new BadRequestException(
`File type '${uploadDto.fileType}' is not allowed for security reasons`,
);
}
// Validate file size
const fileBuffer = Buffer.from(uploadDto.fileData, 'base64');
if (fileBuffer.length > this.MAX_FILE_SIZE_BYTES) {
throw new BadRequestException(
`File size exceeds maximum allowed size of ${this.MAX_FILE_SIZE_BYTES / (1024 * 1024)}MB`,
);
}
// Validate file content matches declared MIME type
validateFileContent(fileBuffer, uploadDto.fileType, uploadDto.fileName);
// Generate unique file key
const fileId = randomBytes(16).toString('hex');
const sanitizedFileName = this.sanitizeFileName(uploadDto.fileName);
const timestamp = Date.now();
// Special S3 path structure for task items: org_{orgId}/attachments/task-item/{entityType}/{entityId}
let s3Key: string;
if (entityType === 'task_item') {
// For task items, extract entityType and entityId from metadata
// Metadata should contain taskItemEntityType and taskItemEntityId
const taskItemEntityType =
uploadDto.description?.split('|')[0] || 'unknown';
const taskItemEntityId =
uploadDto.description?.split('|')[1] || entityId;
s3Key = `${organizationId}/attachments/task-item/${taskItemEntityType}/${taskItemEntityId}/${timestamp}-${fileId}-${sanitizedFileName}`;
} else {
s3Key = `${organizationId}/attachments/${entityType}/${entityId}/${timestamp}-${fileId}-${sanitizedFileName}`;
}
// Upload to S3
const putCommand = new PutObjectCommand({
Bucket: this.bucketName,
Key: s3Key,
Body: fileBuffer,
ContentType: uploadDto.fileType,
Metadata: {
// S3 metadata becomes HTTP headers (x-amz-meta-*) and must be ASCII without control chars
originalFileName: this.sanitizeHeaderValue(uploadDto.fileName),
organizationId,
entityId,
entityType,
...(userId && { uploadedBy: userId }),
},
});
await this.s3Client.send(putCommand);
// Create database record
const attachment = await db.attachment.create({
data: {
name: uploadDto.fileName,
url: s3Key,
type: this.mapFileTypeToAttachmentType(uploadDto.fileType),
entityId,
entityType,
organizationId,
},
});
// Generate signed URL for immediate access
const downloadUrl = await this.generateSignedUrl(s3Key);
return {
id: attachment.id,
name: attachment.name,
type: attachment.type,
downloadUrl,
createdAt: attachment.createdAt,
size: fileBuffer.length,
};
} catch (error) {
console.error('Error uploading attachment:', error);
if (error instanceof BadRequestException) {
throw error;
}
throw new InternalServerErrorException('Failed to upload attachment');
}
}
/**
* Get all attachments for an entity WITH signed URLs (for backward compatibility)
*/
async getAttachments(
organizationId: string,
entityId: string,
entityType: AttachmentEntityType,
): Promise<AttachmentResponseDto[]> {
const attachments = await db.attachment.findMany({
where: {
organizationId,
entityId,
entityType,
},
orderBy: {
createdAt: 'asc',
},
});
// Generate signed URLs for all attachments
const attachmentsWithUrls = await Promise.all(
attachments.map(async (attachment) => {
const downloadUrl = await this.generateSignedUrl(attachment.url);
return {
id: attachment.id,
name: attachment.name,
type: attachment.type,
downloadUrl,
createdAt: attachment.createdAt,
};
}),
);
return attachmentsWithUrls;
}
/**
* Get attachment metadata WITHOUT signed URLs (for on-demand URL generation)
*/
async getAttachmentMetadata(
organizationId: string,
entityId: string,
entityType: AttachmentEntityType,
): Promise<{ id: string; name: string; type: string; createdAt: Date }[]> {
const attachments = await db.attachment.findMany({
where: {
organizationId,
entityId,
entityType,
},
orderBy: {
createdAt: 'asc',
},
});
return attachments.map((attachment) => ({
id: attachment.id,
name: attachment.name,
type: attachment.type,
createdAt: attachment.createdAt,
}));
}
/**
* Get download URL for an attachment
*/
async getAttachmentDownloadUrl(
organizationId: string,
attachmentId: string,
): Promise<{ downloadUrl: string; expiresIn: number }> {
try {
// Get attachment record
const attachment = await db.attachment.findFirst({
where: {
id: attachmentId,
organizationId,
},
});
if (!attachment) {
throw new BadRequestException('Attachment not found');
}
// Generate signed URL
const downloadUrl = await this.generateSignedUrl(attachment.url);
return {
downloadUrl,
expiresIn: this.SIGNED_URL_EXPIRY,
};
} catch (error) {
console.error('Error generating download URL:', error);
if (error instanceof BadRequestException) {
throw error;
}
throw new InternalServerErrorException('Failed to generate download URL');
}
}
/**
* Get attachment by ID
*/
async getAttachmentById(organizationId: string, attachmentId: string) {
return db.attachment.findFirst({
where: { id: attachmentId, organizationId },
select: { id: true, name: true, type: true },
});
}
/**
* Delete attachment from S3 and database
*/
async deleteAttachment(
organizationId: string,
attachmentId: string,
): Promise<void> {
try {
// Get attachment record
const attachment = await db.attachment.findFirst({
where: {
id: attachmentId,
organizationId,
},
});
if (!attachment) {
throw new BadRequestException('Attachment not found');
}
// Delete from S3
const deleteCommand = new DeleteObjectCommand({
Bucket: this.bucketName,
Key: attachment.url,
});
await this.s3Client.send(deleteCommand);
// Delete from database
await db.attachment.delete({
where: {
id: attachmentId,
organizationId,
},
});
} catch (error) {
console.error('Error deleting attachment:', error);
if (error instanceof BadRequestException) {
throw error;
}
throw new InternalServerErrorException('Failed to delete attachment');
}
}
/**
* Copy a policy PDF to a new S3 key for versioning
*/
async copyPolicyVersionPdf(
sourceKey: string,
destinationKey: string,
): Promise<string | null> {
try {
await this.s3Client.send(
new CopyObjectCommand({
Bucket: this.bucketName,
CopySource: `${this.bucketName}/${sourceKey}`,
Key: destinationKey,
}),
);
return destinationKey;
} catch (error) {
console.error('Error copying policy PDF:', error);
return null;
}
}
/**
* Delete a policy version PDF from S3
*/
async deletePolicyVersionPdf(s3Key: string): Promise<void> {
try {
await this.s3Client.send(
new DeleteObjectCommand({
Bucket: this.bucketName,
Key: s3Key,
}),
);
} catch (error) {
console.error('Error deleting policy PDF:', error);
}
}
/**
* Generate signed URL for file download
*/
private async generateSignedUrl(s3Key: string): Promise<string> {
const getCommand = new GetObjectCommand({
Bucket: this.bucketName,
Key: s3Key,
});
return getSignedUrl(this.s3Client, getCommand, {
expiresIn: this.SIGNED_URL_EXPIRY,
});
}
async uploadToS3(
fileBuffer: Buffer,
fileName: string,
contentType: string,
organizationId: string,
entityType: string,
entityId: string,
): Promise<string> {
const fileId = randomBytes(16).toString('hex');
const sanitizedFileName = this.sanitizeFileName(fileName);
const timestamp = Date.now();
const s3Key = `${organizationId}/attachments/${entityType}/${entityId}/${timestamp}-${fileId}-${sanitizedFileName}`;
const putCommand = new PutObjectCommand({
Bucket: this.bucketName,
Key: s3Key,
Body: fileBuffer,
ContentType: contentType,
Metadata: {
originalFileName: this.sanitizeHeaderValue(fileName),
organizationId,
entityId,
entityType,
},
});
await this.s3Client.send(putCommand);
return s3Key;
}
async getPresignedDownloadUrl(s3Key: string): Promise<string> {
return this.generateSignedUrl(s3Key);
}
/**
* Generate presigned download URL with a custom download filename
*/
async getPresignedDownloadUrlWithFilename(
s3Key: string,
downloadFilename: string,
): Promise<string> {
const sanitizedFilename = this.sanitizeHeaderValue(downloadFilename);
const getCommand = new GetObjectCommand({
Bucket: this.bucketName,
Key: s3Key,
ResponseContentDisposition: `attachment; filename="${sanitizedFilename}"`,
});
return getSignedUrl(this.s3Client, getCommand, {
expiresIn: this.SIGNED_URL_EXPIRY,
});
}
/**
* Generate a presigned URL for viewing a PDF inline in the browser
*/
async getPresignedInlinePdfUrl(s3Key: string): Promise<string> {
const getCommand = new GetObjectCommand({
Bucket: this.bucketName,
Key: s3Key,
ResponseContentDisposition: 'inline',
ResponseContentType: 'application/pdf',
});
return getSignedUrl(this.s3Client, getCommand, {
expiresIn: this.SIGNED_URL_EXPIRY,
});
}
/**
* Upload a buffer to S3 with a specific key (no auto-generated path)
*/
async uploadBuffer(
s3Key: string,
buffer: Buffer,
contentType: string,
): Promise<void> {
const putCommand = new PutObjectCommand({
Bucket: this.bucketName,
Key: s3Key,
Body: buffer,
ContentType: contentType,
});
await this.s3Client.send(putCommand);
}
async getObjectBuffer(s3Key: string): Promise<Buffer> {
const getCommand = new GetObjectCommand({
Bucket: this.bucketName,
Key: s3Key,
});
const response = await this.s3Client.send(getCommand);
const chunks: Uint8Array[] = [];
if (!response.Body) {
throw new InternalServerErrorException('No file data received from S3');
}
for await (const chunk of response.Body as any) {
chunks.push(chunk);
}
return Buffer.concat(chunks);
}
private sanitizeFileName(fileName: string): string {
return fileName.replace(/[^a-zA-Z0-9.-]/g, '_');
}
/**
* Sanitize header value for S3 user metadata (x-amz-meta-*) to avoid invalid characters
* - Remove control characters (\x00-\x1F, \x7F)
* - Replace non-ASCII with '_'
* - Trim whitespace
*/
private sanitizeHeaderValue(value: string): string {
// eslint-disable-next-line no-control-regex
const withoutControls = value.replace(/[\x00-\x1F\x7F]/g, '');
const asciiOnly = withoutControls.replace(/[^\x20-\x7E]/g, '_');
return asciiOnly.trim();
}
/**
* Map MIME type to AttachmentType enum
*/
private mapFileTypeToAttachmentType(fileType: string): AttachmentType {
const type = fileType.split('/')[0];
switch (type) {
case 'image':
return AttachmentType.image;
case 'video':
return AttachmentType.video;
case 'audio':
return AttachmentType.audio;
case 'application':
case 'text':
return AttachmentType.document;
default:
return AttachmentType.other;
}
}
}