forked from httptoolkit/httptoolkit-server
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttptoolkit-server.ts
203 lines (173 loc) · 6.74 KB
/
httptoolkit-server.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
import * as _ from 'lodash';
import * as os from 'os';
import * as events from 'events';
import { GraphQLServer } from 'graphql-yoga';
import * as Express from 'express';
import { GraphQLScalarType } from 'graphql';
import { HtkConfig } from './config';
import { reportError, addBreadcrumb } from './error-tracking';
import { buildInterceptors, Interceptor } from './interceptors';
import { ALLOWED_ORIGINS, delay } from './util';
const packageJson = require('../package.json');
const typeDefs = `
type Query {
version: String!
config: InterceptionConfig!
interceptors: [Interceptor!]!
networkInterfaces: Json
}
type Mutation {
activateInterceptor(
id: ID!,
proxyPort: Int!,
options: Json
): Boolean!
deactivateInterceptor(
id: ID!,
proxyPort: Int!
): Boolean!
triggerUpdate: Void
}
type InterceptionConfig {
certificatePath: String!
}
type Interceptor {
id: ID!
version: String!
isActivable: Boolean!
isActive(proxyPort: Int!): Boolean!
}
scalar Json
scalar Error
scalar Void
`
const buildResolvers = (
config: HtkConfig,
interceptors: _.Dictionary<Interceptor>,
eventEmitter: events.EventEmitter
) => {
return {
Query: {
version: () => packageJson.version,
interceptors: () => _.values(interceptors),
config: () => ({
certificatePath: config.https.certPath
}),
networkInterfaces: () => os.networkInterfaces()
},
Mutation: {
activateInterceptor: async (__: void, args: _.Dictionary<any>) => {
const { id, proxyPort, options } = args;
addBreadcrumb(`Activating ${id}`, { category: 'interceptor', data: { id, options } });
const interceptor = interceptors[id];
if (!interceptor) throw new Error(`Unknown interceptor ${id}`);
await Promise.race([
interceptor.activate(proxyPort, options).catch(reportError),
delay(30000) // After 30s, we don't stop activating, but we do report failure
]);
const isActive = interceptor.isActive(proxyPort);
if (isActive) {
addBreadcrumb(`Successfully activated ${id}`, { category: 'interceptor' });
} else {
reportError(new Error(`Failed to activate ${id}`));
}
return isActive;
},
deactivateInterceptor: async (__: void, args: _.Dictionary<any>) => {
const { id, proxyPort, options } = args;
const interceptor = interceptors[id];
if (!interceptor) throw new Error(`Unknown interceptor ${id}`);
await interceptor.deactivate(proxyPort, options).catch(reportError);
return !interceptor.isActive(proxyPort);
},
triggerUpdate: () => {
eventEmitter.emit('update-requested');
}
},
Interceptor: {
isActivable: (interceptor: Interceptor) => {
return interceptor.isActivable().catch((e) => {
reportError(e);
return false;
});
},
isActive: (interceptor: Interceptor, args: _.Dictionary<any>) => {
try {
return interceptor.isActive(args.proxyPort);
} catch (e) {
reportError(e);
return false;
}
}
},
Json: new GraphQLScalarType({
name: 'Json',
description: 'A JSON entity, serialized as a simple JSON string',
serialize: (value: any) => JSON.stringify(value),
parseValue: (input: string): any => JSON.parse(input),
parseLiteral: (): any => { throw new Error('JSON literals are not supported') }
}),
Void: new GraphQLScalarType({
name: 'Void',
description: 'Nothing at all',
serialize: (value: any) => null,
parseValue: (input: string): any => null,
parseLiteral: (): any => { throw new Error('Void literals are not supported') }
}),
Error: new GraphQLScalarType({
name: 'Error',
description: 'An error',
serialize: (value: Error) => JSON.stringify({
name: value.name,
message: value.message,
stack: value.stack
}),
parseValue: (input: string): any => {
let data = JSON.parse(input);
let error = new Error();
error.name = data.name;
error.message = data.message;
error.stack = data.stack;
throw error;
},
parseLiteral: (): any => { throw new Error('Error literals are not supported') }
}),
}
};
export class HttpToolkitServer extends events.EventEmitter {
private graphql: GraphQLServer;
constructor(config: HtkConfig) {
super();
let interceptors = buildInterceptors(config);
this.graphql = new GraphQLServer({
typeDefs,
resolvers: buildResolvers(config, interceptors, this)
});
// TODO: This logic also exists in Mockttp - probably good to commonize it somewhere.
this.graphql.use((req: Express.Request, res: Express.Response, next: () => void) => {
const origin = req.headers['origin'];
// This will have been set (or intentionally not set), by the CORS middleware
const allowedOrigin = res.getHeader('Access-Control-Allow-Origin');
// If origin is set (null or an origin) but was not accepted by the CORS options
// Note that if no options.cors is provided, allowedOrigin is always *.
if (origin !== undefined && allowedOrigin !== '*' && allowedOrigin !== origin) {
// Don't process the request: error out & skip the lot (to avoid CSRF)
res.status(403).send('CORS request sent by unacceptable origin');
} else {
next();
}
});
}
async start() {
await this.graphql.start(<any> {
// Hacky solution that lets us limit the server to only localhost,
// and override the port from 4000 to something less likely to conflict.
port: { port: 45457, host: '127.0.0.1' },
playground: false,
cors: {
origin: ALLOWED_ORIGINS,
maxAge: 86400 // Cache this result for as long as possible
}
});
}
};