-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathmock.server.ts
More file actions
245 lines (214 loc) · 8.27 KB
/
Copy pathmock.server.ts
File metadata and controls
245 lines (214 loc) · 8.27 KB
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
import express from 'express';
import { Server } from 'http';
import { Server as ProxyServer } from 'proxy-chain';
// "Příliš žluťoučký kůň úpěl ďábelské ódy" encoded in Windows-1250
const WIN1250_BODY = Buffer.from([0x50, 0xf8, 0xed, 0x6c, 0x69, 0x9a, 0x20, 0x9e, 0x6c, 0x75, 0x9d, 0x6f, 0x75, 0xe8, 0x6b, 0xfd, 0x20, 0x6b, 0xf9, 0xf2, 0x20, 0xfa, 0x70, 0xec, 0x6c, 0x20, 0xef, 0xe1, 0x62, 0x65, 0x6c, 0x73, 0x6b, 0xe9, 0x20, 0xf3, 0x64, 0x79]);
const WIN1250_STRING = 'Příliš žluťoučký kůň úpěl ďábelské ódy';
export const routes = {
charset: {
path: '/charset',
bodyBuffer: WIN1250_BODY,
bodyString: WIN1250_STRING,
},
charsetMetaCharset: {
path: '/charset/meta-charset',
bodyString: WIN1250_STRING,
},
charsetMetaHttpEquiv: {
path: '/charset/meta-http-equiv',
bodyString: WIN1250_STRING,
},
nonAsciiHeader: {
path: '/non-ascii-header',
headerValue: 'Dienstag, 31. März 2026',
},
utf8Header: {
path: '/utf8-header',
headerValue: 'attachment; filename="naïve.pdf"',
},
}
function parseMultipart(body: Buffer, boundary: string): Record<string, string> {
const form: Record<string, string> = {};
const delimiter = Buffer.from(`--${boundary}`);
const separator = Buffer.from('\r\n\r\n');
let start = body.indexOf(delimiter);
while (start !== -1) {
start += delimiter.length;
const next = body.indexOf(delimiter, start);
if (next === -1) break;
const part = body.subarray(start, next);
const headerEnd = part.indexOf(separator);
if (headerEnd !== -1) {
const headerText = part.subarray(0, headerEnd).toString('utf8');
const nameMatch = headerText.match(/name="([^"]+)"/);
if (nameMatch) {
// Strip the trailing CRLF that precedes the next boundary.
const value = part.subarray(headerEnd + separator.length, part.length - 2).toString('utf8');
form[nameMatch[1]] = value;
}
}
start = next;
}
return form;
}
export async function runServer(port: number): Promise<Server> {
const app = express();
// httpbin-like echo endpoint, so body tests don't depend on an external service.
app.all('/post', express.raw({ type: () => true, limit: '10mb' }), (req, res) => {
const body: Buffer = Buffer.isBuffer(req.body) ? req.body : Buffer.alloc(0);
const contentType = req.headers['content-type'] ?? '';
let form: Record<string, string> | undefined;
if (contentType.includes('application/x-www-form-urlencoded')) {
form = Object.fromEntries(new URLSearchParams(body.toString('utf8')));
} else if (contentType.includes('multipart/form-data')) {
const boundary = contentType.match(/boundary=(.+)$/)?.[1];
if (boundary) form = parseMultipart(body, boundary);
}
res.json({
data: form ? '' : body.toString('utf8'),
form: form ?? {},
headers: req.headers,
});
});
app.get(routes.charset.path, (req, res) => {
res.set('Content-Type', 'text/plain; charset=windows-1250');
res.send(routes.charset.bodyBuffer);
});
app.get(routes.charsetMetaCharset.path, (req, res) => {
const html = Buffer.concat([
Buffer.from('<html><head><meta charset="windows-1250"></head><body>'),
WIN1250_BODY,
Buffer.from('</body></html>'),
]);
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(html);
});
app.get(routes.charsetMetaHttpEquiv.path, (req, res) => {
const html = Buffer.concat([
Buffer.from('<html><head><meta http-equiv="content-type" content="text/html; charset=windows-1250"></head><body>'),
WIN1250_BODY,
Buffer.from('</body></html>'),
]);
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(html);
});
app.get(routes.nonAsciiHeader.path, (req, res) => {
const socket = res.socket!;
socket.write('HTTP/1.1 200 OK\r\n');
socket.write('Content-Type: text/plain\r\n');
socket.write(Buffer.concat([
Buffer.from('X-Non-Ascii: Dienstag, 31. M'),
Buffer.from([0xE4]), // ä in ISO-8859-1
Buffer.from('rz 2026\r\n'),
]));
socket.write('Content-Length: 2\r\n');
socket.write('\r\n');
socket.write('ok');
socket.end();
});
app.get(routes.utf8Header.path, (req, res) => {
const socket = res.socket!;
socket.write('HTTP/1.1 200 OK\r\n');
socket.write('Content-Type: text/plain\r\n');
// Header value carrying UTF-8 bytes (the ï is 0xC3 0xAF).
socket.write(Buffer.concat([
Buffer.from('X-Utf8: '),
Buffer.from(routes.utf8Header.headerValue, 'utf-8'),
Buffer.from('\r\n'),
]));
socket.write('Content-Length: 2\r\n');
socket.write('\r\n');
socket.write('ok');
socket.end();
});
app.get('/socket', (req, res) => {
const socket = req.socket;
const clientAddress = socket.remoteAddress;
const clientPort = socket.remotePort;
res.json({ ip: clientAddress, port: clientPort });
});
app.get('/delay/:ms', (req, res) => {
const delay = parseInt(req.params.ms, 10);
res.setHeader('Content-Type', 'text/plain');
res.write('Headers sent. Preparing body...\n');
setTimeout(() => {
res.end('Body sent after delay.\n');
}, delay);
});
app.get('/cookies', (req, res) => {
const cookies: Record<string, string> = {};
const cookieHeader = req.headers.cookie;
if (cookieHeader) {
cookieHeader.split(';').forEach(cookie => {
const [name, ...rest] = cookie.trim().split('=');
cookies[name] = rest.join('=');
});
}
res.json({ cookies });
});
app.get('/cookies/set', (req, res) => {
for (const [name, value] of Object.entries(req.query)) {
res.cookie(name, value as string, { path: '/' });
}
res.redirect(302, '/cookies');
});
app.get('/cookies/set/:status', (req, res) => {
const status = parseInt(req.params.status, 10);
for (const [name, value] of Object.entries(req.query)) {
res.cookie(name, value as string, { path: '/' });
}
res.redirect(status, '/cookies');
});
app.get('/cookies/set-no-redirect', (req, res) => {
for (const [name, value] of Object.entries(req.query)) {
res.cookie(name, value as string, { path: '/' });
}
res.json({ status: 'cookies set' });
});
app.get('/cookies/chain/:hops', (req, res) => {
const hops = parseInt(req.params.hops, 10);
const hop = parseInt(req.query.hop as string || '1', 10);
res.cookie(`hop${hop}`, `value${hop}`, { path: '/' });
if (hop < hops) {
res.redirect(302, `/cookies/chain/${hops}?hop=${hop + 1}`);
} else {
res.redirect(302, '/cookies');
}
});
app.get('/redirect/:n', (req, res) => {
const n = parseInt(req.params.n, 10);
if (n > 1) {
res.redirect(302, `/redirect/${n - 1}`);
} else {
res.redirect(302, '/get');
}
});
app.get('/redirect-to', (req, res) => {
const url = req.query.url as string;
const statusCode = parseInt(req.query.status_code as string || '302', 10);
res.redirect(statusCode, url);
});
app.get('/get', (req, res) => {
res.json({ url: `http://localhost:${port}/get` });
});
app.get('/cookies/delete', (req, res) => {
for (const name of Object.keys(req.query)) {
res.clearCookie(name);
}
res.redirect(302, '/cookies');
});
return new Promise((res, rej) => {
const server = app.listen(port, (err) => {
if (err) {
rej(err);
} else {
res(server);
}
});
});
}
export async function runProxyServer(port: number): Promise<ProxyServer> {
const server = new ProxyServer({ port });
await server.listen();
return server;
}