• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2
3const common = require('../common');
4const fixtures = require('../common/fixtures');
5
6if (!common.hasCrypto)
7  common.skip('missing crypto');
8
9const assert = require('assert');
10const url = require('url');
11const tls = require('tls');
12const http2 = require('http2');
13const https = require('https');
14const http = require('http');
15
16const key = fixtures.readKey('agent8-key.pem');
17const cert = fixtures.readKey('agent8-cert.pem');
18const ca = fixtures.readKey('fake-startcom-root-cert.pem');
19
20function onRequest(request, response) {
21  const { socket: { alpnProtocol } } = request.httpVersion === '2.0' ?
22    request.stream.session : request;
23  response.status(200);
24  response.end(JSON.stringify({
25    alpnProtocol,
26    httpVersion: request.httpVersion,
27    userAgent: request.getUserAgent()
28  }));
29}
30
31class MyIncomingMessage extends http.IncomingMessage {
32  getUserAgent() {
33    return this.headers['user-agent'] || 'unknown';
34  }
35}
36
37class MyServerResponse extends http.ServerResponse {
38  status(code) {
39    return this.writeHead(code, { 'Content-Type': 'application/json' });
40  }
41}
42
43// HTTP/2 & HTTP/1.1 server
44{
45  const server = http2.createSecureServer(
46    {
47      cert,
48      key, allowHTTP1: true,
49      Http1IncomingMessage: MyIncomingMessage,
50      Http1ServerResponse: MyServerResponse
51    },
52    common.mustCall(onRequest, 1)
53  );
54
55  server.listen(0);
56
57  server.on('listening', common.mustCall(() => {
58    const { port } = server.address();
59    const origin = `https://localhost:${port}`;
60
61    // HTTP/1.1 client
62    https.get(
63      Object.assign(url.parse(origin), {
64        secureContext: tls.createSecureContext({ ca }),
65        headers: { 'User-Agent': 'node-test' }
66      }),
67      common.mustCall((response) => {
68        assert.strictEqual(response.statusCode, 200);
69        assert.strictEqual(response.statusMessage, 'OK');
70        assert.strictEqual(
71          response.headers['content-type'],
72          'application/json'
73        );
74
75        response.setEncoding('utf8');
76        let raw = '';
77        response.on('data', (chunk) => { raw += chunk; });
78        response.on('end', common.mustCall(() => {
79          const { alpnProtocol, httpVersion, userAgent } = JSON.parse(raw);
80          assert.strictEqual(alpnProtocol, false);
81          assert.strictEqual(httpVersion, '1.1');
82          assert.strictEqual(userAgent, 'node-test');
83
84          server.close();
85        }));
86      })
87    );
88  }));
89}
90