Server API
import { Server } from 'iosignal';
const server = new Server({ port: 7777 });
// When the application shuts down:
// server.close(() => console.log('Server closed'));
Provide at least one transport option: port, httpServer, or congPort. port opens WebSocket; httpServer attaches to an existing HTTP server, with wsPath selecting the upgrade path; congPort serves the Arduino TCP transport.
| Option | Meaning |
|---|---|
heartbeatInterval, heartbeatGrace | Liveness check interval and answer grace, in milliseconds |
logMessages, logStats | Log each received message's type and tag (never the payload), and print a one-line summary every N ms. Read current figures with server.stats() |
maxPayload, maxBufferedBytes | Largest WebSocket message and CongSocket frame, and the unsent-data limit above which a connection is closed (bytes) |
trustProxy | When X-Forwarded-For/-Proto are trusted: 'private' (default, loopback/private peers only), true, false, or a number of trusted proxy hops |
membersOnly | Drop signals from connections that are not authenticated; configure an authentication provider or localAuth |
localAuth | 8.1.0+. Local test logins without a key list: 'idKey' (key = ID) or { mode: 'sharedKey', key, role, quota }; the CID is the login ID. Cannot be combined with an authManager argument. Local test logins |
duplicateLogin | 8.0.0+. When the same authenticated CID is already online, 'keepNew' (default) replaces the old connection and 'keepOld' rejects the new login. Applies to this server's authentication manager only. |
quotas, anonymousQuota | Named quota profiles and the profile of unauthenticated connections. Operator-configured, not a fixed library limit |
retain | Retained messages: enabled, size and count limits, budgets per owner. Adjustable later on server.retain |
security.maxClockSkewMs | Positive safe integer clock-skew limit |
security.authChallengeMaxAgeMs | Positive safe integer challenge lifetime |
security.maxReplayEntries | Positive safe integer replay-cache capacity |
Consult the installed serverOption defaults before overriding limits. server.stats() returns connection, channel, retain and traffic figures, including messages dropped by quota. close(callback) closes the server and calls the callback after shutdown. For authenticated deployments, pass a BohoAuth instance as the second constructor argument; see authentication. For the duplicate login policy and onAuthEvent, see duplicate logins.
Quota and limits
Quota is an operator policy, not a fixed library constant. From 9.0, a connection's role (what it may do) is separate from its quota profile (how much it may send).
- Quota profiles are named sets of limits in the
quotasoption:maxMessageBytes,fanout(subscribers one publish is delivered to),msgPerSec,bytesPerSecandmaxConnectionsper account.nullis unlimited. The server always enforces them, and they can be adjusted on a running server throughserver.quotas. - Unauthenticated connections use the
anonymousQuotaprofile. A login uses its key entry's quota, or the result ofBohoAuth'sresolveQuota(authInfo, role)option. - The built-in profiles (
anonymous,basic,pro,unlimited) are starting values for the operator to adjust; seeserverOption. Set and verify them for production. Public services follow their provider's policy. - The client learns its
io.quota.maxMessageBytesfrom the server'sQUOTAmessage (it arrives beforeready;nullis unlimited). Messages over the per-second message or byte limit are dropped without notice.
const server = new Server({
port: 7777,
quotas: { anonymous: { maxMessageBytes: 64 * 1024 }, basic: { fanout: 200 } },
anonymousQuota: 'anonymous'
});
Protocol limits such as the 255-byte tag and subscription list are separate from quota.
Per-device delivery policy
From 9.6.0, a device with an owner can choose whose CID unicasts (deviceCID@topic) it accepts. The owner is the uid of the key entry it logged in with. The built-in key providers (File, String, Redis, Local) supply no uid, so the feature is used with a custom key provider whose getAuth(id) returns uid and rxPolicy. A device without a uid is never filtered.
// Part of the authInfo returned by a key provider's getAuth(id)
{ cid: 'lamp1', uid: 'user-a', rxPolicy: {
v: 1,
mode: 'allowlist', // 'open' (default) | 'allowlist' | 'denylist'
anonymous: 'deny', // unauthenticated senders: default deny for allowlist, allow for denylist
publish: 'all', // 'policy' also filters CID-publication (@topic, @$topic) subscribers
allow: { cids: ['panel1'], uids: ['user-b'] },
deny: { cids: [], uids: [] }
} }
- The first matching rule wins: the device itself, the owner's
uidor theadminrole → allow; an authenticated sender's CID indeny.cids/allow.cids→ deny/allow; the sender'suidindeny.uids/allow.uids→ deny/allow; an unauthenticated sender →anonymous; otherwise themodedefault. Each list holds up to 200 entries. - A denied sender gets the same
Invalid cidreply as for an offline CID, so it cannot tell it is blocked. server.manager.setDeliveryPolicy(cid, policy)replaces a connected device's policy at once. It throws on an invalid policy and returnsfalsewhen no such device is connected or it has no owner. The next login reads the key provider's policy again.- Each denial increments
counters.policyDeniedinserver.stats(), and when someone listens the server emits'delivery:denied'(kind,cid,did,owner,other,at).
Server host
From 9.13.0, server.host(name, options) registers logic that runs inside the server and decides outcomes (games, quizzes). Usage and tag rules are in Game logic inside the server, and a runnable example is Host Quiz.
| Call | Description |
|---|---|
server.host(name, { inbound, own, fanout, retain }) | Registers a host and returns a Host. name: 1-64 characters of letters, digits and _.-. inbound (required): channel tags clients send to the host; own: channel tags and @topics only the host sends. A trailing * is a prefix. fanout: most receivers of one publish (default unlimited). retain: { tags, bytes }: the host's retain budget (default retain.tagsPerOwner and bytesPerOwner) |
host.on('message', (from, tag, ...args)) | Input on an inbound tag. from is { cid, uid, role, authorized, nick, ssid }, set by the server. args have the same shape as a client's message event |
host.on('leave', (from, reason)) | A connection that has sent input closed. Not emitted when its CID moved to another connection |
host.on('error', (err)) | An exception from a message or leave handler. The server keeps running |
host.publish(tag, ...args) | Publishes on an own channel and returns the number of connections reached. A tag with $ is retained. Throws for a tag that is not own |
host.to(cid, topic, ...args) | Sends to one connection, which receives '@' + topic. Returns false when the CID is not online or the message is larger than its receive buffer |
host.participants, host.forget(cid) | Connections that have sent input (Map<cid, from>); remove one (no leave is sent) |
host.report(values) | 9.14.0. Merges values to show on the dashboard (numbers, short strings, booleans; up to 20). A null value removes that key |
host.loop(ms, fn) | 9.14.0. Runs fn(now) every ms and measures tick interval and step time. Returns a stop function. An exception from fn is reported as 'error' and the loop goes on. Read the measurements with host.loopStats() |
host.counters, host.activity(), host.journal(after) | 9.14.0. Per-host cumulative counters (inbound, rejected, denied, published, delivered, sent, joins, leaves, errors, handlerMs), each participant's inputs and first and last input time, and recent joins, leaves, blocked forgeries and errors |
host.close() | Unregisters. The tags become ordinary channels and the host's retained values are removed. server.close() closes hosts too |
server.on('host:denied', (remote, tag, hostName)) | A client sent to a host-only tag and the message was dropped |
counters in server.stats() include hostInbound (inputs handed to a host), hostRejected (inputs not handed over: end-to-end encrypted or unreadable payloads) and hostDenied (messages to host-only tags, dropped).
Dashboard
From 9.14.0, new Server({ dashboard }) turns on a web page that shows the server and its hosts. It is off by default. Screens and access are described in Server dashboard.
| Option | Default | Description |
|---|---|---|
dashboard | off | true, or an object with the fields below |
path | '/dashboard' | Page address. path + '/io.js' serves the browser client too |
access | 'open' | 'open', { token } (8 characters or more), { login: { roles, cids } } (logged-in connections with a role of roles or higher, or a CID in cids; roles defaults to ['admin']) |
panels | all | Panels shown first: server, traffic, hosts, game, participants, events |
history | 300 | Seconds kept for the charts, 10-3600 |
maxViewers | 20 | Viewers at the same time, 1-200 |
showIdentities | false when access is 'open' | Whether participant CIDs and names are shown |
- With
port, the server makes its own HTTP server and serves the page and the WebSocket on the same port. WithhttpServer, callserver.dashboard.handle(req, res)first in your request handler (truefor dashboard addresses). - The dashboard uses the
iosignal.dashboardhost (iosignal.dashboard#in,@iosignal.dashboard); other hosts cannot claim these tags. - Invalid options throw in
new Server().
Services
server.attach(name, service) registers an application service. A service exposes its allowed commands and may implement checkPermission(remote, req). Dispatch uses named command methods or the service's call(remote, req) entry point. Return responses through the installed implementation's replyService mechanism; inspect its types and service tests for the request/response contract.
From 8.0.0, a service that implements onRemoteClose(remote) is called directly by the server when a connection closes. It bypasses RPC permission and command checks, so use it for per-connection cleanup. Permissions are checked by role (hasRole(remote, 'admin'); roles, lowest first: anonymous, device, service, admin). The built-in sudo service accepts only the admin role, and RedisService(client, minRole) accepts service or higher by default. For an unauthenticated lab server, opt in explicitly with new RedisService(client, 'anonymous').
Service authorization is an application responsibility. A generic IOSignal server does not automatically provide Remocon account-management APIs. See create a server for the runnable transport example.