|
| 1 | +import { IncomingMessage, ServerResponse } from 'micri'; |
| 2 | +import { sendError } from './error'; |
| 3 | + |
| 4 | +// These methods are allowd for static resources: files and folder listings. |
| 5 | +const ALLOW_METHODS = ['GET', 'HEAD', 'OPTIONS']; |
| 6 | +const ALLOW_METHODS_STR = ALLOW_METHODS.join(', '); |
| 7 | + |
| 8 | +const ALLOW_ORIGIN = '*'; |
| 9 | +const ALLOW_REQ_HEADERS = 'Accept, Accept-Encoding, Range'; |
| 10 | +const EXPOSE_RES_HEADERS = |
| 11 | + 'Accept-Ranges, Content-Range, Content-Length, Content-Type, Content-Encoding, Content-Disposition, Date, ETag, Transfer-Encoding, Server'; |
| 12 | + |
| 13 | +/** |
| 14 | + * Check that the request method is one of the allowed types for static resources. |
| 15 | + */ |
| 16 | +export default function allowedMethod(req: IncomingMessage, res: ServerResponse): boolean { |
| 17 | + if (!ALLOW_METHODS.includes(req.method || '')) { |
| 18 | + res.setHeader('Allow', ALLOW_METHODS_STR); |
| 19 | + sendError(req, res, 405, { |
| 20 | + code: 'method_not_allowed', |
| 21 | + message: 'Method not allowed', |
| 22 | + }); |
| 23 | + |
| 24 | + return false; |
| 25 | + } |
| 26 | + |
| 27 | + if (req.method === 'OPTIONS') { |
| 28 | + res.writeHead(204, { |
| 29 | + 'Access-Control-Allow-Origin': ALLOW_ORIGIN, |
| 30 | + 'Access-Control-Allow-Methods': ALLOW_METHODS_STR, |
| 31 | + 'Access-Control-Allow-Headers': ALLOW_REQ_HEADERS, |
| 32 | + 'Access-Control-Expose-Headers': EXPOSE_RES_HEADERS, |
| 33 | + 'Access-Control-Max-Age': '86400', |
| 34 | + }); |
| 35 | + res.end(); |
| 36 | + |
| 37 | + return false; |
| 38 | + } |
| 39 | + |
| 40 | + return true; |
| 41 | +} |
0 commit comments