npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@go-ricochet/ricochet

v0.1.0

Published

TypeScript client for the go-ricochet store-and-forward server, for browsers (WSS) and Node.js/Electron (UDX).

Readme

@go-ricochet/ricochet

A TypeScript client for go-ricochet, the store-and-forward server: mailboxes and messages, documents, collections, feeds and push notifications.

It runs in browsers over WebSockets (WSS) and in Node.js or Electron over UDX. It is a port of go-ricochet's Go client (pkg/client). The wire format, payload encryption and compression are byte-compatible with it.

Every code block below is copied from examples/, and the tests run those files.

Install

npm install @go-ricochet/ricochet

Version 0.1.0 is not on npm yet. Node.js 22.18 or later. ESM only.

The package has three entry points:

| Import | For | Adds | |---|---|---| | @go-ricochet/ricochet/browser | Browsers | createRicochetNode() with WebSockets | | @go-ricochet/ricochet/node | Node.js, Electron main | createRicochetNode() with UDX and WebSockets, resolveDnsAddrs() | | @go-ricochet/ricochet/core | Any, with your own libp2p node | Nothing platform-specific |

@go-ricochet/ricochet picks browser or node by the bundler's or runtime's export conditions, else core. The browser entry has no Node.js code.

Every entry registers the UDX multiaddr codec. go-ricochet servers advertise /udx addresses. Without the codec, js-libp2p's identify fails with "Protocol 768 was unknown".

In a browser

import { RicochetClient, createRicochetNode } from '@go-ricochet/ricochet/browser'
// serverAddr is the server's WSS address, for example
// '/dns4/ricochet.spiffyvault.net/tcp/55223/wss/p2p/12D3KooW...'.
const { node, privateKey } = await createRicochetNode()
const client = new RicochetClient(node, {
  servers: [{ peerId: serverPeerId, addrs: [serverAddr] }],
  privateKey
})

const { status } = await client.getDocument(client.peerId, 'notes/today')
// status is 404 until something is put there

await client.close()
await node.stop()

A page served over https:// must use a /wss (or /tls/ws) address. Browsers block ws:// from secure pages.

Bring your own node

Apps that already run js-libp2p pass their node to the client. The node needs Noise and Yamux. Import the UDX codec before anything parses a multiaddr:

// First, before anything parses a multiaddr: go-ricochet advertises /udx
// addresses, and without this codec identify fails with "Protocol 768 was
// unknown". This is the browser entry of the package; never import the
// package root in browser code.
import '@go-ricochet/libp2p-udx/multiaddr'

import { noise } from '@chainsafe/libp2p-noise'
import { yamux } from '@chainsafe/libp2p-yamux'
import { generateKeyPair } from '@libp2p/crypto/keys'
import { identify } from '@libp2p/identify'
import { ping } from '@libp2p/ping'
import { webSockets } from '@libp2p/websockets'
import { createLibp2p } from 'libp2p'
import { RicochetClient } from '@go-ricochet/ricochet'
const privateKey = await generateKeyPair('Ed25519')
const node = await createLibp2p({
  privateKey,
  transports: [webSockets()],
  connectionEncrypters: [noise()],
  streamMuxers: [yamux()],
  services: { identify: identify(), ping: ping() },
  // Only to reach a server on loopback while testing: browsers refuse
  // private addresses by default.
  connectionGater: { denyDialMultiaddr: async () => false }
})

const client = new RicochetClient(node, {
  servers: [{ peerId: serverPeerId, addrs: [serverAddr] }],
  privateKey // only needed for encryption
})
await client.putDocument(client.peerId, 'notes/today', 'hello')
const doc = await client.getDocument(client.peerId, 'notes/today')
// doc.status is 200, doc.content holds the bytes of "hello"

await client.close() // the node is yours: the client leaves it running
await node.stop()

The app and this package must share one copy of @multiformats/multiaddr (13.x), or the codec lands in the other copy. npm ls @multiformats/multiaddr shows the copies.

In Node.js and Electron

import { RicochetClient, createRicochetNode, resolveDnsAddrs } from '@go-ricochet/ricochet/node'
// serverAddr is the server's UDX address, for example
// '/dns4/ricochet.spiffyvault.net/udp/55223/udx/p2p/12D3KooW...'.
// The UDX transport dials IP addresses only, so resolve the name first.
const { node, privateKey } = await createRicochetNode()
const client = new RicochetClient(node, {
  servers: [{ peerId: serverPeerId, addrs: await resolveDnsAddrs([serverAddr]) }],
  privateKey
})

const { status } = await client.getDocument(client.peerId, 'notes/today')
// status is 404 until something is put there

await client.close()
await node.stop()

Use the node entry in Electron's main process. In a renderer, use the browser entry.

createRicochetNode({ udxOnly: true }) leaves out WebSockets. createRicochetNode({ listen: ['/ip4/0.0.0.0/udp/0/udx'] }) also listens. A client does not need to listen: the server pushes notifications over the connection the client opened.

Known issue: js-udx's timers are unref'd. In a script that does nothing else, the process can exit while node.stop() closes a UDX connection (Node reports an unsettled top-level await). Keep the event loop busy until stop() returns, for example with a setInterval.

The client

new RicochetClient(node, options):

| Option | Default | | |---|---|---| | servers | [] | { peerId, addrs?, priority?, weight? }. Lower priority first; higher weight first among equals. | | privateKey | none | The node's Ed25519 key (a libp2p PrivateKey, or 32 or 64 raw bytes). Needed to encrypt and decrypt. | | connectionTimeout | 10 000 ms | To open a stream, dial included. | | messageTimeout | 30 000 ms | For one request and its response. |

Servers are tried in order. A server that cannot be reached is passed over for the next. A server that answers is not second-guessed: its refusal is the result. Every call also takes { server, signal }. server sends to that server only, with one attempt.

Payloads are Uint8Array or string (sent as UTF-8). Peer IDs are strings (12D3KooW...) or libp2p PeerId objects. Times are Unix milliseconds, except a notification's timestamp (seconds, as the server sends it).

client.close() removes the notification handler and refuses later calls. It does not stop the node.

API by area

Mailboxes

// Mailboxes are folders in the caller's own mail store.
await client.createMailbox('orders', 'private', { maxMessages: 500, retentionDays: 7 })
await client.createMailbox('team', 'shared')
await client.grantAccess('team', friendId, 'readWrite')
const acl = await client.listACL('team') // [{ peerId: friendId, accessMode: 'readWrite', ... }]
const mailboxes = await client.listMailboxes()
const info = await client.getMailboxInfo('orders') // messageCount, maxMessages, ...
const capacity = await client.queryCapacity()

Also updateMailboxConfig, revokeAccess and deleteMailbox. Mailbox types are private, shared and public. Access modes are readOnly, writeOnly and readWrite. The server caps maxMessages and retentionDays at its own defaults.

Messages

// Send: a refused message is a result with success false, not an exception.
const sent = await friend.sendMessage(client.peerId, 'hello', {
  folderPath: 'orders',
  priority: Priority.High,
  compress: true, // LZ4 for payloads of 1 KB and more
  encrypt: true // sealed for the recipient; needs the sender's privateKey
})
if (!sent.success) throw sent.error!

// Many at once (up to 100), one result per message, in order.
await friend.sendMessages([
  { recipient: client.peerId, payload: 'one', options: { folderPath: 'orders' } },
  { recipient: client.peerId, payload: 'two', options: { folderPath: 'orders' } }
])

// Retrieve: payloads come back decrypted and decompressed.
// Retrieval removes nothing; acknowledge what you have handled.
let page = await client.retrievePage({ folderPath: 'orders', maxMessages: 50 })
const received = page.messages.map(m => new TextDecoder().decode(m.payload))
while (page.hasMore) {
  const last = page.messages[page.messages.length - 1]!
  page = await client.retrievePage({ folderPath: 'orders', maxMessages: 50, fromSequence: last.sequenceNumber + 1 })
  received.push(...page.messages.map(m => new TextDecoder().decode(m.payload)))
}
const ids = (await client.retrieveMessages({ folderPath: 'orders' })).map(m => m.messageId)

// IMAP-style flags, expunge, and immediate delete.
await client.updateFlags(ids[0]!, MailFlag.Flagged)
await client.updateFlags(ids[1]!, MailFlag.Deleted)
await client.expunge({ folderPath: 'orders' }) // removes the Deleted one
await client.deleteMessages([ids[2]!])

Also markDelivered(ids): it removes non-persistent messages and marks persistent ones seen. sendMessage takes expiry (ms, default 7 days) and persistent. retrievePage takes minPriority and targetPeerId (to read another peer's shared mailbox with a grant). forwardMessage submits a message on its sender's behalf (servers allow this only for trusted peers).

A claim mailbox (go-ricochet 1.6.0) hands its messages out one at a time, such as one-time keys: only its owner stores into it or lists it, and claimMessage(ownerPeerId, folderPath) takes the oldest message and deletes it on the server, so no two claimers get the same one. It returns null when none is left, which is also the answer once the mailbox has handed out its share for the hour (30 claims by default). It throws ForbiddenError (403) for a mailbox that is not a claim mailbox, NotFoundError (404) for none, and a 400 from an older server.

A retrieved message has bound: true when its encrypted payload carried a binding, and false for the legacy format. Treat false as a downgrade if you rely on the binding.

Documents

const me = client.peerId
const put = await client.putDocument(me, 'config/settings', '{"theme":"dark"}', {
  contentType: 'application/json'
}) // put.created is true, put.etag is the content hash

// Conditional write: fails with ConflictError if someone wrote in between.
// history: 5 turns version history on, keeping the version it replaces.
await client.putDocument(me, 'config/settings', '{"theme":"light"}', { ifMatch: put.etag, history: 5 })

// Merge patch (RFC 7386) on a JSON document.
await client.patchDocument(me, 'config/settings', { fontSize: 14 })

// Reads report the status instead of throwing: 200, 304, 403 or 404.
const doc = await client.getDocument(me, 'config/settings')
const again = await client.getDocument(me, 'config/settings', { ifNoneMatch: doc.etag }) // 304
const meta = await client.headDocument(me, 'config/settings')
const all = await client.listDocuments(me)
const history = await client.getDocumentHistory(me, 'config/settings') // newest first, no bodies
const first = await client.getDocumentVersion(me, 'config/settings', 1) // with its content

// Up to 100 documents in one request; each has its own status.
const batch = await client.putDocuments(me, [
  { path: 'notes/a', content: 'A' },
  { path: 'notes/b', content: 'B', contentType: 'text/plain' }
])

// Documents are private to the owner until told otherwise.
await client.putDocument(me, 'profile', '{"name":"Ann"}', { visibility: 'public' })
await client.setDocumentVisibility('notes/a', 'shared')
await client.grantDocumentReader('notes/a', friendId)
const access = await client.documentAccess('notes/a') // { visibility: 'shared', readers: [...] }

const deleted = await client.deleteDocument(me, 'notes/b') // false if it was not there

Also restoreDocumentVersion(path, n), which makes a kept version current again as a new version (so it can be undone too), revokeDocumentReader, and batchDocuments(docs) to split a large set into chunks for putDocuments. Paths match [a-zA-Z0-9_/-]+, 256 characters at most. Only the owner writes.

Version history is off until the owner turns it on with history: n on a putDocument. From that write on the document keeps up to n earlier versions, starting with the one the write replaced; the server clamps n to its max_document_history_versions (10 by default). history: 0 turns it off and deletes the kept versions. getDocument and headDocument report the setting as history (0 when off).

The directory is part of the document protocol: joinDirectory({ displayName, bio?, avatarHash?, extras? }), leaveDirectory(), browseDirectory({ query?, cursor?, limit? }) and getDirectoryEntry(peer).

Collections

// Keyed JSON records with server-side queries.
await client.createCollection('tasks', 'Tasks')
await client.putCollectionItem('tasks', 't1', { title: 'write', priority: 3 })
await client.putCollectionItem('tasks', 't2', { title: 'ship', priority: 5 })
const item = await client.getCollectionItem(me, 'tasks', 't1') // item.content is the parsed JSON

// Filters: equality, $lt $lte $gt $gte $ilike $contains, $and and $or.
const urgent = await client.queryCollection(me, 'tasks', { priority: { $gt: 4 } }, {
  sort: { field: 'priority', asc: false },
  limit: 20,
  wantTotal: true
})
const page50 = await client.listCollectionKeys(me, 'tasks', { limit: 50 }) // follow page50.nextCursor
await client.deleteCollectionItem('tasks', 't1')

Items are JSON. A Uint8Array value is sent as it is and must hold JSON text; any other value is JSON-encoded. item.raw is the JSON exactly as the server sent it. Also getCollection, listCollections, deleteCollection, putCollectionItem(..., { ifMatch }), and the access calls collectionAccess, setCollectionVisibility, grantCollectionReader and revokeCollectionReader.

Feeds

// Append-only logs. A collaborative feed takes entries from other peers too.
await client.createFeed('blog', 'Blog', 'My posts', { visibility: 'public' })
const seq = await client.appendFeedEntry('blog', 'first post', 'post') // 1
const entry = await friend.getFeedEntry(me, 'blog', seq)
const { entries, hasMore } = await friend.getFeedEntries(me, 'blog', { from: 1, limit: 50 })
const several = await friend.getMultiFeedEntries([{ ownerPeerId: me, path: 'blog' }]) // keyed "<owner>/<path>"

await client.createFeed('guestbook', 'Guestbook', '', { collaborative: true, visibility: 'public' })
await friend.appendToFeed(me, 'guestbook', 'hi!', 'note')

Also getFeed, listFeeds, deleteFeed, and feedAccess, setFeedVisibility, grantFeedReader and revokeFeedReader.

Notifications

// The server pushes a notification when mail reaches one of the client's
// private mailboxes while it is connected (it must have made a request).
const stop = await client.onNotification(n => {
  // n.mailboxPath is the folder ("inbox"), n.ownerPeerId whose mailbox it is,
  // n.mailboxType "private"
  result.notified = n
})
await friend.sendMessage(client.peerId, 'ping')
// ... later, to stop listening:
// await stop()

The server dials the client on /ricochet/mailbox-notify/1.0.0 over the connection the client opened. Shared and public mailboxes notify over GossipSub instead; this package does not subscribe to GossipSub.

Encryption

// sendMessage({ encrypt: true }) and retrieve do this for you. The
// functions are there for payloads you carry some other way.
const binding = { recipientPeerId: client.peerId, folderPath: 'inbox', messageId: 'msg-1' }
const sealed = encryptBoundPayload(new TextEncoder().encode('secret'), binding, client.peerId, keys.friends)
const opened = decryptBoundPayload(sealed, binding, friendId, keys.mine)
// opened.payload is the plaintext; opened.bound is false for the legacy
// format, and a ciphertext moved to another message throws
// BoundToAnotherMessageError.

The format is go-ricochet's: NaCl box (X25519 and XSalsa20-Poly1305) between the two Ed25519 identities converted to X25519.

  • Bound (what the client sends): "RCE2", a 24-byte nonce, then the box of the binding header and the payload. The header is the recipient peer ID, the folder path (inbox for an empty one) and the message ID, each as a 2-byte big-endian length and its UTF-8 bytes.
  • Legacy (still accepted): a 24-byte nonce, then the box of the payload.

The binding stops the server, or anyone who can write to a mailbox, from moving a ciphertext to another folder, message ID or recipient. It does not stop a replay of the same message into the same folder.

Also encryptPayload and decryptPayload (legacy), bindingFor(message), and the key conversions ed25519PrivateKeyToX25519, ed25519PublicKeyToX25519 and peerIdToX25519PublicKey.

Compression is LZ4 block format after a 4-byte big-endian original size, with the Compressed flag. The client compresses first, then encrypts. compressPayload and decompressPayload are exported. The compressor is a port of the one the Go client uses, so the bytes are the same.

Errors and status codes

Every failure the server reports is a ProtocolError with status, op, serverMessage and retryAfterMs, or one of its subclasses:

try {
  await friend.putDocument(me, 'config/settings', 'not yours')
} catch (err) {
  if (err instanceof ForbiddenError) {
    // 403: only the owner writes
  } else if (err instanceof NotFoundError || err instanceof ConflictError || err instanceof MailboxFullError) {
    // 404, 409, 507
  } else if (isRetryable(err)) {
    // 429 or 503: wait (err.retryAfterMs) and try again
  } else if (err instanceof ProtocolError) {
    // any other status: err.status, err.serverMessage
  } else {
    throw err // transport failure, timeout, ...
  }
  result.forbidden = err instanceof ForbiddenError
}

| Status | Meaning | In this client | |---|---|---| | 200, 201, 204 | Done; 201 created, 204 deleted | A result | | 207 | A batch with some refusals | Per-item results | | 304 | Not modified (ifNoneMatch) | getDocument status | | 400 | Bad request | ProtocolError | | 403 | Not allowed | ForbiddenError | | 404 | Not found | NotFoundError; getDocument reports it, get* calls return undefined, deletes return false | | 409 | Conditional write lost | ConflictError, with actualETag when the server says | | 413 | Batch too large | ProtocolError | | 429 | Rate limited | RateLimitedError, with retryAfterMs | | 500 | Server fault, or a refusal without a status | ProtocolError | | 503 | Overloaded or draining | OverloadedError, with retryAfterMs | | 507 | Mailbox, quota or storage full | MailboxFullError; do not retry on a timer |

isRetryable(err) is true for 429 and 503. statusOf(err) and retryAfterOf(err) read any error. A refused message from sendMessage or sendMessages comes back as a result with success: false, status and error.

Other errors: NoServerError (none configured or none reachable; attempts holds each failure), ClientClosedError, FrameTooLargeError, DecodeError (a reply the client could not read, or none), PayloadError and BoundToAnotherMessageError (decryption or decompression). All extend RicochetError.

Limits

| Limit | Value | |---|---| | Frame, either way | 10 MB (requests over it fail before dialling) | | Message payload | 10 MB | | Messages per sendMessages | 100 | | Documents per putDocuments | 100, and 6 MB of content | | Queries per getMultiFeedEntries | 50 | | Path length | 256 | | Decompressed payload | 16 MB | | Compression threshold | 1 KB by default (compress: <bytes> to change) | | Feed title, description, entry type | 256, 4096, 64 | | Collection name, key | 256, 256 |

Limits exports these values.

Wire notes

  • One stream per request. A request is one frame: a 4-byte big-endian length, then UTF-8 JSON. The client half-closes after writing and reads one frame back. A retrieve reply is a compound frame inside that frame: a length-prefixed JSON header {messageCount, hasMore}, then each message length-prefixed.
  • Identity is the libp2p peer ID of the Noise session; nothing else is signed. The server checks ownerPeerId against it for writes and mailbox administration, and treats a message whose senderPeerId is someone else as a forwarded one.
  • Messages encode byte for byte as Go's Message.ToJSON. Requests escape <, > and & as Go's encoder does.
  • History: a version listing's createdAt is Unix milliseconds; servers before history could be turned on sent RFC 3339, which the client also reads. A version that is not stored is a 404 (NotFoundError).

Tests

npm run test:unit          # framing, codecs, errors, Go vectors
npm run test:integration   # local go-ricochet over UDX, WS and TLS WS
npm run test:browser       # headless Chromium (Playwright) over WS and TLS WS
npm run check:bundle       # browser bundle has no Node built-ins
npm run test:live          # production, read-only, opt-in

The integration and browser tests build go-ricochet from ../go-ricochet (or RICOCHET_SRC) and run it with a throwaway PostgreSQL database, ricochet_jsdk_test (or RICOCHET_TEST_DB), which they create and drop. They need Go, PostgreSQL and psql, and openssl for the TLS tests. The Chromium tests use Playwright's Chromium if it is installed, else the system Google Chrome.

The Go vectors in test/fixtures/go-vectors.json come from tools/gen-vectors, which calls go-ricochet's own client code:

cd tools/gen-vectors && go run . > ../../test/fixtures/go-vectors.json

License

Apache-2.0, as go-ricochet.