Skip to content
etherspherePublic

About

No description, website, or topics provided.

Resources

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

3 Commits

Folders and files

Repository files navigation

swarm-pubsub

Publish and receive Swarm pubsub messages from the browser or Node.js. There is no local Bee node, no server of your own and no database: the library connects to a broker node over libp2p and speaks the BPS protocol itself. It has no dependencies and adds about 33 kB gzipped to a browser app.

Use it to give any app live, signed messaging in any shape: one-to-many broadcasts, many-to-many rooms, and one-to-one conversations. Chat, game state, live feeds, presence, or commands between devices and agents all fit. It works with channels from bee-js and sample-bps: the chunks are byte-for-byte identical.

Quick start

import { addressFromPrivateKey, connect, generatePrivateKey } from 'swarm-pubsub'

const broker = await connect('/dns4/broker.example.com/tcp/443/tls/ws/p2p/Qm...')

const key = generatePrivateKey()
const channel = await broker.publish('my-room', key)
await channel.send('hello swarm')

Anyone can listen, and needs no key. Listeners connect on their own, so run this in another tab or on another machine, and start it before sending, because messages aren't stored:

const broker = await connect('/dns4/broker.example.com/tcp/443/tls/ws/p2p/Qm...')

const owner = addressFromPrivateKey(key)
await broker.subscribe(owner, 'my-room', {
  onMessage: message => console.log(message.publisher, message.text()),
})

How it works

A channel is identified by its owner address and topic. There are no accounts and nothing to create: a key and a topic name are enough. Everyone on a channel has one of three roles:

Role Needs Receive Publish Manage roster, end channel
Owner The channel's key Yes Yes Yes
Seat Own key, on the roster Yes Yes No
Subscriber Nothing Yes No No

The roster is the owner's list of seats. A publisher's address is proven by its signature: message.publisher can't be forged, by other users or by the broker. That one guarantee is what the patterns below are built on.

What you can build

Most apps are one of these four shapes, or a combination:

Pattern Shape Who publishes Good for
Broadcast One-to-many The owner Live scores, price tickers, notifications, status pages, live blogs, event streams from a backend to browsers
Group room Many-to-many The owner and seats Team chat, shared cursors, presence, collaborative editing, multi-device sync
Authority Many-to-one, then one-to-many Seats send, the owner decides Multiplayer games, auctions, voting, shared whiteboards, anything with one source of truth
Two channels One-to-one Each side owns its own channel Request and response, commands to devices or bots, agent-to-agent messaging, WebRTC signalling

Broadcast

This is the quick start: one owner, any number of subscribers. The owner can be a Node.js process and the subscribers browsers, so a backend can push live updates to pages without running a WebSocket server. Send JSON if you need structure:

await channel.send(JSON.stringify({ match: 'home-away', score: [2, 1] }))

Group room

The owner adds members to the roster, and everyone can talk. publish with an owner waits until the owner grants a seat:

const member = await broker.publish('team-room', memberKey, {
  owner: ownerAddress,
  onMessage: message => render(message.publisher, message.text()),
})
await member.send('hi all')
await room.setRoster([memberAddress, anotherMemberAddress])

setRoster replaces the whole list, so removing someone means sending the list without them. They are disconnected right away. The full version is the chat example.

Two channels

For one-to-one messaging where neither party should need a roster, each owns a channel and subscribes to the other's. A room with one seat works too, but then the owner must grant it. Nobody has to grant anything, which suits request and response between a client and a service:

const responses = await serverBroker.publish(`responses-${clientAddress}`, serverKey)
await serverBroker.subscribe(clientAddress, `requests-${clientAddress}`, {
  onMessage: message => responses.send(`echo: ${message.text()}`),
})
const requests = await clientBroker.publish(`requests-${clientAddress}`, clientKey)
await clientBroker.subscribe(serverAddress, `responses-${clientAddress}`, {
  onMessage: message => console.log(message.text()),
})
await requests.send('ping')

Both sides must be subscribed before the other sends. Add your own request ids if you need to match replies to requests.

Example: an authoritative game server

One party is the game master. It owns the channel and holds the only real copy of the state. Players are seats that send commands. They never change the state themselves: the game master validates each command, applies it, and broadcasts the result. Spectators just subscribe.

This is a small game where players walk around a 10 by 10 board. It runs in the browser or Node.js, and the game master can be either one. The source is examples/game/game.ts, and test/live-game.ts runs it against a real broker.

import type { Broker, Message, Publisher, Subscription } from 'swarm-pubsub'

const BOARD_SIZE = 10
const SNAPSHOT_MILLIS = 5000

export interface GameState {
  tick: number
  players: Record<string, { x: number; y: number }>
}

function parseMove(text: string): { dx: number; dy: number } | null {
  try {
    const { dx, dy } = JSON.parse(text)
    const valid = Number.isInteger(dx) && Number.isInteger(dy) && Math.abs(dx) + Math.abs(dy) === 1
    return valid ? { dx, dy } : null
  } catch {
    return null
  }
}

export async function hostGame(broker: Broker, privateKey: string, room: string, players: string[]) {
  const state: GameState = { tick: 0, players: {} }
  for (const address of players) {
    state.players[address] = { x: 0, y: 0 }
  }

  const broadcast = () => {
    state.tick++
    return host.send(JSON.stringify(state))
  }

  const host: Publisher = await broker.publish(room, privateKey, {
    onMessage: message => {
      const player = state.players[message.publisher]
      const move = parseMove(message.text())
      if (!player || !move) {
        return
      }
      const x = player.x + move.dx
      const y = player.y + move.dy
      if (x < 0 || y < 0 || x >= BOARD_SIZE || y >= BOARD_SIZE) {
        return
      }
      player.x = x
      player.y = y
      void broadcast()
    },
  })

  await host.setRoster(players)
  const snapshots = setInterval(broadcast, SNAPSHOT_MILLIS)
  void host.closed.then(() => clearInterval(snapshots))

  return {
    kick: async (address: string) => {
      delete state.players[address]
      await host.setRoster(Object.keys(state.players))
    },
    end: () => host.end(),
  }
}

function acceptStateFrom(gameMaster: string, onState: (state: GameState) => void) {
  return (message: Message) => {
    if (message.publisher === gameMaster) {
      onState(JSON.parse(message.text()))
    }
  }
}

export async function joinGame(
  broker: Broker,
  privateKey: string,
  room: string,
  gameMaster: string,
  onState: (state: GameState) => void,
): Promise<{ player: Publisher; move: (dx: number, dy: number) => Promise<bigint> }> {
  const player = await broker.publish(room, privateKey, {
    owner: gameMaster,
    onMessage: acceptStateFrom(gameMaster, onState),
  })
  return { player, move: (dx, dy) => player.send(JSON.stringify({ dx, dy })) }
}

export function watchGame(
  broker: Broker,
  room: string,
  gameMaster: string,
  onState: (state: GameState) => void,
): Promise<Subscription> {
  return broker.subscribe(gameMaster, room, { onMessage: acceptStateFrom(gameMaster, onState) })
}

Host a game with the addresses of the invited players:

const broker = await connect(BROKER)
const game = await hostGame(broker, gameMasterKey, 'room-1', [aliceAddress, bobAddress])

Each player joins and sends moves:

const broker = await connect(BROKER)
const { move } = await joinGame(broker, aliceKey, 'room-1', gameMasterAddress, draw)
await move(1, 0)

Why this design holds up:

  • State can't be forged. Players' messages reach everyone, including other players, so clients accept state only when message.publisher is the game master. A player who sends a fake state is ignored.
  • Cheating is rejected in one place. The game master knows who sent each command and checks it, so an illegal or malformed move changes nothing.
  • Everyone sees one order. Messages from different publishers can arrive in different orders, but all state comes from the game master, so every client sees the same sequence. tick lets clients spot a gap.
  • Late joiners catch up. Nothing is stored, so the game master rebroadcasts the whole state every 5 seconds. Lost messages repair themselves the same way.
  • The state stays small. One message holds 4096 bytes. For larger state, send only the parts that changed and split snapshots across messages.

Things to design for:

  • Players must be invited. The broker doesn't tell the owner who is listening, and an unlisted player can't publish, so the game master has to learn each address some other way: an invite link, a sign-up form or a small web endpoint. Addresses must be in the form addressFromPrivateKey returns: lowercase hex with no 0x.
  • Commands and state are public. Anyone who knows the game master's address and the room can read them. For hidden information, such as cards in hand, encrypt each player's data for that player.
  • Keep the game master's key stable. Its address identifies the game. If it disconnects, seats stay connected and can still publish, but their commands aren't being applied. When it returns with the same key it gets the roster back and can carry on, if it kept its state. If everyone leaves, the broker forgets the channel, so call setRoster again.

When not to use it

  • Anything that must not be lost. Nothing is stored, and nothing is redelivered. Keep history in a database or a Swarm feed, and use this for the live layer.
  • Fast-reflex games. Expect around half a second per hop, which suits turn-based and casual real-time play, not shooters or racing games.
  • Open write access. Unknown users can't publish without being added to the roster. Listening is open to everyone.
  • Secrets, unless you encrypt. Every message is readable by anyone who knows the channel.
  • Large payloads. One message holds 4096 bytes. Send a Swarm reference for anything bigger.

Limits

These are the defaults of a Bee broker, so a broker operator can set some of them differently.

Limit Value What happens beyond it
Message size 4096 bytes send throws a RangeError
Seats on a roster 186 setRoster throws a RangeError
Channels per connection 16 Rejected: "the broker is at capacity". Open another connection with connect
Streams per channel, per connection 2 Rejected the same way
Publisher streams per address 2 The oldest is disconnected
Subscribers per channel 1024 Rejected the same way
Channels per broker 512 Rejected the same way
Light clients per broker 100 Bee disconnects a random light client. Every open connection counts, so raise light-node-limit for busy brokers
Queued messages per receiver 64 A receiver that falls this far behind is disconnected
Idle channel 10 minutes The broker closes it. Connected publishers send a heartbeat

Timings from one test client to one broker over wss://. Yours depend on your distance from the broker:

Operation Measured
connect Under 1 second
Joining a channel Under 1 second
One message, publisher to subscriber 0.3 to 0.5 seconds
Request and response on two channels About 0.9 seconds
Burst of 1000 messages of 100 bytes All delivered in about 2 seconds
Burst of 200 messages of 4096 bytes All delivered in under 1 second

API

connect(address, options?)

Opens a connection to a broker and returns a Broker. address is a multiaddr; include /p2p/<peer id> so the library verifies it reached the right node. Browsers need wss (/tls/ws, /tls/sni/<host>/ws or /wss), except on localhost. Node.js 22 or newer can also use ws, or plain TCP such as /ip4/203.0.113.7/tcp/1634/p2p/Qm.... connect gives up after 10 seconds without an answer.

Option Default Meaning
networkId 1n (mainnet) Swarm network id

broker.publish(topic, privateKey, options?)

Resolves with a Publisher once it may publish. Topics are hashed the same way as bee-js Topic.fromString, or pass 32 raw bytes.

Without owner you own the channel. With owner, you take a seat: the promise stays pending until the owner adds your address to the roster, so use signal to give up.

Option Default Meaning
owner your address Channel to join as a seat
index Date.now() First message index. It must exceed every index used before
rosterIndex Date.now() First roster index, with the same rule
heartbeatMillis 60000 Keepalive. The broker drops channels idle for 10 minutes
signal AbortSignal that stops waiting for a seat
onMessage, onRoster, onClose See below
Publisher
send(data) Sends a string or bytes, up to 4096 bytes. Resolves with the index
setRoster(addresses) Owner only. Replaces all seats, up to 186
end() Owner only. Ends the channel for everyone
close() Leaves without ending the channel
closed Promise of the CloseEvent
position, address Current position and your address

You don't receive your own messages back.

broker.subscribe(owner, topic, options?)

Resolves with a Subscription that has close(), closed and position. Options are onMessage, onRoster, onClose and position.

  • onMessage({ publisher, index, payload, text() })
  • onRoster(addresses): the owner is not listed
  • onClose({ ended, error }): ended means the owner ended the channel; error is set when something went wrong

The same handlers work on publish. If onMessage or onRoster throws, the error goes to console.error and the channel stays open, so bad input from another user can't close it.

Reconnecting. A connection can drop at any time. Pass the old position to continue without duplicates:

async function listen(position) {
  const subscription = await broker.subscribe(owner, topic, {
    ...(position ? { position } : {}),
    onMessage,
    onClose: event => {
      if (!event.ended) setTimeout(() => listen(subscription.position), 3000)
    },
  })
}

If the broker connection itself dropped, call connect again first. See examples/chat/main.ts.

broker.close()

Closes every channel and the connection.

Keys

generatePrivateKey() returns a new hex key. addressFromPrivateKey(key) returns its address. Keys need no funds and are not a Bee wallet.

Good to know

  • Messages are live only. A new subscriber sees messages sent after it joined, plus the current roster.
  • Delivery isn't guaranteed. A receiver that falls behind is disconnected, and messages sent while it reconnects are lost.
  • Ordering holds per publisher, not across publishers.
  • Every delivery is verified. Signatures are checked against the owner and roster, so a broker can drop messages but can't forge them. A forged delivery closes the channel with an error. A message from an address that the latest roster doesn't list is dropped, since the broker may not have applied that roster yet.
  • Connections can drop. Handle onClose and reconnect, as shown above.
  • In browsers, Web Crypto is required, so pages must be served from https:// or localhost.

Chat example

The chat recreates sample-bps in the browser: rooms, seats, /roster, /end and /quit.

npm install
npm run chat

Open the printed URL. The default broker is /dns4/broker.hiveway.xyz/tcp/443/tls/ws/p2p/QmUgerWFMatCRrThTqm2EwRRKhb3kprgfMWDXrLx9EefZ5.

To try a broker with no wss:// endpoint from localhost, run the development bridge and use /ip4/127.0.0.1/tcp/1636/ws/p2p/<peer id>. Set BROKER_HOST and BROKER_PORT to choose the broker:

npm run bridge

Broker requirements

The broker is a Bee node, version 2.8.4 or newer, started with bps-broker: true. Browsers also need a wss:// endpoint with a certificate they trust. There are two ways to get one:

  • AutoTLS. Set p2p-wss-enable: true in Bee's config and open the WSS port (p2p-wss-addr, :1635 by default; set nat-wss-addr behind NAT). Bee gets a libp2p.direct certificate by itself and announces a /tls/sni/<host>/ws address, which connect accepts as it is.
  • A WebSocket to TCP bridge behind your own domain. libp2p over WebSocket carries the same bytes as over TCP, so a bridge such as websockify 127.0.0.1:1636 127.0.0.1:1634, behind nginx or Caddy terminating TLS on port 443, works with no change to Bee. The address is then /dns4/<your domain>/tcp/443/tls/ws/p2p/<peer id>. Bee sees every browser as coming from 127.0.0.1, which is fine below its limit of 200 connections per IP.

Development

npm install
npm run typecheck
npm test
npm run test:live  # protocol and game example against a real broker
npm run build
npm run test:e2e   # after build: a browser and a Node.js client message each other through the broker

npm publish runs typecheck, tests, build and test:e2e, in that order, and stops at the first failure. test:e2e installs Playwright's headless Chromium if it is missing.

The package ships two bundles, dist/index.js for browsers and dist/node.js for Node.js, picked automatically through exports. Both are self-contained, so users of the package need nothing extra. The libp2p part (multistream-select, Noise, yamux and identify) is our own code, and the cryptography comes from the bundled noble libraries.

License

BSD-3-Clause

About

No description, website, or topics provided.

Resources

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages