Docs

TypeScript on Node.js: calling side and device side

The package @huelake/connectivitizer connects a Node.js program to a service on a device (calling side), or makes a Node.js program a device that exposes local services (device side). For phone apps see React Native. For a web page or a WebView, where nothing else can run, the package has a browser entry point: a backup only, because every session of a browser goes through the relay and counts as relayed traffic.

Install

Bash
npm install @huelake/connectivitizer

From npm. ESM only, Node.js 20 or newer.

What you need

Decide first whether your program is the calling side (it connects to a device), the device side (it offers services), or both. Then have these ready:

  • Calling side: an API key (czk_…; web app: Credentials → Create an API key) for a program you run yourself. A program that other people install gets a key of its own with linkApp instead (below).
  • Device side: a device key (czd_…; web app: Credentials → Create a device key) and the device name apps will address the device by. One device key serves any number of devices, each under its own name.
  • Device side: the services to expose, each with a name and its local host:port. Nothing else on the machine is reachable.
  • A shared key (czs_…; web app: Credentials → Generate a shared key, or npx connectivitizer keygen). The same key on both sides. It never reaches Connectivitizer.

Keep the keys in environment variables or a git-ignored file (for example .env), never in committed code.

Calling side

TypeScript
import { createClient } from '@huelake/connectivitizer';

const client = createClient({
  auth: { apiKey: process.env.CZ_API_KEY! },
  sharedKey: process.env.CZ_SHARED_KEY!,      // the same key the device has
});

const session = await client.connect('living-room-lamp', ['api']);   // device name, services
const response = await session.fetch('api', '/state');
console.log(response.status, await response.json());

console.log(session.info.mode);                // 'direct' or 'e2e-relay'
console.log(session.info.endToEndEncrypted);   // established by this endpoint, not claimed by the platform
await session.end();
await client.close();
createClient(options)auth; sharedKey; disableDirect: true to always use the relay.
client.listDevices()The devices this application may reach: name, alias, online, and the services it may use.
client.connect(device, services)Opens a session to a device by its name.
session.fetch(service, path, init)An HTTP request to the device's local service: status, headers, text(), json(), bytes(), chunks().
session.webSocket(service, path)A WebSocket to the device's local service.
session.openStream(service)The raw byte stream, for any other TCP protocol.
session.infomode, transport, endToEndEncrypted, trust, peerAddress, directFailureReason.
session.end(), client.close()End the session, or everything.

Errors are ConnectivitizerError with a stable code: see Error codes.

Linking a program instead of giving it a key

A program that other people install should not ask them to type in a key. linkApp gets it a key of its own: the person signs in on this web app and approves.

TypeScript
import { linkApp } from '@huelake/connectivitizer';

const linked = await linkApp({
  client: 'Lamp app',                               // the name it appears under in the web app
  onPrompt: ({ url, code }) => console.log(`Open ${url} and confirm the code ${code}`),
});
// linked.apiKey is returned this once: store it safely and use it as auth: { apiKey } from then on

It rejects with LINK_DENIED when the person refused and with LINK_EXPIRED after ten minutes. The linked program is listed, and revoked, under Credentials.

Device side

TypeScript
import { createAgent } from '@huelake/connectivitizer';

const agent = createAgent({
  deviceKey: process.env.CZ_DEVICE_KEY!,     // from the workspace
  name: 'home-pc',                           // how apps address this device; it stays the same
  sharedKey: process.env.CZ_SHARED_KEY!,
  services: { api: '127.0.0.1:8080' },       // nothing else is reachable
  log: (line) => console.log(line),
});
await agent.run();                           // until agent.stop()

The device appears under Devices the first time it connects.

A device that calls another device

A device opens sessions to other devices with agent.connect, over the connection to the platform it already has. It needs no API key, but two things:

  • Its device key has Its devices may open sessions to other devices switched on (web app: Credentials, when you create or edit the key). Without it, or for a device or service outside the access rules of the key, the platform refuses with FORBIDDEN.
  • It holds the shared key of the other device, in sharedKey. With several keys the device uses the one named like the other device, else its only one, else the one named default.
TypeScript
import { createAgent } from '@huelake/connectivitizer';

const agent = createAgent({
  deviceKey: process.env.CZ_DEVICE_KEY!,     // a device key that may open sessions
  name: 'door-bell',
  sharedKey: process.env.CZ_SHARED_KEY!,     // the key the other device has as well
  services: { api: '127.0.0.1:8080' },
  log: (line) => console.log(line),
});
const running = agent.run();

const session = await agent.connect('hallway-chime', ['api']);   // waits until the device is connected
const response = await session.fetch('api', '/ring', { method: 'POST' });
console.log(response.status, session.info.mode);
await session.end();
agent.connect(device, services)Opens a session to another device by its name. The session is the same object client.connect returns.
agent.listDevices()The devices this device may reach, without itself. For devices that log in with a device key.
agent.outgoingSessionsThe sessions this device opened that are still running. agent.openSessions are the ones opened to it.

The device stays reachable while it calls, and agent.stop() ends the sessions it opened as well. A device cannot call itself (INVALID_REQUEST). React Native has no device side, so an app there is a calling application only.

Good to know

  • Direct sessions need nothing from your code: the SDK finds the machine's addresses (IPv4 and IPv6), binds UDP and punches through the routers. Whether a session is direct depends on the networks: Troubleshooting.
  • A client may hold several shared keys (sharedKey: [parseSharedKey(…), …]): it uses the one named like the device, else its only one, else the one named default.
  • Certificates and pairing (instead of a shared key) are available on Node.js and compatible with cz: StateDirectory, EndpointIdentity, TrustStore, createInvitation / acceptInvitation / completePairing. You need them only if you want certificates instead of a shared key; React Native has no certificates.

A screen in the Connectivitizer app

Your device can bring its own screen: one HTML page that the Connectivitizer app shows when someone taps the device, so there is no app to write. The device serves two files on the service the app connects to (ui, else api): GET /.cz/ui.json, the manifest {"name": "Desk lamp", "entry": "/.cz/ui.html", "version": "1"}, and GET /.cz/ui.html, the page.

The page, as ui.html: a switch, a slider and a value the device reports, with a comment at each part to show where yours go.

HTML
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">


<style>
  body { margin: 0; padding: 24px; font: 16px system-ui, sans-serif; background: #fdf6e3; color: #3b3526; }
  h1 { font-size: 44px; margin: 4px 0 24px; }
  label { display: block; margin: 28px 0 8px; }
  button { font: inherit; padding: 12px 24px; border-radius: 12px; border: 0; background: #b58900; color: #fff; }
  input, select { font: inherit; padding: 10px; border-radius: 10px; border: 1px solid #c8b98a; background: #fff; color: inherit; }
  input[type=range] { width: 100%; padding: 0; border: 0; background: none; accent-color: #b58900; }
</style>


<p>Desk lamp</p>
<h1 id="state">…</h1>
<button id="toggle">Switch</button>

<label for="level">Brightness: <b id="level-value">…</b> %</label>
<input id="level" type="range" min="0" max="100" step="5">

<p>Running for <b id="uptime">…</b> s</p>


<script>
  const $ = (id) => document.getElementById(id);

  // The device answers every request with its state, e.g. {"on":true,"level":40,"uptime":120}.
  // show() puts it on the page: one line per value.
  const show = async (response) => {
    const s = await response.json();
    $('state').textContent = s.on ? 'On' : 'Off';
    $('level-value').textContent = s.level;
    if (document.activeElement !== $('level')) $('level').value = s.level;
    $('uptime').textContent = s.uptime;
  };
  const refresh = () => fetch('/state').then(show).catch(() => { $('state').textContent = 'No /state yet'; });

  // A tap or a change sends a request; the answer is shown right away.
  $('toggle').onclick = () => fetch('/toggle', { method: 'POST' }).then(show);
  $('level').oninput = () => { $('level-value').textContent = $('level').value; };
  $('level').onchange = () => fetch('/level?value=' + $('level').value, { method: 'POST' }).then(show);

  refresh();
  setInterval(refresh, 2000);   // new values every 2 seconds
</script>
</html>

A web server for the page, with ui.html next to it. It listens on 127.0.0.1:8080, which the device side above exposes as api (services: { api: '127.0.0.1:8080' }).

JavaScript
// server.mjs, with ui.html next to it. Start it in the same program as the agent, or on its own.
import { createServer } from 'node:http';
import { readFileSync } from 'node:fs';

const manifest = '{"name":"Desk lamp","entry":"/.cz/ui.html","version":"1"}';
const page = readFileSync(new URL('./ui.html', import.meta.url));
const started = Date.now();
let on = false;
let level = 50;
const state = () => JSON.stringify({ on, level, uptime: Math.round((Date.now() - started) / 1000) });

createServer((request, response) => {
  const send = (type, body) => response.writeHead(200, { 'Content-Type': type }).end(body);
  const url = new URL(request.url, 'http://device');
  const route = `${request.method} ${url.pathname}`;
  if (route === 'GET /.cz/ui.json') return send('application/json', manifest);
  if (route === 'GET /.cz/ui.html') return send('text/html; charset=utf-8', page);
  if (route === 'GET /state') return send('application/json', state());
  if (route === 'POST /toggle') { on = !on; return send('application/json', state()); }
  if (route === 'POST /level') {
    level = Math.min(100, Math.max(0, Number(url.searchParams.get('value')) || 0));
    return send('application/json', state());
  }
  response.writeHead(404).end();
}).listen(8080, '127.0.0.1');

More controls to copy, a preview on your computer that needs no device, what a page can do (colours for the app's bar, the camera, the location, links), and finished examples, with a short start for anyone new to HTML: Device screens.