@dev-swarup/http-mitm-proxy 0.9.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,10 @@
1
+ import pluginJs from "@eslint/js";
2
+ import globals from "globals";
3
+
4
+ export default [
5
+ {
6
+ files: ["**/*.{js,mjs,cjs,ts}"],
7
+ },
8
+ { languageOptions: { globals: globals.browser } },
9
+ pluginJs.configs.recommended,
10
+ ];
@@ -0,0 +1,62 @@
1
+ 'use strict';
2
+
3
+ var port = 8081;
4
+ var net = require('net');
5
+ var assert = require('assert');
6
+ var Proxy = require('../');
7
+ var proxy = Proxy();
8
+
9
+ proxy.onConnect(function(req, socket, head) {
10
+ var host = req.url.split(":")[0];
11
+ var port = req.url.split(":")[1];
12
+
13
+ console.log('Tunnel to', req.url);
14
+ var conn = net.connect({
15
+ port: port,
16
+ host: host,
17
+ allowHalfOpen: true
18
+ }, function(){
19
+ conn.on('finish', () => {
20
+ socket.destroy();
21
+ });
22
+ socket.on('close', () => {
23
+ conn.end();
24
+ });
25
+ socket.write('HTTP/1.1 200 OK\r\n\r\n', 'UTF-8', function(){
26
+ conn.pipe(socket);
27
+ socket.pipe(conn);
28
+ })
29
+ });
30
+
31
+ conn.on('error', function(err) {
32
+ filterSocketConnReset(err, 'PROXY_TO_SERVER_SOCKET');
33
+ });
34
+ socket.on('error', function(err) {
35
+ filterSocketConnReset(err, 'CLIENT_TO_PROXY_SOCKET');
36
+ });
37
+ });
38
+
39
+ // Since node 0.9.9, ECONNRESET on sockets are no longer hidden
40
+ function filterSocketConnReset(err, socketDescription) {
41
+ if (err.errno === 'ECONNRESET') {
42
+ console.log('Got ECONNRESET on ' + socketDescription + ', ignoring.');
43
+ } else {
44
+ console.log('Got unexpected error on ' + socketDescription, err);
45
+ }
46
+ }
47
+
48
+ proxy.listen({ port }, function() {
49
+ console.log('Proxy server listening on ' + port);
50
+
51
+ var cmd = `curl -x http://localhost:${port} https://github.com/ | grep html`;
52
+ console.log('> ' + cmd);
53
+ require('child_process').exec(cmd, function (error, stdout, stderr) {
54
+ if (error) {
55
+ console.error(`exec error: ${error}`);
56
+ return;
57
+ }
58
+ console.log(`${stdout}`);
59
+ assert(/DOCTYPE/.test(stdout));
60
+ proxy.close();
61
+ });
62
+ });
@@ -0,0 +1,44 @@
1
+ 'use strict';
2
+
3
+ var port = 8081;
4
+
5
+ var Proxy = require('../');
6
+ var proxy = Proxy();
7
+
8
+ proxy.onError(function(ctx, err, errorKind) {
9
+ // ctx may be null
10
+ var url = (ctx && ctx.clientToProxyRequest) ? ctx.clientToProxyRequest.url : '';
11
+ console.error(errorKind + ' on ' + url + ':', err);
12
+ });
13
+
14
+ proxy.onRequest(function(ctx, callback) {
15
+ //console.log('REQUEST: http://' + ctx.clientToProxyRequest.headers.host + ctx.clientToProxyRequest.url);
16
+ if (ctx.clientToProxyRequest.headers.host == 'www.google.com'
17
+ && ctx.clientToProxyRequest.url.indexOf('/search') == 0) {
18
+ ctx.use(Proxy.gunzip);
19
+
20
+ ctx.onResponseData(function(ctx, chunk, callback) {
21
+ chunk = new Buffer(chunk.toString().replace(/<h3.*?<\/h3>/g, '<h3>Pwned!</h3>'));
22
+ return callback(null, chunk);
23
+ });
24
+ }
25
+ return callback();
26
+ });
27
+
28
+ proxy.onRequestData(function(ctx, chunk, callback) {
29
+ //console.log('request data length: ' + chunk.length);
30
+ return callback(null, chunk);
31
+ });
32
+
33
+ proxy.onResponse(function(ctx, callback) {
34
+ //console.log('RESPONSE: http://' + ctx.clientToProxyRequest.headers.host + ctx.clientToProxyRequest.url);
35
+ return callback(null);
36
+ });
37
+
38
+ proxy.onResponseData(function(ctx, chunk, callback) {
39
+ //console.log('response data length: ' + chunk.length);
40
+ return callback(null, chunk);
41
+ });
42
+
43
+ proxy.listen({ port: port });
44
+ console.log('listening on ' + port);
@@ -0,0 +1,30 @@
1
+ 'use strict';
2
+
3
+ var port = 8081;
4
+ var path = require('path');
5
+
6
+ var Proxy = require('../');
7
+ var proxy = Proxy();
8
+
9
+ proxy.onError(function(ctx, err, errorKind) {
10
+ // ctx may be null
11
+ var url = (ctx && ctx.clientToProxyRequest) ? ctx.clientToProxyRequest.url : '';
12
+ console.error(errorKind + ' on ' + url + ':', err);
13
+ });
14
+
15
+ proxy.onCertificateMissing = function(ctx, files, callback) {
16
+ console.log('Looking for "%s" certificates', ctx.hostname);
17
+ console.log('"%s" missing', ctx.files.keyFile);
18
+ console.log('"%s" missing', ctx.files.certFile);
19
+
20
+ // Here you have the last chance to provide certificate files data
21
+ // A tipical use case would be creating them on the fly
22
+ //
23
+ // return callback(null, {
24
+ // key: keyFileData,
25
+ // cert: certFileData
26
+ // });
27
+ };
28
+
29
+ proxy.listen({ port: port });
30
+ console.log('listening on ' + port);
@@ -0,0 +1,23 @@
1
+ 'use strict';
2
+
3
+ var port = 8081;
4
+ var path = require('path');
5
+
6
+ var Proxy = require('../');
7
+ var proxy = Proxy();
8
+
9
+ proxy.onError(function(ctx, err, errorKind) {
10
+ // ctx may be null
11
+ var url = (ctx && ctx.clientToProxyRequest) ? ctx.clientToProxyRequest.url : '';
12
+ console.error(errorKind + ' on ' + url + ':', err);
13
+ });
14
+
15
+ proxy.onCertificateRequired = function(hostname, callback) {
16
+ return callback(null, {
17
+ keyFile: path.resolve('/ca/certs/', hostname + '.key'),
18
+ certFile: path.resolve('/ca/certs/', hostname + '.crt')
19
+ });
20
+ };
21
+
22
+ proxy.listen({ port: port });
23
+ console.log('listening on ' + port);
@@ -0,0 +1,20 @@
1
+ 'use strict';
2
+
3
+ var port = 8081;
4
+
5
+ var Proxy = require('../');
6
+ var proxy = Proxy();
7
+
8
+ proxy.onError(function(ctx, err, errorKind) {
9
+ // ctx may be null
10
+ var url = (ctx && ctx.clientToProxyRequest) ? ctx.clientToProxyRequest.url : '';
11
+ console.error(errorKind + ' on ' + url + ':', err);
12
+ });
13
+
14
+ proxy.onRequest(function(ctx, callback) {
15
+ ctx.proxyToClientResponse.end('Hacked, you cannot proceed to the website');
16
+ // no callback() so proxy request is not sent to the server
17
+ });
18
+
19
+ proxy.listen({ port: port });
20
+ console.log('listening on ' + port);
@@ -0,0 +1,36 @@
1
+ 'use strict';
2
+
3
+ var port = 8081;
4
+
5
+ var Proxy = require('../');
6
+ var proxy = Proxy();
7
+
8
+ proxy.onError(function(ctx, err, errorKind) {
9
+ // ctx may be null
10
+ var url = (ctx && ctx.clientToProxyRequest) ? ctx.clientToProxyRequest.url : '';
11
+ console.error(errorKind + ' on ' + url + ':', err);
12
+ });
13
+
14
+ proxy.use(Proxy.gunzip);
15
+
16
+ proxy.onRequest(function(ctx, callback) {
17
+ var chunks = [];
18
+ ctx.onResponseData(function(ctx, chunk, callback) {
19
+ chunks.push(chunk);
20
+ return callback(null, null); // don't write chunks to client response
21
+ });
22
+ ctx.onResponseEnd(function(ctx, callback) {
23
+ var body = Buffer.concat(chunks);
24
+ if(ctx.serverToProxyResponse.headers['content-type'] && ctx.serverToProxyResponse.headers['content-type'].indexOf('text/html') === 0) {
25
+ body = body.toString().replace(/Lucky/g, 'Sexy');
26
+ }
27
+ ctx.proxyToClientResponse.write(body);
28
+ return callback();
29
+ });
30
+ callback();
31
+ });
32
+
33
+
34
+
35
+ proxy.listen({ port: port });
36
+ console.log('listening on ' + port);
@@ -0,0 +1,17 @@
1
+ 'use strict';
2
+
3
+ var port = 8081;
4
+
5
+ var Proxy = require('../');
6
+ var proxy = Proxy();
7
+
8
+ proxy.onRequest(function(ctx, callback) {
9
+ if('content-length' in ctx.proxyToServerRequestOptions.headers) {
10
+ console.log(`found "content-length" header in request to "${ctx.proxyToServerRequestOptions.host}${ctx.proxyToServerRequestOptions.path}". Removing.`);
11
+ delete ctx.proxyToServerRequestOptions.headers['content-length'];
12
+ }
13
+ callback();
14
+ });
15
+
16
+ proxy.listen({ port: port });
17
+ console.log('listening on ' + port);
@@ -0,0 +1,31 @@
1
+ 'use strict';
2
+
3
+ var port = 8081;
4
+
5
+ var Proxy = require('../');
6
+ var proxy = Proxy();
7
+
8
+ proxy.onError(function(ctx, err, errorKind) {
9
+ // ctx may be null
10
+ var url = (ctx && ctx.clientToProxyRequest) ? ctx.clientToProxyRequest.url : '';
11
+ console.error(errorKind + ' on ' + url + ':', err);
12
+ });
13
+ proxy.onWebSocketConnection(function(ctx, callback) {
14
+ console.log('WEBSOCKET CONNECT:', ctx.clientToProxyWebSocket.upgradeReq.url);
15
+ return callback();
16
+ });
17
+ proxy.onWebSocketFrame(function(ctx, type, fromServer, message, flags, callback) {
18
+ console.log('WEBSOCKET FRAME ' + type + ' received from ' + (fromServer ? 'server' : 'client'), ctx.clientToProxyWebSocket.upgradeReq.url, message);
19
+ if (message) var hackedMessage = message.replace(/Rock it/ig, 'Hack it');
20
+ return callback(null, message, flags);
21
+ });
22
+ proxy.onWebSocketError(function(ctx, err) {
23
+ console.log('WEBSOCKET ERROR ', ctx.clientToProxyWebSocket.upgradeReq.url, err);
24
+ });
25
+ proxy.onWebSocketClose(function(ctx, code, message, callback) {
26
+ console.log('WEBSOCKET CLOSED BY '+(ctx.closedByServer ? 'SERVER' : 'CLIENT'), ctx.clientToProxyWebSocket.upgradeReq.url, code, message);
27
+ callback(null, code, message);
28
+ });
29
+
30
+ proxy.listen({ port: port });
31
+ console.log('listening on ' + port);
@@ -0,0 +1,17 @@
1
+ 'use strict';
2
+
3
+ var port = 8081;
4
+
5
+ var Proxy = require('../');
6
+ var proxy = Proxy();
7
+
8
+ proxy.use(Proxy.wildcard);
9
+
10
+ proxy.onError(function(ctx, err, errorKind) {
11
+ // ctx may be null
12
+ var url = (ctx && ctx.clientToProxyRequest) ? ctx.clientToProxyRequest.url : '';
13
+ console.error(errorKind + ' on ' + url + ':', err);
14
+ });
15
+
16
+ proxy.listen({ port: port });
17
+ console.log('listening on ' + port);
package/index.d.ts ADDED
@@ -0,0 +1,314 @@
1
+ //definitions by jason swearingen. jasons aat novaleaf doot coom. for node-htt-mitm-proxy v0.5.2.
2
+
3
+ import http = require("http");
4
+ import https = require("https");
5
+ import net = require("net");
6
+
7
+ declare namespace HttpMitmProxy {
8
+ export interface IProxyStatic {
9
+ (): IProxy;
10
+ /** mod to pass to the use() function: Gunzip response filter (uncompress gzipped content before onResponseData and compress back after)*/
11
+ gunzip: any;
12
+ /** mod to pass to the use() function: Generates wilcard certificates by default (so less certificates are generated)*/
13
+ wildcard: any;
14
+ }
15
+
16
+ export interface IProxyOptions {
17
+ /**port - The port or named socket to listen on (default: 8080).*/
18
+ port?: number;
19
+ /**host - The hostname or local address to listen on.*/
20
+ host?: string;
21
+ /** - Path to the certificates cache directory (default: process.cwd() + '/.http-mitm-proxy')*/
22
+ sslCaDir?: string;
23
+ /** - enable HTTP persistent connection*/
24
+ keepAlive?: boolean;
25
+ /** - The number of milliseconds of inactivity before a socket is presumed to have timed out. Defaults to no timeout. */
26
+ timeout?: number;
27
+ /** - The http.Agent to use when making http requests. Useful for chaining proxys. (default: internal Agent) */
28
+ httpAgent?: http.Agent;
29
+ /** - The https.Agent to use when making https requests. Useful for chaining proxys. (default: internal Agent) */
30
+ httpsAgent?: https.Agent;
31
+ /** - force use of SNI by the client. Allow node-http-mitm-proxy to handle all HTTPS requests with a single internal server. */
32
+ forceSNI?: boolean;
33
+ /** - The port or named socket for https server to listen on. (forceSNI must be enabled) */
34
+ httpsPort?: number;
35
+ /** - Setting this option will remove the content-length from the proxy to server request, forcing chunked encoding */
36
+ forceChunkedRequest?: boolean;
37
+ }
38
+
39
+ export type IProxy = ICallbacks & {
40
+ /** Starts the proxy listening on the given port.. example: proxy.listen({ port: 80 }); */
41
+ listen(
42
+ /** An object with the following options: */ options?: IProxyOptions,
43
+ callback?: Function
44
+ ): void;
45
+ /** proxy.close
46
+ Stops the proxy listening.
47
+
48
+ Example
49
+
50
+ proxy.close(); */
51
+ close(): void;
52
+
53
+ address(): net.AddressInfo;
54
+
55
+ onCertificateRequired(
56
+ hostname: string,
57
+ callback: (
58
+ error: Error | undefined,
59
+ certDetails: { keyFile: string; certFile: string; hosts: string[] }
60
+ ) => void
61
+ ): void;
62
+ onCertificateMissing(
63
+ ctx: IContext,
64
+ files: any,
65
+ callback: (
66
+ error: Error | undefined,
67
+ certDetails: {
68
+ keyFileData: string;
69
+ certFileData: string;
70
+ hosts: string[];
71
+ }
72
+ ) => void
73
+ ): void;
74
+
75
+ //undocumented helpers
76
+ onConnect(
77
+ fcn: (
78
+ req: http.IncomingMessage,
79
+ socket: net.Socket,
80
+ head: any,
81
+ callback: (error?: Error) => void
82
+ ) => void
83
+ ): void;
84
+ onRequestHeaders(
85
+ fcn: (ctx: IContext, callback: (error?: Error) => void) => void
86
+ ): void;
87
+ onResponseHeaders(
88
+ fcn: (ctx: IContext, callback: (error?: Error) => void) => void
89
+ ): void;
90
+ onWebSocketConnection(
91
+ fcn: (ctx: IContext, callback: (error?: Error) => void) => void
92
+ ): void;
93
+ onWebSocketSend(
94
+ fcn: (
95
+ ctx: IContext,
96
+ message: any,
97
+ flags: any,
98
+ callback: (err: Error | undefined, message: any, flags: any) => void
99
+ ) => void
100
+ ): void;
101
+ onWebSocketMessage(
102
+ fcn: (
103
+ ctx: IContext,
104
+ message: any,
105
+ flags: any,
106
+ callback: (err: Error | undefined, message: any, flags: any) => void
107
+ ) => void
108
+ ): void;
109
+ onWebSocketFrame(
110
+ fcn: (
111
+ ctx: IContext,
112
+ type: any,
113
+ fromServer: boolean,
114
+ message: any,
115
+ flags: any,
116
+ callback: (err: Error | undefined, message: any, flags: any) => void
117
+ ) => void
118
+ ): void;
119
+ onWebSocketError(
120
+ fcn: (ctx: IContext, err: Error | undefined) => void
121
+ ): void;
122
+ onWebSocketClose(
123
+ fcn: (
124
+ ctx: IContext,
125
+ code: any,
126
+ message: any,
127
+ callback: (err: Error | undefined, code: any, message: any) => void
128
+ ) => void
129
+ ): void;
130
+
131
+ // onConnectHandlers:((req,socket,head,callback)=>void)[];
132
+ // onRequestHandlers:((ctx,callback)=>void)[];
133
+
134
+ options: IProxyOptions;
135
+ httpPort: number;
136
+ timeout: number;
137
+ keepAlive: boolean;
138
+ httpAgent: http.Agent;
139
+ httpsAgent: https.Agent;
140
+ forceSNI: boolean;
141
+ httpsPort?: number;
142
+ sslCaDir: string;
143
+ };
144
+
145
+ /** signatures for various callback functions */
146
+ export interface ICallbacks {
147
+ onError(
148
+ /**Adds a function to the list of functions to get called if an error occures.
149
+
150
+ Arguments
151
+
152
+ fn(ctx, err, errorKind) - The function to be called on an error.*/ callback: (
153
+ context: IContext,
154
+ err?: Error,
155
+ errorKind?: string
156
+ ) => void
157
+ ): void;
158
+
159
+ /** Adds a function to get called at the beginning of a request.
160
+
161
+ Arguments
162
+
163
+ fn(ctx, callback) - The function that gets called on each request.
164
+ Example
165
+
166
+ proxy.onRequest(function(ctx, callback) {
167
+ console.log('REQUEST:', ctx.clientToProxyRequest.url);
168
+ return callback();
169
+ }); */
170
+ onRequest(
171
+ fcn: (ctx: IContext, callback: (error?: Error) => void) => void
172
+ ): void;
173
+
174
+ onRequestData(
175
+ fcn: (
176
+ ctx: IContext,
177
+ chunk: Buffer,
178
+ callback: (error?: Error, chunk?: Buffer) => void
179
+ ) => void
180
+ ): void;
181
+
182
+ onRequestEnd(
183
+ fcn: (ctx: IContext, callback: (error?: Error) => void) => void
184
+ ): void;
185
+ /** Adds a function to get called at the beginning of the response.
186
+
187
+ Arguments
188
+
189
+ fn(ctx, callback) - The function that gets called on each response.
190
+ Example
191
+
192
+ proxy.onResponse(function(ctx, callback) {
193
+ console.log('BEGIN RESPONSE');
194
+ return callback();
195
+ }); */
196
+ onResponse(
197
+ fcn: (ctx: IContext, callback: (error?: Error) => void) => void
198
+ ): void;
199
+
200
+ onResponseData(
201
+ fcn: (
202
+ ctx: IContext,
203
+ chunk: Buffer,
204
+ callback: (error?: Error, chunk?: Buffer) => void
205
+ ) => void
206
+ ): void;
207
+
208
+ onResponseEnd(
209
+ fcn: (ctx: IContext, callback: (error?: Error) => void) => void
210
+ ): void;
211
+
212
+ /** Adds a module into the proxy. Modules encapsulate multiple life cycle processing functions into one object.
213
+
214
+ Arguments
215
+
216
+ module - The module to add. Modules contain a hash of functions to add.
217
+ Example
218
+
219
+ proxy.use({
220
+ onError: function(ctx, err) { },
221
+ onCertificateRequired: function(hostname, callback) { return callback(); },
222
+ onCertificateMissing: function(ctx, files, callback) { return callback(); },
223
+ onRequest: function(ctx, callback) { return callback(); },
224
+ onRequestData: function(ctx, chunk, callback) { return callback(null, chunk); },
225
+ onResponse: function(ctx, callback) { return callback(); },
226
+ onResponseData: function(ctx, chunk, callback) { return callback(null, chunk); },
227
+ onWebSocketConnection: function(ctx, callback) { return callback(); },
228
+ onWebSocketSend: function(ctx, message, flags, callback) { return callback(null, message, flags); },
229
+ onWebSocketMessage: function(ctx, message, flags, callback) { return callback(null, message, flags); },
230
+ onWebSocketError: function(ctx, err) { },
231
+ onWebSocketClose: function(ctx, code, message, callback) { },
232
+ });
233
+ node-http-mitm-proxy provide some ready to use modules:
234
+
235
+ Proxy.gunzip Gunzip response filter (uncompress gzipped content before onResponseData and compress back after)
236
+ Proxy.wildcard Generates wilcard certificates by default (so less certificates are generated) */
237
+ use(mod: any): void;
238
+ }
239
+
240
+ export type IContext = ICallbacks & {
241
+ isSSL: boolean;
242
+
243
+ /** may be set to true/false when dealing with websockets. */
244
+ closedByServer?: boolean;
245
+
246
+ clientToProxyRequest: http.IncomingMessage;
247
+ proxyToClientResponse: http.ServerResponse;
248
+ proxyToServerRequest: http.ClientRequest;
249
+ serverToProxyResponse: http.IncomingMessage;
250
+
251
+ /** instance of WebSocket object from https://github.com/websockets/ws */
252
+ clientToProxyWebSocket: any;
253
+ /** instance of WebSocket object from https://github.com/websockets/ws */
254
+ proxyToServerWebSocket: any;
255
+
256
+ /** user defined tags, initially constructed in the proxy-internals.tx proxy.onRequest() callback, you can add what you like here. */
257
+ tags: {
258
+ id: number;
259
+ uri: string;
260
+ /** ln 743 of proxy.js, hack to retry */
261
+ failedUpstreamCalls: number;
262
+ /** ln 743 of proxy.js, hack to retry */
263
+ retryProxyRequest: boolean;
264
+ [key: string]: any;
265
+ };
266
+
267
+ /**Adds a stream into the request body stream.
268
+
269
+ Arguments
270
+
271
+ stream - The read/write stream to add in the request body stream.
272
+ Example
273
+
274
+ ctx.addRequestFilter(zlib.createGunzip()); */
275
+ addRequestFilter(stream: any): void;
276
+ /** Adds a stream into the response body stream.
277
+
278
+ Arguments
279
+
280
+ stream - The read/write stream to add in the response body stream.
281
+ Example
282
+
283
+ ctx.addResponseFilter(zlib.createGunzip()); */
284
+ addResponseFilter(stream: any): void;
285
+
286
+ /** filters added by .addRequestFilter() */
287
+ requestFilters: any[];
288
+
289
+ /** filters added by .addResponseFilter() */
290
+ responseFilters: any[];
291
+
292
+ /** undocumented, allows adjusting the request in callbacks (such as .onRequest()) before sending upstream (to proxy or target host)..
293
+ * FYI these values seem pre-populated with defaults based on the request, you can modify them to change behavior. */
294
+ proxyToServerRequestOptions: {
295
+ /** ex: "GET" */
296
+ method: string;
297
+ /** ex: "/success.txt" */
298
+ path: string;
299
+
300
+ /** example: "detectportal.firefox.com" */
301
+ host: string;
302
+ port: null;
303
+ headers: { [key: string]: string };
304
+ agent: http.Agent;
305
+ };
306
+
307
+ onResponseDataHandlers: Function[];
308
+ onResponseEndHandlers: Function[];
309
+ };
310
+ }
311
+
312
+ declare const HttpMitmProxy: HttpMitmProxy.IProxyStatic;
313
+ export = HttpMitmProxy;
314
+ export as namespace HttpMitmProxy;
package/index.js ADDED
@@ -0,0 +1,3 @@
1
+ 'use strict';
2
+
3
+ module.exports = require('./lib/proxy');