tls.createServer([options][, secureConnectionListener])
options
<Object>-
ALPNProtocols
: <string[]> | <Buffer[]> | <TypedArray[]> | <DataView[]> | <Buffer> | <TypedArray> | <DataView> 字符串数组,Buffer
、TypedArray
或DataView
,或包含支持的 ALPN 协议的单个Buffer
、TypedArray
或DataView
。Buffer
的格式应该是[len][name][len][name]...
,例如0x05hello0x05world
,其中第一个字节是下一个协议名称的长度。 传入数组通常要简单得多,例如['hello', 'world']
。 (协议应按优先级排序。) -
clientCertEngine
<string> 可以提供客户端证书的 OpenSSL 引擎的名称。 -
enableTrace
<boolean> 如果为true
, 则tls.TLSSocket.enableTrace()
将在新连接上调用。 建立安全连接后可以启用跟踪,但必须使用此选项来跟踪安全连接设置。 默认值:false
。 -
handshakeTimeout
<number> 如果 SSL/TLS 握手未在指定的毫秒数内完成,则中止连接。 每当握手超时时,tls.Server
对象上就会触发'tlsClientError'
。 默认值:120000
(120 秒)。 -
rejectUnauthorized
<boolean> 如果不是false
,则服务器将拒绝任何未经提供的 CA 列表授权的连接。 此选项仅在requestCert
为true
时有效。 默认值:true
。 -
requestCert
<boolean> 如果为true
,则服务器将从连接的客户端请求证书并尝试验证该证书。 默认值:false
。 -
sessionTimeout
<number> 服务器创建的 TLS 会话将无法恢复之前的秒数。 请参阅会话恢复了解更多信息。 默认值:300
。 -
SNICallback(servername, callback)
<Function> 如果客户端支持 SNI TLS 扩展,将调用的函数。 调用时将传入两个参数:servername
和callback
。callback
是错误优先的回调,它有两个可选参数:error
和ctx
。ctx
是SecureContext
实例(如果提供)。tls.createSecureContext()
可用于获得正确的SecureContext
。 如果使用非真的ctx
参数调用callback
,则将使用服务器的默认安全上下文。 如果未提供SNICallback
,则将使用具有高级 API 的默认回调(见下文)。 -
pskCallback
<Function>socket: <tls.TLSSocket> 此连接的服务器
tls.TLSSocket
实例。- identity: <string> 客户端发送的身份参数。
- 返回: <Buffer> | <TypedArray> | <DataView> 预共享密钥必须是缓冲区或
null
才能停止协商过程。 返回的 PSK 必须与所选密码的摘要兼容。
当协商 TLS-PSK(预共享密钥)时,使用客户端提供的身份调用此函数。 如果返回值为
null
,则协商过程将停止,并向对方发送 "unknown_psk_identity" 警告消息。 如果服务器希望隐藏 PSK 身份未知的事实,则回调必须提供一些随机数据作为psk
以使连接失败并在协商完成之前出现 "decrypt_error"。 默认情况下禁用 PSK 密码,因此使用 TLS-PSK 需要使用ciphers
选项明确指定密码套件。 可以在 RFC 4279 中找到更多信息。 -
pskIdentityHint
<string> 发送给客户端的可选提示,以帮助在 TLS-PSK 协商期间选择身份。 将在 TLS 1.3 中被忽略。设置 pskIdentityHint 失败时,'tlsClientError'
将与'ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED'
代码一起触发。 -
...: 可以提供任何
tls.createSecureContext()
选项。 对于服务器,通常需要标识选项(pfx
、key
/cert
或pskCallback
)。 -
...: 可以提供任何
net.createServer()
选项。
-
secureConnectionListener
<Function>- 返回: <tls.Server>
创建新的 tls.Server
。
secureConnectionListener
,如果提供,将自动设置为 'secureConnection'
事件的监听器。
ticketKeys
选项在 node:cluster
模块工作器之间自动共享。
以下说明了一个简单的回显服务器:
const tls = require('node:tls');
const fs = require('node:fs');
const options = {
key: fs.readFileSync('server-key.pem'),
cert: fs.readFileSync('server-cert.pem'),
// 这仅在使用客户端证书身份验证时才需要。
requestCert: true,
// 仅当客户端使用自签名证书时才需要这样做。
ca: [ fs.readFileSync('client-cert.pem') ]
};
const server = tls.createServer(options, (socket) => {
console.log('server connected',
socket.authorized ? 'authorized' : 'unauthorized');
socket.write('welcome!\n');
socket.setEncoding('utf8');
socket.pipe(socket);
});
server.listen(8000, () => {
console.log('server bound');
});
可以通过使用 tls.connect()
的示例客户端连接到服务器来测试服务器。
options
<Object>-
ALPNProtocols
: <string[]> | <Buffer[]> | <TypedArray[]> | <DataView[]> | <Buffer> | <TypedArray> | <DataView> An array of strings,Buffer
s,TypedArray
s, orDataView
s, or a singleBuffer
,TypedArray
, orDataView
containing the supported ALPN protocols.Buffer
s should have the format[len][name][len][name]...
e.g.0x05hello0x05world
, where the first byte is the length of the next protocol name. Passing an array is usually much simpler, e.g.['hello', 'world']
. (Protocols should be ordered by their priority.) -
clientCertEngine
<string> Name of an OpenSSL engine which can provide the client certificate. -
enableTrace
<boolean> Iftrue
,tls.TLSSocket.enableTrace()
will be called on new connections. Tracing can be enabled after the secure connection is established, but this option must be used to trace the secure connection setup. Default:false
. -
handshakeTimeout
<number> Abort the connection if the SSL/TLS handshake does not finish in the specified number of milliseconds. A'tlsClientError'
is emitted on thetls.Server
object whenever a handshake times out. Default:120000
(120 seconds). -
rejectUnauthorized
<boolean> If notfalse
the server will reject any connection which is not authorized with the list of supplied CAs. This option only has an effect ifrequestCert
istrue
. Default:true
. -
requestCert
<boolean> Iftrue
the server will request a certificate from clients that connect and attempt to verify that certificate. Default:false
. -
sessionTimeout
<number> The number of seconds after which a TLS session created by the server will no longer be resumable. See Session Resumption for more information. Default:300
. -
SNICallback(servername, callback)
<Function> A function that will be called if the client supports SNI TLS extension. Two arguments will be passed when called:servername
andcallback
.callback
is an error-first callback that takes two optional arguments:error
andctx
.ctx
, if provided, is aSecureContext
instance.tls.createSecureContext()
can be used to get a properSecureContext
. Ifcallback
is called with a falsyctx
argument, the default secure context of the server will be used. IfSNICallback
wasn't provided the default callback with high-level API will be used (see below). -
ticketKeys
: <Buffer> 48-bytes of cryptographically strong pseudorandom data. See Session Resumption for more information. -
pskCallback
<Function>- socket: <tls.TLSSocket> the server
tls.TLSSocket
instance for this connection. - identity: <string> identity parameter sent from the client.
- Returns: <Buffer> | <TypedArray> | <DataView> pre-shared key that must either be
a buffer or
null
to stop the negotiation process. Returned PSK must be compatible with the selected cipher's digest.
When negotiating TLS-PSK (pre-shared keys), this function is called with the identity provided by the client. If the return value is
null
the negotiation process will stop and an "unknown_psk_identity" alert message will be sent to the other party. If the server wishes to hide the fact that the PSK identity was not known, the callback must provide some random data aspsk
to make the connection fail with "decrypt_error" before negotiation is finished. PSK ciphers are disabled by default, and using TLS-PSK thus requires explicitly specifying a cipher suite with theciphers
option. More information can be found in the RFC 4279. - socket: <tls.TLSSocket> the server
-
pskIdentityHint
<string> optional hint to send to a client to help with selecting the identity during TLS-PSK negotiation. Will be ignored in TLS 1.3. Upon failing to set pskIdentityHint'tlsClientError'
will be emitted with'ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED'
code. -
...: Any
tls.createSecureContext()
option can be provided. For servers, the identity options (pfx
,key
/cert
, orpskCallback
) are usually required. -
...: Any
net.createServer()
option can be provided.
-
secureConnectionListener
<Function>- Returns: <tls.Server>
Creates a new tls.Server
. The secureConnectionListener
, if provided, is
automatically set as a listener for the 'secureConnection'
event.
The ticketKeys
options is automatically shared between node:cluster
module
workers.
The following illustrates a simple echo server:
const tls = require('node:tls');
const fs = require('node:fs');
const options = {
key: fs.readFileSync('server-key.pem'),
cert: fs.readFileSync('server-cert.pem'),
// This is necessary only if using client certificate authentication.
requestCert: true,
// This is necessary only if the client uses a self-signed certificate.
ca: [ fs.readFileSync('client-cert.pem') ]
};
const server = tls.createServer(options, (socket) => {
console.log('server connected',
socket.authorized ? 'authorized' : 'unauthorized');
socket.write('welcome!\n');
socket.setEncoding('utf8');
socket.pipe(socket);
});
server.listen(8000, () => {
console.log('server bound');
});
The server can be tested by connecting to it using the example client from
tls.connect()
.