forked from thepoison606/talktome
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhttpsRedirect.test.js
More file actions
66 lines (60 loc) · 2.32 KB
/
Copy pathhttpsRedirect.test.js
File metadata and controls
66 lines (60 loc) · 2.32 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
const test = require('node:test');
const assert = require('node:assert/strict');
const http = require('node:http');
const https = require('node:https');
const selfsigned = require('selfsigned');
const {
formatRedirectHost,
installHttpRedirectOnHttpsPort,
isPlainHttpTlsError,
} = require('./httpsRedirect');
function request(client, options) {
return new Promise((resolve, reject) => {
const req = client.get({ ...options, agent: false }, (res) => {
let body = '';
res.setEncoding('utf8');
res.on('data', (chunk) => { body += chunk; });
res.on('end', () => resolve({ statusCode: res.statusCode, headers: res.headers, body }));
});
req.on('error', reject);
req.setTimeout(2_000, () => req.destroy(new Error('request timed out')));
});
}
test('recognizes plaintext HTTP rejected by TLS', () => {
assert.equal(isPlainHttpTlsError({ code: 'ERR_SSL_HTTP_REQUEST' }), true);
assert.equal(isPlainHttpTlsError({ reason: 'http request' }), true);
assert.equal(isPlainHttpTlsError({ code: 'ERR_SSL_WRONG_VERSION_NUMBER' }), false);
assert.equal(formatRedirectHost('::ffff:192.168.1.20'), '192.168.1.20');
assert.equal(formatRedirectHost('fe80::1'), '[fe80::1]');
});
test('redirects HTTP while continuing to serve HTTPS on the same port', async () => {
const certificates = await selfsigned.generate([{ name: 'commonName', value: 'localhost' }], {
days: 1,
keySize: 2048,
});
const server = https.createServer({ key: certificates.private, cert: certificates.cert }, (req, res) => {
res.setHeader('Connection', 'close');
res.end('secure');
});
await new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', resolve);
});
const port = server.address().port;
installHttpRedirectOnHttpsPort(server, { httpsPort: port });
try {
const redirected = await request(http, { host: '127.0.0.1', port });
assert.equal(redirected.statusCode, 301);
assert.equal(redirected.headers.location, `https://127.0.0.1:${port}/`);
const secure = await request(https, {
host: '127.0.0.1',
port,
rejectUnauthorized: false,
});
assert.equal(secure.statusCode, 200);
assert.equal(secure.body, 'secure');
} finally {
server.closeAllConnections();
await new Promise((resolve) => server.close(resolve));
}
});