Skip to content

The framed message channel ​

For protocol tools and tests, you can use the RFC 6242 framing layer without a session. You then do everything a session normally does: send the hello, switch to chunked framing when both sides agree on base:1.1, number your own message-ids, and parse the replies.

ts
import { NETCONF_NS, openChannel, ssh } from '@node-net/netconf';

const factory = ssh({ host, username, password, hostKey });
const connection = await factory(AbortSignal.timeout(10_000));
const channel = openChannel(connection, {
  // each whole message, in order
  message: (text) => console.log('<<', text),
  // once: closed, failed or bad framing
  end: (reason) => console.log('ended:', reason.message),
});

// nothing is sent until you write
channel.write(channel.encode(myHello));
// both directions, from the next message
channel.useChunkedFraming();
const rpc = `<rpc message-id="1" xmlns="${NETCONF_NS}"><get/></rpc>`;
channel.write(channel.encode(rpc));
await channel.close();

In end-of-message framing, encode() refuses a message that contains ]]>]]>. An incoming message larger than maxMessageBytes (64 MiB by default) ends the channel with a FramingError.

Decoding bytes you already have ​

To decode bytes you already hold, such as a copy of a stream you're watching, use FrameDecoder on its own. It's the same decoder a session uses:

ts
import { FrameDecoder } from '@node-net/netconf';

// end-of-message framing to start with
const decoder = new FrameDecoder();
decoder.push(bytes);
for (let message; (message = decoder.next()) !== undefined; ) {
  console.log(message);
}
// between messages, once both hellos advertise base:1.1
decoder.setMode('chunked');

Malformed framing makes next() throw a FramingError, and the decoder can't be used after that.

push() takes a Uint8Array (a Node Buffer is one). To avoid copying large replies, the decoder may keep a reference to the bytes you push until it has decoded them, so don't reuse or change that array afterwards.

A session without a client ​

One step up from the channel, openSession(connection) gives you the messages layer on its own: it frames the connection, exchanges hellos, agrees the base version, and resolves with a Session ready for RPCs. It is client.session without the client: no device profile, no capability checks, no client.ops or client.content, and no extensions. Use it for protocol tools, or when you build every request yourself:

ts
import { openSession, x } from '@node-net/netconf';

// lab is the REPL's transport to the lab device
const connection = await lab(AbortSignal.timeout(10_000));
const session = await openSession(connection);

// '1.1', and the session-id the server assigned
console.log(session.baseVersion, session.sessionId);
// true
console.log(session.serverCapabilities.has(':candidate'));

const reply = await session.rpc(
  x('get-config', x('source', x('running'))),
);
reply.data;

await session.close();

session.rpc() adds the <rpc> element and the message-id, and resolves with an RpcReply, exactly as client.session.rpc() does: see RPC and reply. The options take what a device profile would otherwise supply, such as quirks, capabilities to advertise, timeouts and parseLimits. If the hello fails, the connection is closed before openSession() rejects. Closing the session sends <close-session> and then closes the connection.

Your own transport ​

A transport is a ConnectionFactory: a function that takes an AbortSignal and resolves with a Connection. Anything that can produce one, such as a test harness, another tunnel or an in-process server, can be passed to connect({ transport }).

A Connection moves bytes and nothing else. Framing, the hello and everything above are the library's job:

ts
interface Connection {
  readonly peer: { host: string; port: number; identity?: string };
  // Called once. Bytes that arrived earlier are held for it.
  receive(receiver: ConnectionReceiver): void;
  write(bytes: Uint8Array): void;
  // End our sending side; what the peer sends still arrives.
  end(): void;
  // Drop the connection at once.
  destroy(): void;
  // Close gracefully. Idempotent; never rejects.
  close(): Promise<void>;
}

interface ConnectionReceiver {
  data(chunk: Uint8Array): void;
  // The peer ended its sending side.
  end(): void;
  // Exactly once, last; with the error if it failed.
  close(error?: Error): void;
}

You rarely implement one by hand. With a Node.js stream (a socket, a child process's stdio, a tunnel), duplexConnection() adapts it:

ts
import { connect as tcp } from 'node:net';
import { connect, duplexConnection } from '@node-net/netconf';

const peer = { host: 'router1', port: 830 };
const client = await connect({
  transport: async () => {
    const socket = tcp(peer.port, peer.host);
    await new Promise((resolve) => socket.once('connect', resolve));
    return duplexConnection(socket, { peer });
  },
});

connectionPair() returns two connected in-memory ends, and joinConnections(a, b) splices two connections so data, ends and closes flow both ways. FakeServer is built on the pair (see Testing).

Outside Node.js ​

@node-net/netconf/core is the part of the library that needs nothing from Node.js: the protocol, the client, the device profiles that ship with the library, and the connection interface with connectionPair(). It runs in a browser, a web worker or another JavaScript runtime, against any transport you can give it, such as an in-process server or a WebSocket relay you write yourself.

ts
import { connect } from '@node-net/netconf/core';
import { FakeServer } from '@node-net/netconf/testing';

const server = new FakeServer();
const client = await connect({ transport: server.transport() });

@node-net/netconf is a superset of it that adds what needs Node.js: ssh(), tls(), call home, known_hosts, duplexConnection() and loading profiles from files. YANG module directories in yang.modules need Node.js too; with @node-net/netconf/core, pass the modules as a ModuleSource instead, such as memorySource() from @node-net/yang/core.

Released under the MIT Licence.