@doars/roupn
v0.2.1
Published
Synchronise application state between users in real-time via end-to-end encrypted messages.
Downloads
43
Readme
roupn
Synchronise application state between users in real-time via end-to-end encrypted messages.
- Minimal footprint with no unnecessary dependencies.
- Communication is encrypted from one client to another, ensuring privacy.
- The server only relays messages and cannot decrypt the content sent.
- A built-in verification flow helps prevent man-in-the-middle attacks.
- Automatically synchronizes a shared state object between clients using an efficient diffing mechanism.
- Provides straightforward functions for setting up both the server and client.
roupn operates with a central server that acts as a message relay. Clients connect to this server to create or join rooms. The room's creator is responsible for verifying new users to ensure they are who they claim to be, establishing a secure room for the group. All data exchanged between clients is end-to-end encrypted and is verified during the joining process.
Because messages are end-to-end encrypted, the server cannot inspect their content. It can still observe metadata such as addresses, timing, room membership, and message sizes, and it controls availability. This metadata is private too, so a trusted server should still be used when available.
From the user's perspective
A user can be given the option to create or join a room. When creating a room, this user receives a room code from the server, for example AB3D5F, and provides it to the people they want to join. Each joining user then sees a different verification code, for example U2W4YZ. This code must be given back to the room's creator over a secure and trusted channel. The creator enters it to verify that the public keys received by both users have not been altered.
Usage
Setting up the server
The server is responsible for creating rooms and relaying messages between users. You can set up a server using createServerConnector. It handles HTTP requests for creating rooms and WebSocket connections for real-time communication.
createServerConnector(options)
contentType(string): Content type for messages. Default:'application/json'.deserializeMessage(Function): Function to deserialize messages. Default:JSON.parse.serializeMessage(Function): Function to serialize messages. Default:JSON.stringify.createRoomEndpoint(string): Endpoint for creating a room. Default:'/create-room'.joinRoomEndpoint(string): Endpoint for joining a room. Default:'/join-room'.maxUsersPerRoom(number): Absolute maximum users allowed per room. Default:16.maxRooms(number): Maximum number of active rooms. Default:1000.creatorJoinTimeout(number): Milliseconds before an unclaimed room is removed. Default:30000. Set to0to disable.roomIdleTimeout(number): Milliseconds before an inactive room is removed. Default:1800000. Set to0to disable.roomCreationsPerAddress(number): Per-address room creation attempts per minute. Default:10.roomCreationsGlobal(number): Global room creation attempts per minute. Default:100.getRemoteAddress(request)(Function): Returns the address used for rate limiting. The default reads onlyrequest.socket.remoteAddress; forwarding headers are never trusted automatically.authorizeRoomCreation({ request, remoteAddress })(Function): Synchronously authorizes an attempt. Returnfalseto respond with403; thrown errors produce500.maxEncodedMessageBytes(number): Maximum encoded WebSocket message size. Default:262144.maxProtocolSegments(number): Maximum protocol segments per message. Default:16.maxProtocolKeyBytes(number): Maximum UTF-8 segment-key size. Default:64.maxDecodedFieldBytes(number): Maximum decoded bytes per field. Default:196608.maxTotalDecodedBytes(number): Maximum decoded bytes across fields. Default:262144.maxSocketBufferedAmount(number): Buffered bytes before a slow consumer is closed. Default:1048576.connectionMessages(number): Messages allowed per connection rate window. Default:60.directMessages,broadcastMessages, andserverMessages(number): Independent per-category messages allowed per connection rate window. Each defaults to60.connectionMessageBytes(number): Encoded bytes allowed per connection rate window. Default:1048576.connectionRateWindow(number): Connection rate window in milliseconds. Default:10000.handshakeMessages(number): Pending-handshake messages allowed per minute. Default:10.maxPendingUsersPerRoom(number): Maximum reserved and unverified users. Default:8.handshakeTimeout(number): Milliseconds before an unverified peer is removed. Default:30000. Set to0to disable.validateOrigin({ origin, request })(Function): Upgrade origin policy. It defaults to exact same-origin validation and rejects missing origins.allowedWebSocketProtocols(string[]): Optional WebSocket subprotocol allowlist.
Production deployments should terminate TLS at the application or reverse
proxy and configure an additional reverse-proxy rate limit for the room creation
endpoint. Only configure getRemoteAddress to use forwarding headers when the
request came through a trusted proxy that replaces those headers.
Construct the WebSocket server with a transport-level maxPayload no larger
than the connector's logical encoded-message limit:
const connector = createServerConnector()
const socketServer = new WebSocketServer({
maxPayload: 256 * 1024,
noServer: true,
})Connect the returned handlers to the HTTP and WebSocket servers:
httpServer.on('request', (request, response) => {
if (!connector.handleHttpRequest(request, response)) {
response.writeHead(404)
response.end()
}
})
httpServer.on('upgrade', (request, socket, head) => {
if (!connector.handleSocketUpgrade(request, socket, head, socketServer)) {
socket.destroy()
}
})Production clients must use https: and wss: URLs. Plain http: and ws:
are accepted only for localhost, 127.0.0.0/8, and ::1, unless the explicit
allowInsecureNonLoopback development option is enabled. Terminate TLS at the
application or a trusted reverse proxy. Creator credentials are sent as a
single-use first protocol message and never appear in the WebSocket URL. If an
older deployment logged creator query parameters, redact those historical
access logs.
For a complete example see the server.js in the example directory.
Setting up the client
On the client side, use createClientConnector to handle connections and encryption, or createClientSynchronizer to add shared-state management.
The synchronizer works with two state objects. Its private state holds connection status, user IDs, and other internal data and should be treated as read-only. Its public state is synchronized across the room; changes made to it are automatically broadcast to verified users.
createClientConnector(options)
createRoomEndpoint(string): HTTP endpoint for creating a room. Default:'/create-room'.joinRoomEndpoint(string): WebSocket endpoint for joining a room. Default:'/join-room'.contentType(string): Content-Type for HTTP requests. Default:'application/json'.deserializeMessage(Function): Function to deserialize incoming messages. Default:JSON.parse.serializeMessage(Function): Function to serialize outgoing messages. Default:JSON.stringify.httpUrl(string): Base HTTP URL for API requests. Default:'http://localhost:3000'.wsUrl(string): Base WebSocket URL for room connections. Default:'http://localhost:3000'.messageBufferMaxCount(number): The maximum number of messages to store in the buffer. Default:50.messageBufferMaxDuration(number): The maximum duration in milliseconds to store a message in the buffer. Default:60000.allowInsecureNonLoopback(boolean): Development-only override for non-loopbackhttp:orws:URLs. Default:false.
When creating or joining a room, you can provide the following options:
publicData(any): Data shared before the encrypted connection is fully established. It can be used to verify application compatibility, but it is visible to the relay and must not contain secrets.verifyPublicData(Function): A function that verifies the public data from other users.
Subscribe to onError before creating or joining a room. The connector also provides room, user-verification, direct-message, room-message, and server-message methods, alongside connection, room, user, message, and error events. Event objects expose addListener, removeListener, and dispatch.
createClientSynchronizer(options)
- All createClientConnector options.
windowPerUser(number): Number of state updates to keep per joined user. Used in case of rollbacks. Default:16.synchronisationInterval(number): Interval in milliseconds for a full state synchronisation. Default:60000.maxDiffChanges(number): Maximum changes accepted in one state update. Default:1000.maxDiffPathDepth(number): Maximum accepted state-delta path depth. Default:32.maxDiffValueBytes(number): Maximum serialized value size per state change. Default:196608.maxSerializedStateBytes(number): Maximum serialized full-state synchronization size. Default:1048576.
For a complete example see the client.js in the example directory.
Installation
Via NPM
npm install @doars/roupnServer
import { createServerConnector } from '@doars/roupn'Client
IIFE build via a CDN
<!-- Base bundle (connector only) -->
<script src="https://cdn.jsdelivr.net/npm/@doars/roupn@1/dst/roupn.base.iife.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@doars/roupn@1/dst/roupn.base.iife.min.js"></script>
<!-- Full bundle (connector and synchronizer) -->
<script src="https://cdn.jsdelivr.net/npm/@doars/roupn@1/dst/roupn.iife.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@doars/roupn@1/dst/roupn.iife.min.js"></script>ESM build via a CDN
// Base bundle (connector only).
import { createClientConnector } from 'https://cdn.jsdelivr.net/npm/@doars/roupn@1/dst/roupn.base.js'
// Full bundle (connector and synchronizer).
import { createClientConnector, createClientSynchronizer } from 'https://cdn.jsdelivr.net/npm/@doars/roupn@1/dst/roupn.js'The browser bundles contain client APIs only. Server applications should import createServerConnector from the package entry. The client requires WebSocket, Web Crypto, Fetch, URL, Worker, and Blob APIs.
For compact language-model documentation, see llms.txt.
