HTTPS#

穩定性:2 - 穩定

原始碼: lib/https.js

HTTPS 是透過 TLS/SSL 的 HTTP 協定。在 Node.js 中,它實作為一個獨立的模組。

判斷是否不支援加密#

Node.js 可以建立而不包含對 node:crypto 模組的支援。在這種情況下,嘗試從 https import 或呼叫 require('node:https') 會導致擲回錯誤。

使用 CommonJS 時,可以使用 try/catch 捕捉擲回的錯誤

let https;
try {
  https = require('node:https');
} catch (err) {
  console.error('https support is disabled!');
} 

使用字彙 ESM import 關鍵字時,只有在嘗試載入模組之前註冊 process.on('uncaughtException') 處理常式,才能捕捉錯誤(例如,使用預載入模組)。

使用 ESM 時,如果程式碼有可能在未啟用加密支援的 Node.js 版本上執行,請考慮使用 import() 函式,而不是詞彙 import 關鍵字

let https;
try {
  https = await import('node:https');
} catch (err) {
  console.error('https support is disabled!');
} 

類別:https.Agent#

類似於 http.Agent 的 HTTPS Agent 物件。請參閱 https.request() 以取得更多資訊。

new Agent([options])#

  • options <Object> 設定在代理程式上的可設定選項組。可以有與 http.Agent(options) 相同的欄位,以及
    • maxCachedSessions <number> TLS 快取會話的最大數量。使用 0 停用 TLS 會話快取。預設值:100

    • servername <string> 要傳送至伺服器的 伺服器名稱指示擴充 的值。使用空字串 '' 停用傳送擴充。預設值:目標伺服器的主機名稱,除非使用 IP 位址指定目標伺服器,否則預設值為 ''(沒有擴充)。

      請參閱 會話復原 以取得有關 TLS 會話重複使用的資訊。

事件:'keylog'#
  • line <Buffer> ASCII 文字行,格式為 NSS SSLKEYLOGFILE
  • tlsSocket <tls.TLSSocket> 產生此事件的 tls.TLSSocket 執行個體。

當此代理程式管理的連線產生或收到金鑰資料時,就會發出 keylog 事件(通常在交握完成之前,但並非絕對)。此金鑰資料可儲存以進行除錯,因為它允許解密擷取的 TLS 流量。每個 socket 可能會發出多次事件。

常見的用例是將收到的行附加到共用文字檔,稍後再由軟體(例如 Wireshark)使用該檔案來解密流量

// ...
https.globalAgent.on('keylog', (line, tlsSocket) => {
  fs.appendFileSync('/tmp/ssl-keys.log', line, { mode: 0o600 });
}); 

類別:https.Server#

請參閱 http.Server 以取得更多資訊。

server.close([callback])#

請參閱 node:http 模組中的 server.close()

server[Symbol.asyncDispose]()#

穩定性:1 - 實驗性

呼叫 server.close() 並傳回一個 Promise,在伺服器關閉時完成。

server.closeAllConnections()#

請參閱 node:http 模組中的 server.closeAllConnections()

server.closeIdleConnections()#

請參閱 node:http 模組中的 server.closeIdleConnections()

server.headersTimeout#

請參閱 node:http 模組中的 server.headersTimeout

server.listen()#

啟動 HTTPS 伺服器,以偵聽加密連線。此方法與 net.Server 中的 server.listen() 相同。

server.maxHeadersCount#

請參閱 node:http 模組中的 server.maxHeadersCount

server.requestTimeout#

請參閱 node:http 模組中的 server.requestTimeout

server.setTimeout([msecs][, callback])#

請參閱 node:http 模組中的 server.setTimeout()

server.timeout#

請參閱 node:http 模組中的 server.timeout

server.keepAliveTimeout#

請參閱 node:http 模組中的 server.keepAliveTimeout

https.createServer([options][, requestListener])#

// curl -k https://127.0.0.1:8000/
const https = require('node:https');
const fs = require('node:fs');

const options = {
  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
};

https.createServer(options, (req, res) => {
  res.writeHead(200);
  res.end('hello world\n');
}).listen(8000); 

const https = require('node:https');
const fs = require('node:fs');

const options = {
  pfx: fs.readFileSync('test/fixtures/test_cert.pfx'),
  passphrase: 'sample',
};

https.createServer(options, (req, res) => {
  res.writeHead(200);
  res.end('hello world\n');
}).listen(8000); 

https.get(options[, callback])#

https.get(url[, options][, callback])#

http.get() 相同,但適用於 HTTPS。

options 可以是物件、字串或 URL 物件。如果 options 是字串,則會自動使用 new URL() 進行剖析。如果它是 URL 物件,則會自動轉換為一般的 options 物件。

const https = require('node:https');

https.get('https://encrypted.google.com/', (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });

}).on('error', (e) => {
  console.error(e);
}); 

https.globalAgent#

所有 HTTPS 要求的 https.Agent 全域執行個體。

https.request(options[, callback])#

https.request(url[, options][, callback])#

對安全網頁伺服器提出要求。

也接受來自 tls.connect() 的下列額外 optionscacertciphersclientCertEnginecrldhparamecdhCurvehonorCipherOrderkeypassphrasepfxrejectUnauthorizedsecureOptionssecureProtocolservernamesessionIdContexthighWaterMark

options 可以是物件、字串或 URL 物件。如果 options 是字串,則會自動使用 new URL() 進行剖析。如果它是 URL 物件,則會自動轉換為一般的 options 物件。

https.request() 傳回 http.ClientRequest 類別的執行個體。ClientRequest 執行個體是可寫入串流。如果需要使用 POST 要求上傳檔案,請寫入 ClientRequest 物件。

const https = require('node:https');

const options = {
  hostname: 'encrypted.google.com',
  port: 443,
  path: '/',
  method: 'GET',
};

const req = https.request(options, (res) => {
  console.log('statusCode:', res.statusCode);
  console.log('headers:', res.headers);

  res.on('data', (d) => {
    process.stdout.write(d);
  });
});

req.on('error', (e) => {
  console.error(e);
});
req.end(); 

使用來自 tls.connect()options 的範例

const options = {
  hostname: 'encrypted.google.com',
  port: 443,
  path: '/',
  method: 'GET',
  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
};
options.agent = new https.Agent(options);

const req = https.request(options, (res) => {
  // ...
}); 

或者,透過不使用 Agent 來退出連線共用。

const options = {
  hostname: 'encrypted.google.com',
  port: 443,
  path: '/',
  method: 'GET',
  key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'),
  cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'),
  agent: false,
};

const req = https.request(options, (res) => {
  // ...
}); 

使用 URL 作為 options 的範例

const options = new URL('https://abc:[email protected]');

const req = https.request(options, (res) => {
  // ...
}); 

在憑證指紋或公開金鑰上釘選的範例(類似於 pin-sha256

const tls = require('node:tls');
const https = require('node:https');
const crypto = require('node:crypto');

function sha256(s) {
  return crypto.createHash('sha256').update(s).digest('base64');
}
const options = {
  hostname: 'github.com',
  port: 443,
  path: '/',
  method: 'GET',
  checkServerIdentity: function(host, cert) {
    // Make sure the certificate is issued to the host we are connected to
    const err = tls.checkServerIdentity(host, cert);
    if (err) {
      return err;
    }

    // Pin the public key, similar to HPKP pin-sha256 pinning
    const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU=';
    if (sha256(cert.pubkey) !== pubkey256) {
      const msg = 'Certificate verification error: ' +
        `The public key of '${cert.subject.CN}' ` +
        'does not match our pinned fingerprint';
      return new Error(msg);
    }

    // Pin the exact certificate, rather than the pub key
    const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' +
      'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16';
    if (cert.fingerprint256 !== cert256) {
      const msg = 'Certificate verification error: ' +
        `The certificate of '${cert.subject.CN}' ` +
        'does not match our pinned fingerprint';
      return new Error(msg);
    }

    // This loop is informational only.
    // Print the certificate and public key fingerprints of all certs in the
    // chain. Its common to pin the public key of the issuer on the public
    // internet, while pinning the public key of the service in sensitive
    // environments.
    do {
      console.log('Subject Common Name:', cert.subject.CN);
      console.log('  Certificate SHA256 fingerprint:', cert.fingerprint256);

      hash = crypto.createHash('sha256');
      console.log('  Public key ping-sha256:', sha256(cert.pubkey));

      lastprint256 = cert.fingerprint256;
      cert = cert.issuerCertificate;
    } while (cert.fingerprint256 !== lastprint256);

  },
};

options.agent = new https.Agent(options);
const req = https.request(options, (res) => {
  console.log('All OK. Server matched our pinned cert or public key');
  console.log('statusCode:', res.statusCode);
  // Print the HPKP values
  console.log('headers:', res.headers['public-key-pins']);

  res.on('data', (d) => {});
});

req.on('error', (e) => {
  console.error(e.message);
});
req.end(); 

範例輸出

Subject Common Name: github.com
  Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16
  Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU=
Subject Common Name: DigiCert SHA2 Extended Validation Server CA
  Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A
  Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho=
Subject Common Name: DigiCert High Assurance EV Root CA
  Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF
  Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18=
All OK. Server matched our pinned cert or public key
statusCode: 200
headers: max-age=0; pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="; pin-sha256="RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho="; pin-sha256="k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws="; pin-sha256="K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q="; pin-sha256="IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4="; pin-sha256="iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0="; pin-sha256="LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A="; includeSubDomains