Security

TLS client certificate verification

TLS protects a network connection and helps authenticate the peer through certificate validation. OpenID Connect (OIDC) defines an identity layer on OAuth 2.0. Secure transport and identity token validation are distinct steps; a trusted TLS connection does not by itself authorize an application user. Never disable certificate verification to make a connection succeed. Never treat a decoded token or an arbitrary issuer URL as trusted. Do not send real tokens to a tutorial or log them. Evidence: local teaching fixture, not a production security guarantee. Source: https://nodejs.org/download/release/v22.16.0/docs/api/tls.html

Formal Syntax & Structure

nodejs syntaxnodejs
tls.connect(options[, callback])

Working Example

Example Snippetnodejs
import tls from 'node:tls';import {execFileSync} from 'node:child_process';import {mkdtempSync,readFileSync,rmSync} from 'node:fs';import {tmpdir} from 'node:os';import {join} from 'node:path';import assert from 'node:assert/strict';const dir = mkdtempSync(join(tmpdir(),'bm-tls-'));let server;try {  execFileSync('openssl',['req','-x509','-newkey','rsa:2048','-nodes',    '-keyout',join(dir,'key.pem'),'-out',join(dir,'cert.pem'),'-days','1',    '-subj','/CN=localhost','-addext','subjectAltName=DNS:localhost'],    {stdio:'ignore',timeout:3000});  const cert = readFileSync(join(dir,'cert.pem'));  server = tls.createServer({key:readFileSync(join(dir,'key.pem')),cert},s=>s.end('ok'));  server.on('tlsClientError',()=>{});  await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(0,'127.0.0.1',resolve);});  function probe(servername,ca) {    return new Promise(resolve=>{      const s=tls.connect({host:'127.0.0.1',port:server.address().port,servername,ca,rejectUnauthorized:true});      let text='';      s.setTimeout(1000,()=>s.destroy(new Error('timeout')));      s.on('data',chunk=>{text+=chunk;});      s.once('end',()=>resolve(text==='ok'?'ok':'unexpected'));      s.once('error',e=>resolve(e.code??'error'));    });  }  assert.equal(await probe('localhost',cert),'ok');  assert.equal(await probe('wrong.example',cert),'ERR_TLS_CERT_ALTNAME_INVALID');  assert.equal(await probe('localhost',undefined),'DEPTH_ZERO_SELF_SIGNED_CERT');  console.log('trusted peer, wrong hostname, untrusted peer: checks passed');} finally {  if(server?.listening) await new Promise(resolve=>server.close(resolve));  rmSync(dir,{recursive:true,force:true});}
Node.js Reference