forked from bcgov/common-hosted-form-service
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathupload.js
More file actions
218 lines (185 loc) · 7.23 KB
/
Copy pathupload.js
File metadata and controls
218 lines (185 loc) · 7.23 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
const bytes = require('bytes');
const fs = require('fs-extra');
const multer = require('multer');
const os = require('os');
const path = require('path');
const crypto = require('crypto');
const log = require('../../../components/log')(module.filename);
const Problem = require('api-problem');
// Multer stages uploads in a dedicated subdirectory of the OS temp dir (rather
// than the shared temp root) so the upload cleanup sweeper can safely target
// only CHEFS upload temp files and never touch unrelated files in /tmp.
const UPLOADS_SUBDIR = 'chefs-uploads';
// The default staging directory: a dedicated subdir of the OS temp dir. Shared
// by fileSetup() and getFileUploadsDir() so the resolved path is identical
// whether it is read before or after init().
const defaultUploadsDir = () => path.join(fs.realpathSync(os.tmpdir()), UPLOADS_SUBDIR);
// Resolved lazily by getFileUploadsDir() (or explicitly by fileSetup via init()).
// Left unset so a read before init() still returns the correct default rather
// than the bare OS temp dir.
let fileUploadsDir;
let maxFileSize = bytes.parse('25MB');
let maxFileCount = 1;
let storage;
let uploader;
/**
* Helper function to create a Problem instance with status code 400.
* @param {string} detail - The detail message for the Problem.
* @returns {Problem} - A Problem instance with status code 400.
*/
const createBadRequestProblem = (detail) => {
return new Problem(400, { detail });
};
/**
* Unicode-aware filename sanitization
* @param {string} filename - Original filename
* @returns {string} - Safe, international-friendly filename
*/
const sanitizeFilename = (filename) => {
const ext = path.extname(filename);
const nameWithoutExt = path.basename(filename, ext);
let sanitized = nameWithoutExt
.normalize('NFD') // Decompose Unicode (é → e + ´)
.replace(/[\u0300-\u036f]/g, '') // Remove diacritical marks (´ ` ^ ~)
.normalize('NFC') // Recompose what's left
.replace(/[^\p{L}\p{N}_.-]/gu, '_') // Keep letters/numbers in ANY language
.trim();
// SAFE: Collapse multiple underscores using string methods
while (sanitized.includes('__')) {
sanitized = sanitized.replace('__', '_');
}
// SAFE: Remove leading/trailing underscores using while loops
while (sanitized.startsWith('_') || sanitized.startsWith('-')) {
sanitized = sanitized.slice(1);
}
while (sanitized.endsWith('_') || sanitized.endsWith('-')) {
sanitized = sanitized.slice(0, -1);
}
const finalName = sanitized || 'file';
// Add timestamp to prevent collisions
const timestamp = Date.now();
return `${timestamp}_${finalName}${ext}`;
};
const fileSetup = (options) => {
fileUploadsDir = (options && options.dir) || process.env.FILE_UPLOADS_DIR || defaultUploadsDir();
try {
fs.ensureDirSync(fileUploadsDir);
} catch (error) {
log.error(`Error creating file uploads directory '${fileUploadsDir}':`, error);
throw new Error(`Could not create file uploads directory '${fileUploadsDir}'.`);
}
maxFileSize = (options && options.maxFileSize) || process.env.FILE_UPLOADS_MAX_FILE_SIZE || '25MB';
maxFileSize = bytes.parse(maxFileSize);
if (maxFileSize === null) {
throw new Error('Could not determine max file size (bytes) for file uploads.');
}
maxFileCount = (options && options.maxFileCount) || process.env.FILE_UPLOADS_MAX_FILE_COUNT || '1';
maxFileCount = parseInt(maxFileCount);
if (isNaN(maxFileCount)) {
maxFileCount = 1;
}
return { fileUploadsDir, maxFileSize, maxFileCount };
};
const fileUpload = {
init(options) {
let { fileUploadsDir, maxFileSize, maxFileCount } = fileSetup(options);
const formFieldName = (options && options.fieldName) || process.env.FILE_UPLOADS_FIELD_NAME || 'files';
storage = multer.diskStorage({
destination: function (_req, _file, callback) {
callback(null, fileUploadsDir);
},
filename: function (_req, file, callback) {
try {
// Sanitize the filename to handle Unicode characters
const safeFilename = sanitizeFilename(file.originalname);
callback(null, safeFilename);
} catch (error) {
log.error(`Error processing filename: ${file.originalname}`, error);
// Fallback to a safe generated name
const fallbackName = `file_${Date.now()}_${crypto.randomBytes(4).toString('hex')}`;
callback(null, fallbackName);
}
},
});
// Set up the multer, either array for multiple upload, or single for one.
if (maxFileCount > 1) {
uploader = multer({
storage: storage,
limits: { fileSize: maxFileSize, files: maxFileCount },
}).array(formFieldName);
} else {
// Just in case we set a negative number.
maxFileCount = 1;
uploader = multer({
storage: storage,
limits: { fileSize: maxFileSize, files: maxFileCount },
}).single(formFieldName);
}
},
/**
* Gets the directory where the files are uploaded to.
*
* @returns the file uploads directory.
*/
getFileUploadsDir() {
// Fall back to the default if read before init() so callers never receive
// the bare OS temp dir (which the sweeper would not be scoped to).
if (!fileUploadsDir) {
fileUploadsDir = defaultUploadsDir();
}
return fileUploadsDir;
},
async upload(req, res, next) {
try {
if (!uploader) {
const problem = new Problem(500, {
detail: 'File Upload middleware has not been configured.',
});
next(problem);
return;
}
uploader(req, res, (error) => {
let problem;
// Detect multer errors, send back nicer through the middleware stack.
if (error instanceof multer.MulterError) {
switch (error.code) {
case 'LIMIT_FILE_SIZE':
problem = createBadRequestProblem(`Upload file size is limited to ${maxFileSize} bytes`);
break;
case 'LIMIT_FILE_COUNT':
problem = createBadRequestProblem(`Upload is limited to ${maxFileCount} files`);
break;
case 'LIMIT_UNEXPECTED_FILE':
problem = createBadRequestProblem('Upload encountered an unexpected file');
break;
case 'LIMIT_PART_COUNT':
problem = createBadRequestProblem('Upload rejected: upload form has too many parts');
break;
case 'LIMIT_FIELD_KEY':
problem = createBadRequestProblem('Upload rejected: upload field name for the files is too long');
break;
case 'LIMIT_FIELD_VALUE':
problem = createBadRequestProblem('Upload rejected: upload field is too long');
break;
case 'LIMIT_FIELD_COUNT':
problem = createBadRequestProblem('Upload rejected: too many fields');
break;
default:
problem = createBadRequestProblem(`Upload failed with the following error: ${error.message}`);
break;
}
} else if (error) {
problem = createBadRequestProblem(error.message);
}
if (problem) {
next(problem);
return;
}
next();
});
} catch (error) {
next(error);
}
},
};
module.exports = { fileUpload, fileSetup, createBadRequestProblem };