Skip to content
Get started

Friends

View as Markdown

Friends is the reference for your own backend. A Cloudflare Worker with a Durable Object keeps who is friends with whom and who is online on which server. A lobby bundle on each Paper server calls it. Players type /friend add <name> and /friend list, and see their friends online when they join.

Source: examples/friends. Its README explains how to deploy the Worker to your own Cloudflare account.

  • One project, two plugins. vite.config.ts has Cloudflare’s cloudflare() next to minekube(). vite build builds the Worker and the bundle; vite dev runs the Worker in workerd and installs the bundle on the dev server on every save. See Next to a Worker.
  • Typed calls both ways. src/FriendsApi.ts is an Effect RpcGroup that the bundle and the Worker both import, so a change breaks the type check on both sides.
  • The Worker knows who calls. The bundle connects with a fresh instance token on each connect, offered as the WebSocket’s second protocol. The Worker verifies it with jose against the network’s keys, checks that the key that signed it is the server it names, and hands the connection to the Durable Object with the server’s instance ID, which closes it when the token runs out. A minute before that, the bundle opens a new connection, announces its players there, and closes the old one, so they never show as offline. A member server vouches for its players: the backend believes what it says about who joined it, and lets it read and change the friends only of those players. That is no guard against a dishonest member, which can say any player joined it, and then act for them or rename them; a server you don’t trust that far doesn’t belong in the network. The token’s labels are the server’s own claim, so the Worker uses them as hints only.
  • Rules apart from the server. src/Lobby.ts imports no Java. Its Commands call the backend and answer with what it said, so Stories test the lobby without a Worker. worker/Friends.ts is tested in Bun with Effect’s RpcTest and with a WebSocket in memory.

From the repository:

Terminal window
mk api
cd examples/friends
mk server
bun run dev

mk server started in the folder puts the dev server into the network friends (dev.join), so it gets instance tokens. bun run dev runs vite dev with Node, since Cloudflare’s plugin cannot start workerd from Bun. bun test examples/friends runs the rules, the backend and the token checks.

There are no recordings and no end-to-end test with clients yet.

Was this helpful?