Connecting
connect() takes a transport, a function that opens the connection, plus session options. The built-in transports are ssh() (RFC 6242, port 830) and tls() (RFC 7589, port 6513).
SSH
import { connect, ssh, knownHostsFile } from '@node-net/netconf';
const client = await connect({
transport: ssh({
host: 'router1',
username: 'admin',
// read only when connecting
password: () => process.env.ROUTER_PASSWORD!,
hostKey: knownHostsFile(),
}),
});Authentication
| Option | |
|---|---|
password | A string, or a function (sync or async) that returns one. Functions are called only when needed, and the value is never stored. |
privateKey, passphrase | A key as a string or Buffer, or a function that returns one |
agent | Path to an SSH agent socket, such as process.env.SSH_AUTH_SOCK |
keyboardInteractive | A function that answers keyboard-interactive prompts (below) |
Methods are tried in the order none, password, private key, agent, keyboard-interactive, and only those the server says it accepts, so a method it doesn't allow never costs a failed attempt against a lockout policy.
A server that refuses the credentials, or drops the connection during authentication, makes connect() reject with an AuthenticationError.
Keyboard-interactive
Some servers, often those that check logins against TACACS+ or RADIUS, accept only keyboard-interactive authentication (RFC 4256): the server sends prompts and the client answers them. A password answers it with no extra options, as long as every prompt is hidden (a password prompt doesn't echo). The password isn't sent this way if the server has already refused it through password authentication, so a wrong password costs one failed attempt, not two.
For anything else, such as a one-time code, pass keyboardInteractive. It gets each challenge and returns one answer per prompt, and may be async:
import { ssh, knownHostsFile } from '@node-net/netconf';
const transport = ssh({
host: 'router1',
username: 'admin',
hostKey: knownHostsFile(),
// gets { name, instructions, prompts: [{ prompt, echo }] }
keyboardInteractive: ({ prompts }) =>
prompts.map((p) =>
/code/i.test(p.prompt)
? process.env.ROUTER_OTP!
: process.env.ROUTER_PASSWORD!,
),
});A server may send several challenges in turn; the function is called for each. A prompt that echoes is never answered with the password: without keyboardInteractive, that challenge fails with an AuthenticationError. So does a keyboardInteractive that throws, with the error as its cause.
Host keys
Verifying the host key is mandatory. Choose how with hostKey:
// ~/.ssh/known_hosts, or give a path
hostKey: knownHostsFile()
// known_hosts lines you already hold
hostKey: knownHosts(fileContents)
// one pinned fingerprint, or an array of them
hostKey: 'SHA256:Ab12…'
// a pinned public key line (arrays may mix both)
hostKey: 'ssh-ed25519 AAAA…'
// your own verifier
hostKey: ({ host, port, key }) => myCheck(key)
// accept anything; logged as a warning
hostKey: INSECURE_ACCEPT_ANYA key that doesn't match rejects with a HostKeyError. fingerprintOf(key) gives a key's SHA256: fingerprint. toVerifier(pin) turns a fingerprint, key line or list of them into a verifier function, and throws a TypeError for a malformed one, so pins read from configuration can be checked up front.
Jump hosts
Devices behind a bastion need no port forwarding. jump works like ssh -J: each hop has its own credentials and host-key check, and the SSH session to the device runs end to end through the tunnel:
import { ssh, knownHostsFile } from '@node-net/netconf';
const transport = ssh({
host: 'router1',
username: 'admin',
password: () => process.env.ROUTER_PASSWORD!,
hostKey: knownHostsFile(),
jump: {
host: 'bastion',
username: 'me',
agent: process.env.SSH_AUTH_SOCK,
hostKey: knownHostsFile(),
},
});Give an array for a chain of jump hosts, connected in order.
Algorithms
By default ssh() offers ssh2's default algorithms minus every legacy one, as DEFAULT_SSH_ALGORITHMS lists. Left out are SHA-1 host-key signatures (ssh-rsa), SHA-1 and MD5 MACs (hmac-sha1, hmac-sha1-etm@openssh.com, hmac-md5 and their variants), SHA-1 key exchange, CBC and RC4 ciphers, and DSA keys. RSA host and user keys still work, through rsa-sha2-512 and rsa-sha2-256 (RFC 8332).
An old device that only has a legacy algorithm needs it enabled explicitly. algorithms (type SshAlgorithms) changes one category at a time (kex, serverHostKey, cipher, hmac, compress): a list replaces that category, and { append, prepend, remove }, each one name or a list and each optional, edits the default. Any legacy algorithm in the result is logged as a warning on every connection:
// add SHA-1 MACs back for one old device (logged)
algorithms: { hmac: { append: 'hmac-sha1' } }
// or replace the host-key list outright
algorithms: { serverHostKey: ['ssh-rsa'] }Other SSH options
port, keepaliveInterval, keepaliveCountMax, and subsystem or command for devices that start NETCONF some other way. Device profiles can supply these, and algorithms, as connection defaults.
TLS
Devices that speak NETCONF over TLS take a client certificate instead of a password. You must say how to verify the server: give its CA (the chain and host name are checked), pin its certificate's SHA-256 fingerprint, or both. The system's public CA list is never used.
import { readFileSync } from 'node:fs';
import { connect, tls } from '@node-net/netconf';
const client = await connect({
transport: tls({
host: 'router1',
cert: readFileSync('me.pem'),
key: readFileSync('me.key'),
ca: readFileSync('ca.pem'),
}),
});In the lab, tls() connects to the lab device instead, and no certificate is read or checked. To see the TLS itself, run the program against nncd (below).
A certificate the server refuses, or one it can't map to a user, rejects with an AuthenticationError. A server certificate that fails verification rejects with a CertificateError.
TLS 1.2 is the minimum version, and the cipher suites follow RFC 9325 (BCP 195). TLS 1.3 uses its standard suites. TLS 1.2 is limited to ECDHE key exchange with AES-GCM or ChaCha20-Poly1305, as DEFAULT_TLS_CIPHERS lists: no static RSA key exchange, finite-field DHE or CBC. For a server that can't do better, pass ciphers, an OpenSSL cipher list that replaces the default:
// also allow one static-RSA suite for an old server
ciphers: `${DEFAULT_TLS_CIPHERS}:AES128-GCM-SHA256`Try it against nncd
The lab device is @node-net/netconf-server, and its nncd command serves it over TLS on your machine. Install it, with the client, in a new directory:
mkdir nncd-lab && cd nncd-lab
npm init -y
npm install @node-net/netconf @node-net/netconf-serverMake a CA, a certificate for the server (localhost), and a client certificate for the user admin:
mkdir lab-tls && cd lab-tls
key() {
openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 \
-out "$1.key"
}
key ca
openssl req -x509 -key ca.key -out ca.pem -days 30 -subj /CN=lab-ca
key server
openssl req -new -key server.key -subj /CN=localhost |
openssl x509 -req -CA ca.pem -CAkey ca.key -out server.pem -days 30 \
-extfile <(echo subjectAltName=DNS:localhost)
key admin
openssl req -new -key admin.key -subj /CN=admin |
openssl x509 -req -CA ca.pem -CAkey ca.key -out admin.pem -days 30 \
-extfile <(echo extendedKeyUsage=clientAuth)nncd's config names the device and a TLS listener. The listener trusts the CA, and its cert-to-name entry maps any certificate the CA issued to a user, named by the certificate's common name. users lists who may log in:
FP=$(openssl x509 -in ca.pem -noout -fingerprint -sha256 |
sed 's/.*=/04:/')
cat > server.json <<EOF
{
"device": "../node_modules/@node-net/netconf-server/devices/lab/device.json",
"listen": {
"tls": {
"cert": "server.pem",
"key": "server.key",
"ca": ["ca.pem"],
"certToName": [
{ "id": 1, "fingerprint": "$FP", "mapType": "common-name" }
]
}
},
"users": [{ "username": "admin" }]
}
EOF
cd ..
npx nncd --config lab-tls/server.jsonnncd logs Listening for NETCONF over TLS on port 6513. In another terminal, in the same directory, save the program as lab-tls/client.mjs, connecting to localhost with the files you made:
import { readFileSync } from 'node:fs';
import { connect, tls } from '@node-net/netconf';
const client = await connect({
transport: tls({
host: 'localhost',
cert: readFileSync('lab-tls/admin.pem'),
key: readFileSync('lab-tls/admin.key'),
ca: readFileSync('lab-tls/ca.pem'),
}),
});
console.log(await client.content.readValue('/ietf-system:system/hostname'));
await client.close();node lab-tls/client.mjs prints lab1, and nncd logs the session with username=admin transport=tls. A client certificate from another CA, or one for a user not in users, is refused with an AuthenticationError.
Session options
Options after transport shape the session. Here a client gives each RPC 10 seconds, and sends an operation the server's capabilities don't cover with a warning, instead of refusing it:
import { connect, ssh, knownHostsFile } from '@node-net/netconf';
const transport = ssh({
host: 'router1',
username: 'admin',
password: () => process.env.ROUTER_PASSWORD!,
hostKey: knownHostsFile(),
});
const client = await connect({
transport,
timeouts: { rpc: 10_000 },
capabilityCheck: 'warn',
});
client.connectOptions.timeoutsThese are all of them:
await connect({
transport,
// the defaults, in ms
timeouts: { connect: 30_000, hello: 30_000, rpc: 60_000, close: 5_000 },
// RPCs awaiting a reply at once; later ones queue
maxInFlight: 32,
// largest message accepted, in bytes
maxMessageBytes: 64 * 1024 ** 2,
// deepest nesting and most nodes in a received message
parseLimits: { maxDepth: 256, maxNodes: 1_000_000 },
// or 'warn', 'off'
capabilityCheck: 'strict',
// anything with trace/debug/info/warn/error; silent by default
logger: console,
// least severe level logged; 'trace' (the default) logs everything
logLevel: 'trace',
signal: AbortSignal.timeout(10_000),
// for format: 'json'; see JSON and YANG
yang: { modules: './yang', requireSchema: false, cache },
});maxMessageBytes and parseLimits bound the memory a broken or hostile server can make the client use. Each message's limit is checked as its bytes arrive, so an over-limit message is refused before it is held in full. However the server splits the message into chunks, the client holds at most about twice maxMessageBytes for it while it arrives, plus one copy when it is handed on. parseLimits is checked in one pass over a message's text before any of it is parsed. Its nodes are elements, attributes (namespace declarations included), text runs, comments, processing instructions and CDATA sections. Parsing costs roughly 0.1–0.3 KB of heap per node at its peak, about 8 times the size of a large reply's text, so the default allows up to about 300 MB, or about 330 MB when every element declares a namespace. A namespace declaration costs the same however many others are in scope. Raise maxNodes only for replies you know are that large, and only with the heap to match. Passing either limit is a FramingError or XmlError that closes the session, like any other broken message.
yang sets up JSON conversion: YANG modules to use before the bundled ones and <get-schema>, whether to refuse a schema-less conversion, and a YangCache to share between clients.
Every request also takes its own { timeout, signal }. A timeout rejects with a TimeoutError whose phase is connect, hello or rpc, and the session stays open after an RPC timeout.
Every timeout is in milliseconds, and the same rules apply to all of them:
Infinitymeans no limit.- A value above 2,147,483,647 (about 24.8 days, the longest timer the platform has) is shortened to it.
- Zero, a negative number or
NaNis aRangeError, and a value that isn't a number is aTypeError. Either is thrown before anything is sent, soconnect()rejects before it opens a connection. Zero doesn't mean "no limit": useInfinityfor that.
Logged message bodies are redacted: the text inside password-like elements becomes ***. Pass redact to use your own rule (Redaction).
client.connectOptions holds the options you passed to connect(), as a frozen copy of the top level. Nested objects such as namespaces are the ones you passed. Its profile is what you passed, so it may be an autoDetect([...]): client.profile is the profile it chose. Credentials stay inside transport, which is a function.
Logging
Pass logger to see what the session is doing, and logLevel to choose how much. Both can be changed while the client is open. See Logging and tracing.
Closing
There are several ways to close a client session:
// sends <close-session>, then closes the transport
await client.close();
// closes at the end of the scope
await using client = await connect(…);
// closes when the function settles
await withClient(options, async (client) => …);close() can be called more than once. The 'closed' event fires exactly once, with a cause if the session ended because something failed.
Reconnecting
A session ends when the connection drops, such as when the device reboots. Requests in flight then reject with SessionClosedError, and the 'closed' event has the cause. A long-running service connects again. reconnecting() does that with backoff, and gives you each new client:
import { reconnecting } from '@node-net/netconf';
import { subscriptions } from '@node-net/netconf/operations/subscriptions';
const options = { transport, extensions: [subscriptions] };
// Runs once per session; the next client comes when this session ends
for await (const client of reconnecting(options)) {
await using changes = await client.ops.subscriptions.establish({
datastore: 'running',
onChange: { syncOnStart: true },
});
for await (const update of changes) handle(update);
}The loop body restores what the session had, because only you know what is safe to redo. reconnecting() sends no request of its own and never repeats one. A request in flight when the connection dropped rejected with SessionClosedError, and it's up to you whether to send it again on the new session. Subscriptions belong to a session, so re-establish them in the body. A body can also set up listeners and return: the next client still comes only once the session ends.
A persistent confirmed commit survives the session that started it. Remember its persistId, and settle it from the next session:
let pending: string | undefined;
for await (const client of reconnecting(options)) {
if (pending !== undefined) {
// Still reachable after the change: confirm it (or cancelCommit)
await client.ops.commit({ persistId: pending });
pending = undefined;
}
// ...work, setting pending when you make a persistent confirmed commit
}Between attempts it waits retry.initialDelay (1 second), doubled (retry.factor) after each further failure up to retry.maxDelay (60 seconds). Each wait is a random 50–100% of that (retry.jitter: false turns this off). A session that stays open for maxDelay resets the backoff, so a server that accepts and then drops at once isn't retried in a tight loop. onRetry is told each wait's attempt number, delay and error:
const clients = reconnecting({
...options,
retry: { initialDelay: 500, maxDelay: 30_000, maxAttempts: 10 },
onRetry: ({ attempt, delay, error }) =>
console.warn(`attempt ${attempt} in ${delay} ms: ${error.message}`),
signal: AbortSignal.timeout(3_600_000),
});Transport failures, connect and hello timeouts and lost sessions are retried. A failure that retrying can't fix ends the loop with that error: an AuthenticationError, HostKeyError or CertificateError, a HelloError, an invalid profile, a missing capability, or an error that isn't a NetconfError. So does the last error after retry.maxAttempts consecutive failed attempts (unlimited by default). Leaving the loop with break, return or a throw, or await using on what reconnecting() returns, closes the current client. Aborting signal does the same, and ends the loop without an error.
reconnecting() takes the same options as connect(), and is in @node-net/netconf/core too.