@sirena-lwm2m/coap
v0.10.1
Published
RFC 7252 CoAP server stack for Node.js (>= 24): UDP and TCP (RFC 8323) transports, DTLS/TLS secure transports, a router with middleware, block-wise transfers (RFC 7959), Observe (RFC 7641), pluggable transaction stores and OpenTelemetry metrics.
Readme
@sirena-lwm2m/coap
RFC 7252 CoAP server stack for Node.js (>= 24): UDP and TCP (RFC 8323) transports, DTLS/TLS secure transports, a router with middleware, block-wise transfers (RFC 7959), Observe (RFC 7641), pluggable transaction stores and OpenTelemetry metrics.
| Capability | Docs | |---|---| | UDP transport | udp-transport | | TCP transport (RFC 8323) | tcp-transport | | Secure transports | security | | Router and middleware | router | | Block-wise transfers | blockwise | | Observe | observe | | Transaction stores | store | | Observability | observability | | Full API | api-reference | | Contributing | mutation-testing, releasing |
Installation
npm install @sirena-lwm2m/coapQuick start — UDP
import { createServer, Response, stringToBytes } from '@sirena-lwm2m/coap';
const server = createServer({
listen: [{ host: '0.0.0.0', port: 5683 }],
});
server.on('request', async (req, ctx) => {
await ctx.respond(Response.ok(stringToBytes(req.url)));
});
await server.start();
console.log('Listening on:', server.listenerSummary());TCP transport (RFC 8323)
The server supports CoAP over TCP using the coap+tcp:// URI scheme. Bind one or more TCP listeners alongside UDP by passing URI strings to the listen array.
import { createServer, Response, stringToBytes } from '@sirena-lwm2m/coap';
const server = createServer({
listen: [
'coap://127.0.0.1:5683', // UDP
'coap+tcp://127.0.0.1:5684', // TCP (RFC 8323)
],
});
server.on('request', async (req, ctx) => {
// ctx.transport is 'udp' or 'tcp'
console.log(`[${ctx.transport}] ${req.url}`);
await ctx.respond(Response.ok(stringToBytes(`hello via ${ctx.transport}`)));
});
await server.start();
console.log('Listening on:', server.listenerSummary());
await server.stop();See examples/slice-2.ts for a working dual-transport demo.
See docs/tcp-transport.md for framing details, connection multiplexing, and configuration.
Secure transports (coaps:// and coaps+tcp://)
Breaking in 0.10.0:
coaps://is now DTLS 1.2 over UDP (RFC 7252 section 9). Earlier versions served it as TLS over TCP. For TLS over TCP usecoaps+tcp://.
const server = createServer({
listen: ['coaps://0.0.0.0:5684', 'coaps+tcp://0.0.0.0:5685'],
security: { mode: 'psk', psk: (identity) => lookupKey(identity) }, // or { mode: 'x509', key, cert }
});
server.on('dtls-handshake', ({ peer, durationMs }) => { /* peer.mode: 'psk' | 'x509' */ });Built-in DTLS provider: DTLS 1.2 server and client session; cipher suites TLS_PSK_WITH_AES_128_CCM_8, TLS_PSK_WITH_AES_128_GCM_SHA256, TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8, TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256; extended master secret; X.509 mode needs an EC (ECDSA) key; no resumption, renegotiation or DTLS 1.3. security.sessionCacheSize is deprecated and ignored.
Client DTLS over UDP:
import { DtlsClientSession } from '@sirena-lwm2m/coap';
const session = new DtlsClientSession({ psk: { identity, key } });
const flight = session.start(); // send flight.outgoing; feed peer packets to session.handleDatagram(buf)MTU: a CoAP message sent over coaps:// may be at most dtlsMaxPayload bytes (default 1200, the whole message). DTLS does not fragment; larger sends fail with 'exchange-error', so use block-wise transfer for large bodies.
coaps+tcp:// is TLS over TCP (Node tls) and emits tls-handshake. If you used coaps:// for TLS over TCP before 0.10.0, switch to coaps+tcp://; see the migration notes in docs/security.md.
Replace the DTLS implementation with ServerOptions.dtlsProvider (a DtlsProvider factory returning a DtlsSocket). See the API reference.
Router and middleware
createApp (from @sirena-lwm2m/coap/router) attaches a radix-tree router to a server. Path templates use {name} parameters, available as ctx.params. discovery: true serves /.well-known/core. See docs/router.md and examples/slice-4.ts.
import { createServer, Response, stringToBytes } from '@sirena-lwm2m/coap';
import { createApp } from '@sirena-lwm2m/coap/router';
const server = createServer({ listen: ['coap://0.0.0.0:5683'] });
const app = createApp({ server, discovery: true });
app.use((req, ctx, next) => next()); // middleware
app.add({
path: '/3/{iid}',
method: 'GET',
handler: async (_req, ctx) => {
await ctx.respond(Response.ok(stringToBytes(`instance ${ctx.params?.iid}`)));
},
});
await server.start();Block-wise transfers (RFC 7959)
blockwiseMiddleware reassembles Block1 uploads and chunks Block2 downloads, so handlers see a whole body and respond once. See docs/blockwise.md and examples/slice-5-firmware.ts.
import { blockwiseMiddleware } from '@sirena-lwm2m/coap/blockwise';
app.use(blockwiseMiddleware({ maxBytes: 4 * 1024 * 1024, idleTimeoutMs: 10_000 }));Observe (RFC 7641)
Call ctx.observe(observable) in a GET handler after responding; registered clients receive a notification for each value the Observable emits. See docs/observe.md and examples/slice-6-temperature.ts.
import { Response } from '@sirena-lwm2m/coap';
import type { Observable, Observer, Unsubscribe } from '@sirena-lwm2m/coap';
const observers = new Set<Observer<Uint8Array>>();
const temperature: Observable<Uint8Array> = {
subscribe(o: Observer<Uint8Array>): Unsubscribe {
observers.add(o);
return () => { observers.delete(o); };
},
};
app.add({
path: '/temperature',
method: 'GET',
handler: async (_req, ctx) => {
await ctx.respond(Response.ok(new Uint8Array([20])));
ctx.observe(temperature); // no-op for non-Observe requests
},
});
// later: for (const o of observers) o.next(new Uint8Array([21]));Transaction stores
CON/NON de-duplication uses a TransactionStore; the default is in-memory. createSqliteStore (needs the optional better-sqlite3 package) makes it durable across restarts. See docs/store.md and examples/slice-7-file-store.ts.
import { createSqliteStore } from '@sirena-lwm2m/coap/store';
const store = await createSqliteStore({ path: './dedup.db' });
const server = createServer({ listen: ['coap://0.0.0.0:5683'], store });Observability
ServerOptions.metrics takes a CoapMetrics. tryBindOtel lazily loads @opentelemetry/api and falls back to no-op instruments if it is absent. See docs/observability.md and examples/slice-7-otel.ts.
import { tryBindOtel } from '@sirena-lwm2m/coap/observability';
const metrics = await tryBindOtel('@sirena-lwm2m/coap');
const server = createServer({ listen: ['coap://0.0.0.0:5683'], metrics });ExchangeContext
Every 'request' event handler receives a Request and an ExchangeContext:
interface ExchangeContext {
remote: string; // "ip:port" of the sender
local: string; // "ip:port" of the receiving socket
transport: 'udp' | 'tcp'; // which transport delivered this request
token: Uint8Array; // CoAP token bytes
messageId: number; // CoAP message ID (0 for TCP)
options: CoapOption[]; // raw parsed options
peer: Peer; // anonymous, or psk identity / x509 certChain
respond(res: Response): Promise<void>;
cancel(): void;
abort(code: CoapCode): void;
}License
MIT
