-
Notifications
You must be signed in to change notification settings - Fork 568
/
middleware.ts
315 lines (296 loc) · 8.58 KB
/
middleware.ts
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
import {
Config,
Logger,
Middleware,
Init,
MidwayFrameworkType,
IMiddleware,
ILogger,
IgnoreMatcher,
} from '@midwayjs/core';
import { resolve } from 'path';
import { promises } from 'fs';
import { Readable, Stream } from 'stream';
import {
EXT_KEY,
MultipartInvalidFilenameError,
MultipartInvalidFileTypeError,
UploadFileInfo,
UploadOptions,
} from '.';
import { parseFromReadableStream, parseMultipart } from './parse';
import * as getRawBody from 'raw-body';
import { fromBuffer } from 'file-type';
import { formatExt } from './utils';
const { unlink, writeFile } = promises;
@Middleware()
export class UploadMiddleware implements IMiddleware<any, any> {
@Config('upload')
uploadConfig: UploadOptions;
@Logger()
logger: ILogger;
/**
* cache global upload white list when uploadConfig.whitelist is set
* @private
*/
private uploadWhiteListMap = new Map<string, string>();
/**
* cache global upload mime type white list when uploadConfig.mimeTypeWhiteList is set
* @private
*/
private uploadFileMimeTypeMap = new Map<string, string[]>();
match: IgnoreMatcher<any>[];
ignore: IgnoreMatcher<any>[];
@Init()
async init() {
if (this.uploadConfig.match) {
this.match = [].concat(this.uploadConfig.match || []);
} else {
this.ignore = [].concat(this.uploadConfig.ignore || []);
}
}
resolve(app) {
if (
this.uploadConfig.whitelist &&
Array.isArray(this.uploadConfig.whitelist)
) {
for (const whiteExt of this.uploadConfig.whitelist) {
this.uploadWhiteListMap.set(whiteExt, whiteExt);
}
}
if (this.uploadConfig.mimeTypeWhiteList) {
for (const ext in this.uploadConfig.mimeTypeWhiteList) {
const mime = [].concat(this.uploadConfig.mimeTypeWhiteList[ext]);
this.uploadFileMimeTypeMap.set(ext, mime);
}
}
if (app.getFrameworkType() === MidwayFrameworkType.WEB_EXPRESS) {
return async (req: any, res: any, next: any) => {
return this.execUpload(req, req, res, next, true);
};
} else {
return async (ctx, next) => {
const req = ctx.request?.req || ctx.request;
return this.execUpload(ctx, req, ctx, next, false);
};
}
}
async execUpload(ctx, req, res, next, isExpress) {
const { mode, tmpdir, fileSize } = this.uploadConfig;
const boundary = this.getUploadBoundary(req);
if (!boundary) {
return next();
}
ctx.fields = {};
ctx.files = [];
ctx.cleanupRequestFiles = async (): Promise<Array<boolean>> => {
if (!ctx.files?.length) {
return [];
}
return Promise.all(
ctx.files.map(async (fileInfo: UploadFileInfo<any>) => {
if (typeof fileInfo.data !== 'string') {
return false;
}
try {
await unlink(fileInfo.data);
return true;
} catch {
return false;
}
})
);
};
// create new map include custom white list
const currentContextWhiteListMap = new Map([
...this.uploadWhiteListMap.entries(),
]);
if (typeof this.uploadConfig.whitelist === 'function') {
const whiteListArray = this.uploadConfig.whitelist.call(this, ctx);
whiteListArray.forEach(ext => currentContextWhiteListMap.set(ext, ext));
}
// create new map include custom mime type white list
const currentContextMimeTypeWhiteListMap = new Map([
...this.uploadFileMimeTypeMap.entries(),
]);
if (typeof this.uploadConfig.mimeTypeWhiteList === 'function') {
const mimeTypeWhiteList = this.uploadConfig.mimeTypeWhiteList.call(
this,
ctx
);
for (const ext in mimeTypeWhiteList) {
const mime = [].concat(mimeTypeWhiteList[ext]);
currentContextMimeTypeWhiteListMap.set(ext, mime);
}
}
let body;
if (this.isReadableStream(req, isExpress)) {
if (mode === 'stream') {
const { fields, fileInfo } = await parseFromReadableStream(
req,
boundary
);
const ext = this.checkAndGetExt(
fileInfo.filename,
currentContextWhiteListMap
);
if (!ext) {
throw new MultipartInvalidFilenameError(fileInfo.filename);
} else {
fileInfo[EXT_KEY] = ext as string;
ctx.fields = fields;
ctx.files = [fileInfo];
return next();
}
}
body = await getRawBody(req, {
limit: fileSize,
});
} else if (
req?.originEvent?.body &&
(typeof req.originEvent.body === 'string' ||
Buffer.isBuffer(req.originEvent.body))
) {
body = req.originEvent.body;
} else {
body = req.body;
}
const data = await parseMultipart(body, boundary, this.uploadConfig);
if (!data) {
return next();
}
ctx.fields = data.fields;
const requireId = `upload_${Date.now()}.${Math.random()}`;
const files = data.files;
for (const fileInfo of files) {
const ext = this.checkAndGetExt(
fileInfo.filename,
currentContextWhiteListMap
);
if (!ext) {
throw new MultipartInvalidFilenameError(fileInfo.filename);
}
const { passed, mime, current } = await this.checkFileType(
ext as string,
fileInfo.data,
currentContextMimeTypeWhiteListMap
);
if (!passed) {
throw new MultipartInvalidFileTypeError(
fileInfo.filename,
current,
mime
);
}
fileInfo[EXT_KEY] = ext;
}
ctx.files = await Promise.all(
files.map(async (file, index) => {
const { data } = file;
if (mode === 'file') {
const ext = file[EXT_KEY];
const tmpFileName = resolve(tmpdir, `${requireId}.${index}${ext}`);
await writeFile(tmpFileName, data, 'binary');
file.data = tmpFileName;
} else if (mode === 'stream') {
file.data = new Readable({
read() {
this.push(data);
this.push(null);
},
});
}
return file;
})
);
return next();
}
getUploadBoundary(request): false | string {
const method = (request.method || request.httpMethod || '').toUpperCase();
if (
method !== 'POST' &&
method !== 'PUT' &&
method !== 'DELETE' &&
method !== 'PATCH'
) {
return false;
}
if (!request.headers?.['content-type']) {
return false;
}
const contentType: string = request.headers['content-type'];
if (!contentType.startsWith('multipart/form-data;')) {
return false;
}
const boundaryMatch = /boundary=(.*)(;|\s|$)/.exec(contentType);
if (!boundaryMatch?.[1]) {
return false;
}
return boundaryMatch[1];
}
isReadableStream(req: any, isExpress): boolean {
// ref: https://github.com/rvagg/isstream/blob/master/isstream.js#L10
if (
req instanceof Stream &&
typeof (req as any)._read === 'function' &&
typeof (req as any)._readableState === 'object' &&
(!(req as any).body || isExpress)
) {
return true;
}
if (req.pipe && req.on && !req.body) {
return true;
}
return false;
}
// check extensions
checkAndGetExt(
filename,
whiteListMap = this.uploadWhiteListMap
): string | boolean {
const lowerCaseFileNameList = filename.toLowerCase().split('.');
while (lowerCaseFileNameList.length) {
lowerCaseFileNameList.shift();
const curExt = `.${lowerCaseFileNameList.join('.')}`;
if (this.uploadConfig.whitelist === null) {
return formatExt(curExt);
}
if (whiteListMap.has(curExt)) {
// Avoid the presence of hidden characters and return extensions in the white list.
return whiteListMap.get(curExt);
}
}
return false;
}
// check file-type
async checkFileType(
ext: string,
data: Buffer,
uploadFileMimeTypeMap = this.uploadFileMimeTypeMap
): Promise<{ passed: boolean; mime?: string; current?: string }> {
// fileType == null, pass check
if (!this.uploadConfig.mimeTypeWhiteList) {
return { passed: true };
}
const mime = uploadFileMimeTypeMap.get(ext);
if (!mime) {
return { passed: false, mime: ext };
}
if (!mime.length) {
return { passed: true };
}
const typeInfo = await fromBuffer(data);
if (!typeInfo) {
return { passed: false, mime: mime.join('、') };
}
const findMime = mime.find(mimeItem => mimeItem === typeInfo.mime);
return {
passed: !!findMime,
mime: mime.join('、'),
current: typeInfo.mime,
};
}
static getName() {
return 'upload';
}
}