websocket
Official sources are open to Staxis GitLab group members:
how to join and view the code.
Repository: websocket development
Versions: tags and releases
Description
websocket accepts HTTP Upgrade requests and attaches a custom WebSocket frame engine to the shared httpListener, or starts a separate native HTTP server in isolated mode. It tracks clients, mounts URL paths, and dispatches complete text or binary messages. Its label and runtime typology are both websocket.
The main README introduces the current path-based API. WebSocket transport frames, application messages, and game actions are separate layers of responsibility: this pack does not automatically turn messages into authenticated commands, game replication, or an engine-specific multiplayer protocol.
Read before flight
-
We suggest choosing shared or isolated mode before installation and updating manifest.require accordingly. The dependency is evaluated before configuration; setting isolated=true alone does not remove it.
-
We suggest defining the application authentication flow and validating each action or binary message before accessing game state. Origin and path checks do not identify a player. Keep Vault keys and layer-access tokens on the backend.
-
We suggest using trusted TLS termination for public wss connections and reviewing proxy headers. The isolated server is plain HTTP. Only trust forwarded IPs when direct access and forwarding headers are controlled by your proxy.
-
We suggest testing browser handshakes, fragmentation, abrupt disconnects, and resource limits before deployment. Keep allowExtensions=false as the supplied baseline: this engine does not implement compression. Apply application-level message, queue, and processing budgets.
Requirements and Installation
Shared mode requires httpListener, whose supplied manifest already permits websocket. Assemble the HTTP stack and attach httpListener before websocket, then place the layer consuming this API after it. See the HTTP Series for HTTP responsibilities. Install through the Manager:
manager -> install -> websocket
The pack uses Node.js built-ins and its own frame engine. It requires no external npm WebSocket library or per-pack allowedDeps, allowedImports, or allowedFileAccess exceptions while config.engineopt.guard.allowNodeDeps is enabled. Prepare KEY:WEBSOCKET and the normal project integrity/Vault material through First setup.
Files Map
| File | Purpose |
|---|---|
| manifest.json | Declares identity and the shared-listener dependency |
| configs.js | Supplies listener, handshake, IP, frame-size, and timeout settings |
| main.js | Resolves the server, checks upgrades, tracks clients, and publishes the path-based API |
| webSocketEngine.js | Parses and builds frames, reassembles messages, and handles control frames and socket writes |
| README.md | Current setup and path-based usage overview |
| README.api.md, README.parser.md, README.shield.md | Supplementary references containing older API and proposed application/shield contracts; compare with the current implementation |
| .fomap | Resources managed by pack installation and export |
Shared and Isolated Listener Modes
In shared mode, keep "require": ["httpListener"] in the websocket manifest and config.serveropt.websocket.isolated=false. The layer obtains the native HTTP server and attaches its upgrade handler. It uses the same listening address as HTTP; it does not open a second port.
For an independent server, change the manifest's require field to an empty array, then merge the isolated settings below. This starts a dedicated native HTTP listener; an ordinary HTTP request to that listener receives OK. It does not automatically run the serverApp middleware chain.
{
"require": []
}
// config.js -> config (merge into the exported object)
serveropt: {
websocket: {
isolated: true,
host: '127.0.0.1',
port: 8081,
trustProxy: false
}
}
Use an explicit host and port for an isolated deployment. Host, port, and websocket.trustProxy are isolated-server settings. Shared mode instead derives forwarded-IP handling from config.serveropt.proxySets and config.serveropt.proxyLimiter, with the older proxylimiter spelling also recognized.
Configuration
All pack settings belong to config.serveropt.websocket. Merge this supplied baseline into the exported config.js object:
// config.js -> config (merge into the exported object)
serveropt: {
websocket: {
isolated: false,
host: '0.0.0.0',
port: null,
trustProxy: false,
pathsAllow: ['/ws'],
originAllow: [],
allowSubprotocols: [],
allowExtensions: false,
maxConnPerIp: 50,
upgradeRate: { windowMs: 10000, limit: 25 },
maxFrameSizeBytes: 1024 * 1024,
pingIntervalMs: 30000,
idleTimeoutMs: 90000
}
}
| Option under config.serveropt.websocket | Behaviour |
|---|---|
| isolated, host, port, trustProxy | Choose listener ownership and isolated address/proxy policy; shared mode ignores the isolated address |
| pathsAllow | Initial exact URL paths eligible for upgrades; mount() can add more |
| originAllow | Hostname rules, including *.example.com; [] skips Origin checks. A nonempty list requires an Origin header |
| allowSubprotocols | Select a matching offered subprotocol when possible; this is not a mandatory-protocol authentication check |
| allowExtensions | Controls rejection of extension offers and the parser RSV check; it does not implement permessage-deflate |
| maxConnPerIp | Maximum tracked simultaneous connections per resolved IP |
| upgradeRate.windowMs, upgradeRate.limit | Window in milliseconds and the allowed upgrade-attempt count per resolved IP |
| maxFrameSizeBytes | Incoming frame and outgoing payload size limit; default 1 MiB |
| pingIntervalMs, idleTimeoutMs | Server ping interval and inactivity-close timeout, in milliseconds |
pathsAllow checks the URL pathname without its query string. Origin entries are hostnames, not full URLs or user identities. The connection and upgrade counters are local to this layer instance, not a distributed quota service. Set positive limits explicitly; several zero values fall back to defaults.
Authorize a Calling Layer
Add the requesting pack's manifest.label to websocket's manifest permits before it acquires the API. The supplied manifest has no consumer permits list. Merge this field without replacing the rest of the manifest:
{
"permits": ["websocket", "someOtherLayer"]
}
Inside someOtherLayer, use its engine and layers equipment. A consumer can declare "require": ["websocket"]. The Vault arguments below are pack labels; the layers.require argument is the provider's runtime typology.
const tokenAccess = engine.vault.requireAccess(
'someOtherLayer', // Requesting pack's manifest.label
'websocket' // Provider pack's manifest.label
)
if (typeof tokenAccess !== 'string' || tokenAccess.startsWith('error:')) {
throw new Error('WebSocket layer access was denied')
}
const instance = layers.require(
'websocket', // Provider's manifest.typology: its runtime slot
tokenAccess,
false
)
const ws = instance?.assets
if (!ws || typeof ws.mount !== 'function') {
throw new Error('WebSocket layer is unavailable')
}
Mount a Path and Handle Text
The following is the current README's mount(path, opts, handler) pattern with a small application-defined JSON contract. The layer itself accepts text and binary; JSON parsing and the echo action whitelist below are application code. This is a connectivity example, not player authentication.
ws.mount('/ws/game', {}, (info, evt, conn) => {
if (evt.type !== 'text') return
let message
try {
message = JSON.parse(evt.data)
} catch {
conn.sendText(JSON.stringify({ error: 'invalid-json' }))
return
}
if (!message || message.v !== 1 || message.action !== 'echo' ||
typeof message.requestId !== 'string' || message.requestId.length > 64 ||
typeof message.data?.text !== 'string' || message.data.text.length > 200) {
conn.sendText(JSON.stringify({ error: 'invalid-command' }))
return
}
conn.sendText(JSON.stringify({
v: 1,
type: 'reply',
action: 'echo',
requestId: message.requestId,
data: { text: message.data.text }
}))
})
info contains clientid, path, clientip, and protocol. evt contains type='text' with a string or type='binary' with a Buffer. conn is the frame connection, exposing sendText, sendBinary, sendPing, sendPong, close, isClosed, on, and off. The opts object is currently stored with the path but is not applied as per-path parser or security overrides. Keep handlers short and handle asynchronous failures yourself.
Runtime API
| Method | Current contract |
|---|---|
| on(event, fn), off(event, fn) | Subscribe/remove a specific handler. on returns an unsubscribe function |
| mount(path, opts, handler) | Allow an exact URL path and assign its message handler; returns true |
| unmount(path) | Request disconnection of tracked clients and remove the path entry; returns false if absent |
| sendTo(id, data, type) | Target one connection ID; text by default, otherwise binary. Text objects are JSON-stringified |
| broadcast({ path, filter, data, type }) | Send to all tracked clients or one path, optionally filtering { id, path, ip, protocol }; returns a numeric count |
| clients(path?) | Snapshot entries contain id, path, ip, and since |
| stats() | Returns { total, perPath, paths } |
| disconnect(id, code, reason) | Request closure for one ID; defaults to code 1000 and reason bye |
Global events are connection(info), message(info, evt), disconnect(info), and error(info). connection includes request headers; disconnect includes code and reason; error includes error. The wrapper does not publish the old heartbeat event. Low-level ping/pong events belong to conn.
const onMessage = (info, evt) => {
// info.clientid is the connection ID; evt.data is text or a Buffer.
// Add bounded metrics here without logging authentication payloads.
}
const unsubscribe = ws.on('message', onMessage)
// Either form removes this specific subscription:
ws.off('message', onMessage)
unsubscribe()
const connected = ws.clients('/ws/game')
const firstClient = connected[0]
if (firstClient) {
ws.sendTo(firstClient.id, { v: 1, type: 'event', action: 'notice', data: {} })
}
const sent = ws.broadcast({
path: '/ws/game',
filter: client => client.path === '/ws/game',
data: { v: 1, type: 'event', action: 'tick', data: {} },
type: 'text'
})
const snapshot = ws.stats()
// snapshot has total, perPath, and paths; sent is a numeric count.
A false send result can mean socket backpressure rather than an undelivered packet: the engine queues writes while waiting for drain. The API provides no delivery acknowledgments or bounded retry service. Use your own request IDs, acknowledgments, and bounded application queues where needed. Removing a path also requires removing it from pathsAllow if it should not remain eligible for a future upgrade.
From a Byte Stream to Application Messages
webSocketEngine.js runs after the HTTP 101 response. TCP data chunks are accumulated until a frame can be read. The header supplies FIN, reserved bits, opcode, masking, and payload length. Client frames are unmasked, and continuation frames are reassembled before a text/binary message reaches your handler. One TCP chunk is not necessarily one WebSocket frame or one application message.
| Opcode | Transport meaning |
|---|---|
| 0x0 | Continuation of a fragmented message |
| 0x1 | Text message data |
| 0x2 | Binary message data |
| 0x8 | Close control frame |
| 0x9 | Ping control frame |
| 0xA | Pong control frame |
These protocol opcodes are not game action names. The engine responds to ping frames and schedules its own pings. It has a write queue and idle timeout. maxFrameSizeBytes does not currently impose a separate aggregate cap on a fragmented incoming message, so apply and validate your application budgets.
Optional Application Binary Tags
If your game uses compact binary messages, define its own version, message-kind tag, byte order, and length contract. The six-byte example below is an application convention, not a built-in Staxis protocol. Its kind byte is unrelated to the WebSocket frame opcode.
// Application-defined format: byte 0 = version, byte 1 = message kind,
// bytes 2..5 = unsigned sequence number in big-endian order.
ws.mount('/ws/game/binary', {}, (info, evt, conn) => {
if (evt.type !== 'binary' || evt.data.length !== 6) return
const version = evt.data.readUInt8(0)
const kind = evt.data.readUInt8(1)
const sequence = evt.data.readUInt32BE(2)
if (version !== 1 || kind !== 1) return
const reply = Buffer.alloc(6)
reply.writeUInt8(1, 0)
reply.writeUInt8(2, 1)
reply.writeUInt32BE(sequence, 2)
conn.sendBinary(reply)
})
Does Your Game Need a Real-Time Backend?
For lobby state, turn actions, chat, or bounded game events, start with a small explicit message contract. Keep authoritative state and permission checks on the server. The following draft guides describe how different clients can approach this layer; they are not prebuilt engine adapters or replication systems.
Browser connection and message contract
Native builds and Web builds
WebSockets client and callback boundaries
WebSocketPeer polling and packet types
Lifecycle
Attach resolves or creates the server and registers the HTTP upgrade handler. Detach removes that handler, requests disconnection of tracked clients, clears global event subscriptions, and publishes { closed: true }. The current isolated-server path does not close its listening HTTP server during detach. Validate abrupt-disconnect bookkeeping and shutdown in your host lifecycle.
Documentation
This page is the HTML adaptation of the pack's README.md. README.api.md, README.parser.md, and README.shield.md contain older service/namespace APIs, strict-JSON envelopes, and proposed wsShield controls that are not the current runtime contract. Do not assume automatic action dispatch, replay protection, message authentication, or topic isolation from those notes.
Protocol references: RFC 6455 and the Node.js HTTP upgrade event. Complete Staxis onboarding for access to official source guides.