This repository has been archived by the owner on May 17, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathserver.js
59 lines (52 loc) · 1.68 KB
/
server.js
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
/** Copyright (c) 2018 Uber Technologies, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import {createPlugin, type FusionPlugin} from 'fusion-core';
import type {Fetch} from 'fusion-tokens';
import {verifyMethod, CsrfIgnoreRoutesToken} from './shared';
type PluginDepsType = {
ignored: typeof CsrfIgnoreRoutesToken.optional,
};
type ServiceType = () => Promise<void>;
const enhancer = (
oldFetch: Fetch
): FusionPlugin<PluginDepsType, ServiceType> => {
return createPlugin({
deps: {
ignored: CsrfIgnoreRoutesToken.optional,
},
provides: deps => {
return function serverFetch() {
return Promise.reject(new Error('Cannot use fetch on the server'));
};
},
middleware: deps => {
const {ignored = []} = deps;
const ignoreSet = new Set(ignored);
return async function csrfMiddleware(ctx, next) {
if (ctx.path === '/csrf-token' && ctx.method === 'POST') {
// TODO(#158): Remove this once clients have had the opportunity to upgrade
ctx.set('x-csrf-token', 'x');
ctx.status = 200;
ctx.body = '';
} else if (verifyMethod(ctx.method) && !ignoreSet.has(ctx.path)) {
const token = ctx.headers['x-csrf-token'];
if (!token) {
const message =
`Missing csrf token on ${ctx.path}` +
(__DEV__
? ' Ensure you are using `fetch` from `fusion-plugin-csrf-protection-[react].'
: '');
ctx.throw(403, message);
}
}
return next();
};
},
});
};
export default enhancer;