Server protocol (draft)
The web client speaks it today, and the native apps will (#258, #259). The client’s half is pinned by spec/online: two pure state machines, Session and TableClient, and the transcripts every client runs.
bin/test online-serverplays a hand against a local server through them. A change here changes those transcripts, and old app versions still in the stores speak it, so changes are additive unless the protocol version says otherwise (“Hello”,client): the server closes an outdated client with 4426, which spec/online treats as final.
The game server signs players in over HTTP (“Accounts”), creates tables and hands out invites over HTTP (“Tables”), lets each player name themselves (“Profile”), and then speaks JSON over one WebSocket per player. Moves and nodes use the CLI’s names and shapes (cli.md “The game node”), so a client that can drive the CLI can drive the server.
Connecting
- A table exists once its host created it with
POST /tables(“Tables”); the host sits in seat 0. Everyone else gets a seat by redeeming an invite to it (POST /invites/redeem): its link’s token, or its typed code, which may wait for the host to approve. Someone without an account may open a table’s link as a guest instead (POST /auth/guest, “Join as a guest”). Joining never creates a table, and never gives a seat. GET /tables/{table}/ws, upgraded to a WebSocket.{table}is 1 to 64 letters, digits,-or_; any other id answers HTTP 404 without upgrading.- A new table is not dealt: it waits in its lobby (“The lobby”) with the rule set, player count and
seat controllers the host asked for, until the host starts it. The start deals with the seats’
controllers as they are then. The server draws the shuffle’s
seedandstreamfrom the OS’s secure random source and never sends them. The server saves the table, in the lobby or playing, and after a restart restores it (seats, hands and all) on the next join instead of dealing again. The game is saved as a saved game, the hand’s move log and the computer players’ random sources included, so a restored table’s computer players play on exactly as they would have without the restart. - Each seat has a controller (
human,easyornormal). Computer seats are played by the table itself, with the bots, and never over the network: after the deal, after every move and afternextHand, the table applies computer actions while one of its computer seats is the seat to act and the hand is not over (cli.md “Computer seats”), then sends every connected seat its view. A computer seat is never free: an invite takes the lowest free human seat, and a table whose human seats are all taken is full. A restored table keeps its controllers. GET /healthanswers{"ok":true}. It touches neither the database nor the sign-in providers.
Every frame is a text frame holding one JSON object with a type, at most 8 KiB. A larger
message ends the connection. When the server already holds its maximum of open connections, the
upgrade is refused with HTTP 503; a client IP that opens more than 30 WebSockets a minute gets HTTP
429. A player has at most 5 connections open at once, across all tables.
After the hello, the server pings every third of the idle timeout (60 seconds by default). A connection that sends nothing, not even a pong, for the whole timeout is closed with 4408. WebSocket clients answer pings by themselves.
Hello
The first message must arrive within the hello timeout (10 seconds by default):
{"type":"hello","token":"<access token>","client":{"platform":"ios","app":"canasta","version":"2026.11.25","protocol":"1.0.0"}}-
clientsays who is calling, so the server can turn away a client it no longer speaks to. It is read first, before the token, so an outdated app is told to update even when its token has expired. Every client sends it, and a hello without it is refused withupdateRequired(the web ships with the server and the apps send it from their first store build, so only a stale page or a build from before this rule lacks it):platformisios,androidorweb.appis the client app’s id: the game for an app (canasta),homefeltfor the web. 1 to 32 characters ofa–z,0–9and-.versionis the app’s date version,YYYY.M.Dwith no leading zeros (decision 0013). The apps send it; the web, which is always the deployed build, leaves it out.protocolis the version of this protocol the client speaks,MAJOR.MINOR.PATCH. Today it is theprotocolin version.json,1.0.0. A change an older client cannot handle bumps the major.
-
The server refuses with kind
client, codeupdateRequired(close 4426) whenclientis missing, whenprotocol’s major differs from the server’s, or when an app’sversionis below its platform’s minimum (HOMEFELT_MIN_CLIENT_VERSIONS, docs/server.md). Versions compare as three numbers, year, then month, then day. The error’scontextnames what to update:{"platform": "ios", "minimum": "2026.12.3"}for an old app,{"protocol": "1.0.0"}for another major. That refusal is final: the client shows its update message and does not reconnect. -
A
protocolwith another major is refused withupdateRequiredbefore anything else inclientis read, so a later client that names a platform or app id this server does not know still hears “update”, never “not a hello”. -
A
clientthat is not an object, aplatformother than the three, anappoutside its characters, a missing or malformedversionfromiosorandroid, or aprotocolthat is notMAJOR.MINOR.PATCHof plain numbers is not a hello:noHello(close 4400). -
tokenis the access token from a sign-in or refresh (“Accounts”), sent in the message rather than the URL so it stays out of proxy and server logs. The server signed it itself (ES256, its own key id) withissandaudcanasta,subthe player’s user id (a UUID), and anexpthat has not passed (30 seconds of clock skew allowed).subnames the player. An expired token is refused withtokenExpired: refresh, then connect again. A guest’s token also hasguest, the one table it may sit at (“Join as a guest”): a hello at any other table is refused withguestNotAllowed(kindauth, close 4403), and so is one whose account the server knows as another table’s guest whatever the token says. A guest whose session has ended (removed, left, signed out, or the game over) is refused withguestEnded(kindauth, close 4410), which is final: the client shows it and does not reconnect. -
The player must hold a seat at the table: they host it, redeemed an invite to it, or sat there before. They get that seat. A deleted account is refused (
invalidToken) even while its access token has not expired, and deleting an account closes its open connections with 4401. A player with no seat there is refused withnotSeated, and an id no table has withnoSuchTable(both close with 4403). A table whose game this server does not run (a saved table from a game since removed) is refused withunknownGame(kindtable, 4403): that refusal is final, so a client shows it and does not reconnect, unliketableUnavailable. Other fields, such as an older client’sseat, are ignored.
The server answers with welcome, the game node (once the game has started), then the table:
{"type":"welcome","table":"k7m2q9x4ab3c","seat":2,"user":"6f1c2a4e-…"}{"type":"node","node":{"name":"game","path":["root","game"],"state":{…},"actions":[…],"children":[]}}{"type":"table","table":{"id":"k7m2q9x4ab3c","host":0,"paused":false,"aidsAllowed":true,"reconnectSecs":120,"seats":[…]}}The table
The table message says who sits where. It comes after the welcome and again to every connected
seat whenever any of it changes: someone takes a seat, connects or leaves, the host pauses or
continues, turns beginner aids off or on in the lobby, or a seat is handed to a computer. id echoes the host action that changed it, on the
host’s copy only.
game: which game the table holds, from the server’s fixed list of games (“Create a table”).canastais the only one so far. A client opens the table with that game’s rules and screens, and refuses a game it does not know rather than showing it as another.host: the host’s seat, ornullwhen nobody holds the role (the host deleted their account and nobody else holds a seat). It changes when the role passes on (“The host passes the role on”).started: false while the table waits in its lobby.paused: the host paused the game; moves are refused withpauseduntil they continue it.aidsAllowed: whether players at this table may use their beginner aids (spec/README.md “Beginner aids”); true unless the host turned them off before the start (“The lobby”). It holds for the whole game. Everyone sees it. While it is false no seat’s view carriesmeldable(“The seat view”), so clients show a player who has aids on why the marks are gone.reconnectSecs: how long a player who drops has to come back (120 by default). The game waits.seats, one per seat:seat;you, true for the receiving connection’s own seat;held, whether a person holds it (a deleted account’s seat stays held, by nobody);name, the holder’s display name (nullfor an empty seat, a deleted account, or no profile);nameChosen, true when the holder set that name themselves (“Profile”; false with anullname);guest, true when the holder is a guest (“Join as a guest”; clients show “guest” beside the name, false for an empty seat);controller(human,easy,normal);state, what the seat is:human(a person holds it),computer,pending(on the host’s copy only: an open seat that a waiting join request would take, one per request, in seat order; everyone else sees itopen) oropen;standIn, true when a computer plays the seat for its player, who dropped;connected; andawaySecs, how long a held seat’s player has been gone (nullwhile connected or for an empty seat). The time counts from when they left, or from when the server loaded the table. Other players’ user ids are never sent.requests: on the host’s copy, the join requests waiting for them (“Redeem a code”), oldest first, each{"id":"…","name":"Bob","nameChosen":true,"accountAgeDays":0,"expiresInSecs":1740}: the request’s id (whichapproveanddenyname), the person’s display name (nullwithout a profile) andnameChosenas on a seat, how many whole days their account has existed, and how long the request has left. Empty on every other copy. The message comes again whenever a request arrives or is decided.- A name with
nameChosenfalse is the server’s placeholder, not a name: clients show the seat as one without a name, by its number from 1 in the viewer’s language, as the hot-seat game names its seats (seat.player: “Player 2”, “Jugador 2”), whatever the text says. A join request has no seat yet, so it shows as someone without a name (“Someone”, “Alguien”). The text is “Player” for an account a sign-in named, or a dev player’s sign-in name, so a client never compares it. restored: true on the firsttablemessage each seat receives after the server brought the table back from its last save and its move log (“Moves”): after a crash or a restart that did not save it, the logged moves made since that save were replayed. A client tells the player once: “The table was restored.” It is false on every othertablemessage, and on every message of a table that was loaded from a save with nothing to replay. The seats still to tell are saved with the table, so a second restart before a seat comes back still tells it; a restart between a seat’s hello and the table’s next save may tell it twice.
The lobby
A new table waits in its lobby. Everyone seated there gets welcome and the table message (no
node: there is no game to show yet), and again the table message whenever it changes. Invites and
join requests work as at any table, and a player may leave (“Leaving”). Moves are refused with
notStarted, and so are pause and resume.
The host fills the seats and starts:
{"type":"host","action":"handOver","input":{"seat":2,"level":"easy"},"id":1}{"type":"host","action":"openSeat","input":{"seat":2},"id":2}{"type":"host","action":"start","input":{"computers":"normal"},"id":3}{"type":"host","action":"aids","input":{"allowed":false},"id":4}handOveron an open seat gives it to a computer (easyornormal), as at any table.openSeat(lobby only) opens a computer’s seat again for a person. Seat 0, a held seat, or a seat that is not a computer’s is refused withnotComputer; after the startalreadyStarted.aids(lobby only) turns beginner aids off (allowedfalse) or on again (allowedtrue) for the whole table (aidsAllowed, “The table”). It is saved with the table and everyone’stablemessage says it. Setting what is already set changes nothing; an input without a booleanallowedisinvalidInput; after the startalreadyStarted: the setting the game started with holds until it ends (Eduardo, 2026-11-24). Each player’s own aids switch stays theirs: it is never sent to the server.startdeals with the seats as they are. Open seats (openorpending) are filled with computers atcomputers(easyornormal) when it is given; without it they refuse the start withopenSeats(the message names them): the host fills them, or waits for players. Clients should offer “fill with computers” (Normal by default) when the host taps Start with seats open. Every seat then gets its node, and thetablemessage saysstarted: true. A secondstartisalreadyStarted.
The lobby is saved like any table: it survives a restart and comes back as the host left it.
Leaving
{"type":"leave"} gives up the seat for good; the server closes the connection with 1000. In the
lobby the seat is open again and the player holds no seat (an invite brings them back). Once the
game started, a Normal computer plays the seat for good: a seat never passes to another person. A
dropped connection is not leaving: the seat waits for its player (“Host actions”). If the server
cannot save the leave, nothing changes and the player gets tableUnavailable (kind seat, with
the message’s id): try again.
The host passes the role on
- A host who leaves, or deletes their account, hands the role to the next player in seat order (after the host’s seat, wrapping round) who is connected, or else to the next one who holds a seat.
- A host who stays away longer than
reconnectSecswhile someone else is connected hands it to the next connected player in seat order. Coming back after that, the old host is a player like any other. - Everyone hears of it in the
tablemessage (host). The new host is saved (with the leaver’s freed seat, in one save), and sees and decides join requests from then on. - A table nobody hosts (its host left while alone at it) gets a host again as soon as someone holds a seat there: the person in the lowest held seat, when they take it or say hello.
Host actions
Only the host sends these; anyone else gets notHost. Like do, they share the
connection’s rate limit and may carry an id.
{"type":"host","action":"pause","id":3}{"type":"host","action":"resume"}{"type":"host","action":"handOver","input":{"seat":2,"level":"easy"}}{"type":"host","action":"approve","input":{"request":"5d0c…"}}{"type":"host","action":"deny","input":{"request":"5d0c…"}}{"type":"host","action":"remove","input":{"seat":2}}pause: no moves untilresume. The game is saved paused and stays paused across restarts, so a game can be continued another day. Pausing a paused table, or resuming one that is not, changes nothing.resume: moves are taken again; a computer that is to act plays first.handOver: a computer player (leveleasyornormal,normalwhen left out) takes seatseat:- an empty human seat: the computer plays it for good, as if the host had created it so;
- a held seat whose player is gone for longer than
reconnectSecs: the computer stands in. The seat stays the player’s, and their next hello gives it back to them (the computer stops). - A seat whose player is connected is refused with
seatConnected, one still within the reconnect window withreconnectWindow(the message says how long is left), a computer seat withalreadyComputer, a seat the table does not have withnoSuchSeat.
approve: the person who asked takes the lowest free human seat, as if they had opened the link. A request that is not waiting (decided, lapsed, or unknown) is refused withnoSuchRequest; one whose invite was revoked, expired or used up meanwhile withinvalidInvite(kindinvite), which closes it; a full table withtableFull(kindseat), which keeps it waiting.deny: the request closes and the person gets no seat;noSuchRequestas forapprove.remove: the guest atseatloses it, as if they had left (“Leaving”: open again in the lobby, a Normal computer’s for good once the game started), and their guest session ends (“Join as a guest”). Their connection getsguestEndedand closes with 4410. A seat that is not a guest’s (an account’s, a computer’s, an open one) is refused withnotGuest(kindtable), a seat the table does not have withnoSuchSeat. A player with an account cannot be removed: they leave.
After an action every connected seat gets the table message, and a node when the game moved (a
computer played).
Moves
{"type":"do","action":"draw","input":{},"id":7}actionandinputare the CLI’s game actions (draw,take,lay,add,discard) and their inputs, except thatseatmay be left out: the server fills in the connection’s seat. Aseatthat names another seat is refused withnotYourSeat.inputdefaults to{}.idis optional, a non-negative integer; the answer to this move echoes it.- An input names at most 108 cards across
cardsand every meld inmelds; more isinvalidInput. - A connection may send 20
domessages a second (with a burst of 20). More are answered withrateLimitedand not run. - Moves run one at a time, in the order the table receives them.
- Every accepted move is queued for the table’s move log before anyone is answered, not written: the
table hands it to a bounded queue that one writer empties into the database, so a turn never waits
for the database (decided by Eduardo, 26 November 2026). A crash in the moment between a move’s
answer and its write loses that move: normally a few milliseconds, longer while the database is
slow, and never more than a table’s share of the queue. The log holds the moves the people at the
table made, written out again from the decoded move (never the client’s own JSON), with the seat
filled in; the computer seats’ moves are not logged, because replaying the people’s moves from the
save, with the save’s random sources, plays them again exactly. When the table is saved, the log
rows the save covers are deleted. When the server loads a table, it waits for the queue to be
written, takes the last save, lets any computer due to act in it play (as it did live), and replays
the log rows made after it, in order. A gap in the log or a row the game refuses stops the load
with
tableDamaged(kindseat), which is final: the table stays unloaded until someone repairs it. - The move is refused with
saveBacklog(kindtable) and changes nothing when the queue is full, when this table already has its share of moves waiting in it, or when the table’s last save failed and cannot be made again yet (a change such as a pause or a seat handed over is not in the log, so moves wait until it is saved). It is worth sending again in a moment. - After a move, every connected seat gets a
nodewith its own view; only the mover’s copy carriesid. A refused move changes nothing and answers the mover only:
{"type":"error","id":7,"error":{"kind":"rule","code":"notYourTurn","message":"notYourTurn","context":{}}}A rule error carries the CLI’s context (cli.md): minimum and points for the codes
that have them, else {}. It is worked out from the mover’s own move and the side’s public
minimum, and only the mover receives it.
The seat view
The node’s state is the CLI’s game state cut down to what this seat may see. It is built from an
allowlist, so a key the core adds later stays hidden until the server lists it.
- Kept:
ruleSet,hand,dealer,turn,turnStage,question,wentOut,stockCount,lastCards,specialHand(its cards are face up),pileTop,pileCount,pileHidden,pileFrozen,gameOver,winners;sideswithside,gameScore,opened,initialMinimumandmelds(each withrank,cards,kind,isCanasta,bonus);seatswithseat,side,controller,handSize,redThrees,blackThrees,bonusCards(a count);handOrder(below);scoreSheetrows withhand,dealer,wentOut,concealedandsides(each withside,melds,canastas,redThrees,goingOut,cardsInHand,unfinishedCanastas,total,gameScore,nextMinimum). “May I go out?” is asked and answered aloud, and a row exists only once its hand is over and holds points, never cards. - The viewer’s own seat, and only it, also carries
hand(its cards, in the connection’shandOrder),handPoints,meldable,discardable(each card’s points, meldable mark and discardable mark, one per card ofhand, in the same order; cli.md “The game node”) anddeclarable, also after the hand is over. They follow from the viewer’s own cards and the side’s public melds. The top-levelhandis the hand number. - While the host has turned beginner aids off (
aidsAllowedfalse in “The table”), the own seat carries nomeldableeither: a client cannot show the marks, modified or not.handPointsstays, since “Meld N points” needs it, and so dodiscardableanddeclarable, rules and not aids. handOrderis this connection’s own order for its hand,dealtwhen it says hello and then whatever its lastsortHandset (“Sorting the hand”). It is never another connection’s: each player’s node shows their own.- Dropped:
seedandstream, which would let a player replay the shuffle and read every hand and the stock (and the bots’ random sources), and the other seats’hand,handPoints,meldable,discardableanddeclarable, computer seats included. A seat no player of the table holds sees no seat’s.
actions lists the game actions (draw, take, lay, add, discard, ask, answer,
declare, layOutThree, nextHand, sortHand) with seat taken out of each input schema. The server fills in the
connection’s seat; nextHand and sortHand take none, so any seat may deal the next hand once one
is over. newGame is not offered: the server deals. The CLI state’s view and viewer are not on
the allowlist, so they stay hidden; the server deals with view all. A do whose action is not
one of those offered (newGame included) is refused with protocol unknownAction before its
input is read, and changes nothing.
Sorting the hand
{"type":"do","action":"sortHand","input":{"order":"rank"},"id":9}orderisdealt,rankorsuit, sorted as the CLI’ssortHandsorts (Hand order). It sets this connection’shandOrder, and nothing else: it is not a move, the table’s game and every other seat’s view stay as they were, it is never saved, and no other connection hears of it, neither a node nor atablemessage.- The answer is a
nodeto this connection only, withid: its ownhand,handPoints,meldableanddiscardablein the new order andhandOrderset. Every node it gets after that keeps the order, cards drawn or taken later included. - The order lasts as long as the connection: a new hello starts at
dealt, so a client that wants its order back sendssortHandagain after the welcome. - It is answered at any stage of a started game, a paused one and a finished hand included. In the
lobby it is refused with
notStarted. An input other than{"order":…}(aseatincluded) isinvalidInput, as in the CLI. It counts toward thedorate limit.
Errors
error.kind is one of:
| Kind | Codes | Meaning |
|---|---|---|
protocol |
noHello, badJson, badRequest, rateLimited, tooManyConnections, and the CLI’s unknownAction, invalidInput |
The message could not be read, does not fit its schema, or came too fast; or the player has too many connections |
rule |
the engine’s rule error codes | The move breaks a rule |
auth |
invalidToken, tokenExpired, guestNotAllowed, guestEnded, and over HTTP tooManyAccounts |
The access token was refused, the IP made too many accounts, a guest asked for something outside their table, or a guest’s session ended |
seat |
notYourSeat, notSeated, noSuchTable, noSuchSeat, tableFull, tableClosed, tableUnavailable, tableDamaged, and over HTTP tooManyGuests |
The seat acted for is not this connection’s, the player holds no seat at the table, there is no such table or seat; or the saved table could not be loaded (tableUnavailable: try again; tableDamaged: its move log does not replay, final) |
table |
paused, notHost, notGuest, seatConnected, reconnectWindow, alreadyComputer, noSuchRequest, notStarted, alreadyStarted, openSeats, notComputer, serverBusy, saveBacklog, and over HTTP unknownGame, unknownRuleSet, invalidPlayers, invalidControllers, tooManyTables, tooManyTablesPerHour, tableClosed |
The game is paused, a host action was refused, the server holds its maximum of tables or is behind on saving moves (saveBacklog, worth retrying), or a table could not be created |
profile |
over HTTP invalidName, tooManyRenames |
A new display name breaks the name rules, or came less than 5 seconds after the last (“Set your name”) |
invite |
invalidInvite, rateLimited, removed, tooManyInvites, tooManyRequests, noSuchRequest, alreadyApproved |
An invite or a join request was refused (HTTP, and invalidInvite for approve) |
client |
updateRequired |
This client is too old for the server (“Hello”, client): update the app, or reload the page |
Close codes
| Code | When |
|---|---|
| 4400 | No hello, or something other than a hello, within the timeout |
| 4401 | The token was refused (after an auth error) |
| 4403 | No such table, no seat there for this player, a table of a game the server does not run (unknownGame), a table whose move log does not replay (tableDamaged), or the table cannot be loaded now (after a seat or table error; only tableUnavailable and serverBusy are worth retrying) |
| 4408 | Nothing arrived, not even a pong, within the idle timeout |
| 4409 | The same player connected to the table again; the older connection is closed |
| 4410 | A guest’s session ended (guestEnded): the host removed them, they left or signed out, or the game is over; final |
| 4426 | The client must update (after updateRequired, kind client); final until it does |
| 1000 | The player left the table for good (leave) |
| 4428 | The player said hello more than 30 times this minute (rateLimited), or already has 5 connections open (tooManyConnections) |
| 4429 | The client read its messages too slowly; 64 were waiting to be sent |
| 1001 | The server is stopping. The table was saved; reconnect and send a hello to continue |
Every close finishes the WebSocket close handshake: the server waits up to a second for the client’s reply to its own close, and answers a close the client starts (1000 when leaving) with the same code before it drops the connection, so a client never sees 1006 for a clean close.
A player who disconnects keeps their seat, and gets it back on their next hello.
Tables
JSON over HTTP, with the access token as Authorization: Bearer <access token> (401 invalidToken or
tokenExpired without a valid one). Bodies are at most 8 KiB, errors have the shape “Accounts”
describes, and every endpoint here shares one allowance per client IP (60 requests a minute by
default, IPv6 by /64; more answer 429 rateLimited). A guest’s token is refused by every endpoint
here with 403 guestNotAllowed (kind auth), and redeeming refuses a guest’s account whatever its
token says: a guest creates, lists, invites to and redeems nothing (“Join as a guest”).
Create a table
POST /tables, every field optional:
{"game":"canasta","ruleSet":"family","players":4,"controllers":["human","easy","human","normal"],"aidsAllowed":true}gameis the game the table holds, one id from the server’s fixed list, spelled exactly:canastais the only one so far, and the default when left out. The rule sets below are that game’s. A table keeps its game for its whole life.ruleSetis a rule set id fromspec/rulesets(the server’s default when left out),playersa count the rule set deals (the default 4),controllersone per seat (allhumanby default). Seat 0 is the host’s and must behuman.aidsAllowed(true by default) is whether players may use their beginner aids at the table (“The table”); the host may change it withaidsuntil the start (“The lobby”).- The answer is 201 with the new table’s id (12 random letters and digits), which the WebSocket URL takes. The caller hosts it and holds seat 0, and the table waits in its lobby (“The lobby”):
{"table":{"id":"k7m2q9x4ab3c","game":"canasta","seat":0,"host":"6f1c2a4e-…"}}| Status | Code | When |
|---|---|---|
| 400 | badRequest (kind protocol) |
The body is not this JSON (unknown fields included, a game that is not a string, or an aidsAllowed that is not a boolean) |
| 400 | unknownGame |
game is not one of the server’s games |
| 400 | unknownRuleSet, invalidPlayers, invalidControllers |
The request does not make a table |
| 429 | tooManyTables |
The host has 10 tables that are not finished (open, playing or paused) |
| 429 | tooManyTablesPerHour |
The host created 10 tables in the last hour |
| 503 | serverBusy |
The server holds its maximum of tables in memory; try again later |
| 503 | tableUnavailable |
The database did not answer; try again |
Your tables
GET /me/tables lists the tables the caller can go back to, so a table closed without leaving is
not lost: every table that is not finished where they hold a seat, and every table where a join
request of theirs waits for the host. At most 50, the most recently active first, then the waiting
requests, newest first:
{"tables":[ {"id":"k7m2q9x4ab3c","game":"canasta","ruleSet":"family","players":4,"membership":"seated","seat":2,"host":0, "started":true,"paused":false,"turn":2, "seats":[{"seat":0,"you":false,"state":"human","name":"Abuela","nameChosen":true}, {"seat":1,"you":false,"state":"computer","name":null,"nameChosen":false}, {"seat":2,"you":true,"state":"human","name":"Eduardo","nameChosen":true}, {"seat":3,"you":false,"state":"open","name":null,"nameChosen":false}]}, {"id":"p4r8w2n6cd9e","game":"canasta","ruleSet":"family","players":4,"membership":"pending", "request":"5d0c…","expiresInSecs":1500}]}membershipsays which it is:seated(the caller holdsseat) orpending(a join request,request, whichGET /invites/requests/{request}follows and lapses inexpiresInSecs).gameis the table’s game (“Create a table”), on every entry, seated or pending;ruleSetis the rule set’s id andplayersits player count.- A seated table also has
host(the host’s seat,nullwhen nobody holds the role),started(false in the lobby),paused(the host paused it),turn(the seat to act, which is the asker’s partner while a question waits;nullin the lobby and between hands), andseats, one per seat as thetablemessage has them, but onlyseat,you,state(humanfor a seat a person holds, a deleted account’s included;computer;open),name(the holder’s display name,nullotherwise) andnameChosen(shown as in “The table”). A table in memory answersturnas it stands; any other, as it was last saved. - A pending table has only the fields above: who sits there is for the people seated, and the host has not let the caller in yet.
- No hand, stock, seed or other player’s user id is ever in it.
Invite to a table
POST /tables/{table}/invites with an optional {"maxUses":3} (unlimited when left out) answers 201:
{"invite":{"token":"q3V8…22 characters","code":"K7M2Q9","codeExpiresInSecs":1800,"expiresInSecs":604800,"table":"k7m2q9x4ab3c","game":"canasta"}}The host or a player seated at the table may invite. An invite has two secrets:
token, what the invite link carries: 128 random bits in base64url (22 characters). It opens the invite once (one person joins with it), never waits for approval, and lasts as long as the invite, 7 days (expiresInSecs). The server keeps only its SHA-256.code, the typed fallback for someone without the link: 6 symbols from23456789ABCDEFGHJKLMNPQRSTUVWXYZ, which expirescodeExpiresInSecsafter it was made (30 minutes by default, never after the invite). Show it with that expiry. A code typed by someone the host does not know becomes a join request (“Redeem a code”).
maxUses counts the people who join through the invite, by link, code or approval. A table has at
most 20 open invites, and a person at most 20 live ones in all (groups and tables).
| Status | Code | When |
|---|---|---|
| 403 | notSeated (kind seat) |
The caller is neither the host nor seated there |
| 404 | noSuchTable |
No table has that id |
| 409 | tableClosed |
The game is over |
| 429 | tooManyInvites (kind invite) |
20 open codes for the table, or 20 live codes of the caller’s |
Redeem a code
POST /invites/redeem takes the link’s token, {"token":"q3V8…"}, or a typed code,
{"code":"k7m2q9"} (case and surrounding spaces do not matter), never both. It joins the invite’s
group, or seats the caller at its table in the lowest free human seat. The answer is 200:
{"outcome":"seated","table":"k7m2q9x4ab3c","game":"canasta","seat":2}{"outcome":"alreadySeated","table":"k7m2q9x4ab3c","game":"canasta","seat":2}{"outcome":"joined","group":"0b9e…"}{"outcome":"alreadyMember","group":"0b9e…"}Then the player says hello on the table’s WebSocket. Every answer that names a table also names
its game, so the client opens the right game before the table message arrives.
- A token always seats or joins at once, and is then used up. It never counts as a failure and is never refused by the failure budgets below: 128 bits are not guessed.
- A typed code seats or joins at once only someone the host trusts: who shares a group with the
table’s host (for a group code, with the group’s owner or the code’s creator while they still
belong to the group). Anyone else gets
202 and a join request that waits for the host, who sees it in the
tablemessage and answers withapproveordeny(“Host actions”). For a group, the owner or the code’s creator decides (the group endpoints are not served yet). A request lapses after 30 minutes; typing the code again while it waits answers the same request. At most 10 wait at a table or group.
{"outcome":"pending","request":"5d0c…","table":"k7m2q9x4ab3c","game":"canasta","expiresInSecs":1800}GET /invites/requests/{request} tells the person who asked where their request stands:
{"request":{"status":"pending","expiresInSecs":1500}}{"request":{"status":"approved","table":"k7m2q9x4ab3c","game":"canasta","seat":2}}{"request":{"status":"approved","group":"0b9e…"}}{"request":{"status":"denied"}}{"request":{"status":"lapsed"}}{"request":{"status":"withdrawn"}}Anyone else’s request, or an unknown id, is 404 noSuchRequest (kind invite). Once it is
approved, the player says hello on the table’s WebSocket.
| Status | Code | When |
|---|---|---|
| 400 | badRequest (kind protocol) |
Neither or both of code and token |
| 404 | invalidInvite (kind invite) |
No such code or token, or it is revoked, expired or used up. A typed code counts as a failure |
| 403 | removed (kind invite) |
The group’s owner removed the caller |
| 409 | tableFull (kind seat) |
No free human seat |
| 409 | seatRefused (kind seat) |
The seat could not be given (the account was deleted meanwhile); nothing changed |
| 409 | tableClosed (kind table) |
The game is over |
| 429 | tooManyRequests (kind invite) |
10 join requests already wait at the table or group |
| 429 | rateLimited (kind invite, with Retry-After) |
Typed codes only. Too many failures: 20 in the last hour for this user (5 for an account younger than 7 days) or 60 for this IP (IPv6 by /64); after 3, each next attempt waits twice as long as the last (2 seconds, up to 5 minutes); and once the server has seen 1,000 failures in the hour, anyone (user or IP) who failed in that hour. Someone with no recent failure still redeems. A refused attempt counts as a failure too (up to 100 an hour), so waiting is the only way through. A person the host trusts, typing a good code for that host’s table or group, has a budget of 100 per user and per IP instead, so the family is not locked out by someone else’s guessing from its home IP |
Withdraw a join request
DELETE /invites/requests/{request} withdraws the caller’s own join request and answers 204: it
stops waiting, the host’s requests list (and the seat it showed as pending) drops it at once,
and GET /invites/requests/{request} says withdrawn. Withdrawing again, or withdrawing a request
that was already denied or lapsed, changes nothing and answers 204 too. A request the host already
approved is not undone: 409 alreadyApproved (kind invite), and the caller holds the seat (leave
the table to give it up). Anyone else’s request, or an unknown id, is 404 noSuchRequest, so the
answer never shows which requests exist. If the host approves at the same moment, one of the two
wins: the withdrawal, and the host’s approve is refused with invalidInvite; or the approval,
and the withdrawal answers 409.
Revoke an invite
DELETE /invites/{code} (its code, even once the code has expired) answers 204, and both its code
and its link stop working. Its creator, the group’s owner or the table’s host may revoke
it; anyone else, or an unknown code, gets 404 invalidInvite.
Profile
JSON over HTTP like “Tables”: Authorization: Bearer <access token> (401 invalidToken or
tokenExpired without a valid one, and invalidToken for a deleted account), bodies of at most
8 KiB, and the same allowance per client IP as the table endpoints. A player reads and changes
only their own profile: there is no user id in the path. A guest may read and change theirs.
Read your profile
GET /me answers:
{"user":{"id":"6f1c2a4e-…","displayName":"Player","nameChosen":false,"guest":false}}-
guestis true for a guest (“Join as a guest”). -
displayNameis what tables call the player once they choose it. A first sign-in names a new accountPlayer, a placeholder. -
nameChosenis false until the player sets a name withPATCH /me, however they were named before (a first sign-in, or a dev player’s sign-in name). Clients ask for a name after a sign-in while it is false (they may let the player skip, and ask again next time). While it is false, tables show the player’s seat by its number (“The table”), and their own name line, which has no seat, shows the client’s word for a player (player.unnamed: “Player”, “Jugador”).
Set your name
PATCH /me {"displayName":"Abuela Rosa"} sets the name and answers like GET /me, with
nameChosen true. The server reads the name in this order, and refuses it at the first rule it
breaks:
- It is normalised to Unicode NFC (
e+ U+0301 becomesé), and the stored name is that form. - White space is trimmed from both ends.
- It is 1 to 40 characters (Unicode scalar values, counted after NFC).
- It holds no hidden character: no control character (
Cc, such as tabs and newlines), no format character (Cf: the bidirectional marks, embeddings, overrides and isolates that could make a name read in another order, zero-width spaces and joiners such as U+200B, U+200D and U+2060, U+FEFF, the soft hyphen U+00AD, tag characters U+E0000 to U+E007F), no line or paragraph separator (Zl,Zp), and none of the blank fillers U+115F, U+1160, U+3164, U+FFA0 and U+2800. So “Abuela” with a zero-width space cannot pass for “Abuela”. (Emoji sequences joined with U+200D, such as a family of three, are refused for the same reason; single emoji are fine.) - It holds at least one letter, number or symbol (
L,NorS), so a name never looks blank. - It has at most 2 combining marks (
M) in a row, which stops “zalgo” text spilling over the names around it (éand an emoji’s variation selector are one mark each).
A name that breaks a rule answers 400 invalidName (kind profile), and nothing changes. A body
that is not this JSON (a missing or non-string displayName, or another field) answers 400
badRequest. A player renames at most once every 5 seconds: a valid name sent sooner answers 429
tooManyRenames (kind profile) with a Retry-After header, and nothing changes. Refused names
do not count.
Names that come from a sign-in (Apple’s, Google’s, or a dev player’s) follow the same rules, by
repair instead of refusal: normalised, hidden characters dropped, combining runs cut to 2, trimmed
and cut to 40 characters; Player when no letter, number or symbol is left. Two players at a table
may have the same name.
Every table shows the new name: the table message’s seat name and the host’s join requests.
The server tells only the tables where the player holds a seat or has a pending join request (from
its saved seats and requests): each of those open in memory sends its table message again at
once to every connected seat; any other table reads the name when it next opens.
Accounts
JSON over HTTP. Bodies are at most 8 KiB (more answers HTTP 413). Every endpoint here shares one
allowance per client IP (20 requests a minute by default, IPv6 clients by /64); more answer 429
rateLimited with a Retry-After header. Errors have the WebSocket’s shape:
{"error":{"kind":"auth","code":"invalidToken","message":"The token was refused."}}The message is the same for every refusal with that code; the client never learns which check failed.
Sign in
POST /auth/apple and POST /auth/google:
{"idToken":"<the provider's identity token>","nonce":"<the raw nonce>","authorizationCode":"<Apple only, optional>"}- Before each sign-in the app makes a raw nonce (32 random bytes, base64url; 16 to 128 visible ASCII
characters are accepted) and hands its SHA-256, in lowercase hex, to the provider’s SDK
(
ASAuthorizationAppleIDRequest.nonce, Google Sign-In’s or Credential Manager’snonce). The identity token comes back with that hash in itsnonceclaim; the app sends the raw nonce here. - Apple tokens must have
isshttps://appleid.apple.comandaudthe bundle id (dev.edsancha.homefelt.canasta) or a configured Services ID. Google tokens must haveisshttps://accounts.google.comoraccounts.google.comandaudone of the server’s Google client ids. Both are RS256, signed by a key in the provider’s JWKS, unexpired, with a non-emptysub. authorizationCodeis Apple’s one-time code from the same sign-in: the iOS app’sASAuthorizationAppleIDCredential.authorizationCode, or the web client’sauthorization.codefrom Sign in with Apple JS. The server trades it for the Apple refresh token it needs to revoke the user’s Apple sign-in when they delete their account, using the client id the identity token was issued to (itsaud):- the bundle id: traded as the app;
- the server’s web Services ID: traded as that Services ID with its registered return URL, and
only on a browser request (below) whose
Originis the return URL’s origin. A web code from anywhere else is not traded. The server trades each code once and never retries it (Apple accepts a code once, within five minutes). It keeps the refresh token only when theid_tokenin Apple’s answer names the same Apple user (sub) as the identity token just checked, and the client id the code was traded as (aud), so a code from someone else’s sign-in never lands on this account. A code that is refused, not traded, or answered for another user or client id does not fail the sign-in; the account then has no Apple token for that client id until a later sign-in brings one.
- The first sign-in with a provider account creates the user. One client IP (IPv6 by /64) creates
at most 10 accounts an hour; past that a first sign-in answers 429
tooManyAccounts, while people who already have an account still sign in. The answer:
{"tokenType":"Bearer","accessToken":"eyJ…","expiresIn":900,"refreshToken":"q3V…","refreshExpiresIn":2592000,"user":{"id":"6f1c2a4e-…"},"created":true}expiresIn and refreshExpiresIn are seconds. created says the account is new.
| Status | Code | When |
|---|---|---|
| 400 | badRequest (kind protocol) |
The body is not this JSON |
| 401 | invalidToken |
The identity token or the nonce was refused |
| 401 | tokenExpired |
The identity token has expired; sign in again |
| 429 | tooManyAccounts (with Retry-After) |
This IP created 10 accounts in the last hour; existing accounts still sign in |
| 404 | providerDisabled |
This server has no client ids for Google |
| 503 | authUnavailable |
The provider’s keys or the database are unreachable; try again |
Refresh
POST /auth/refresh {"refreshToken":"…"} answers a new pair in the same shape (without created;
a guest’s also carries guest, below).
The token sent is used up: keep only the new one. Sending a used token again revokes every token
descended from the same sign-in, so refresh one at a time. A refused token answers 401
invalidRefreshToken: sign in again.
Log out
POST /auth/logout {"refreshToken":"…"} revokes the tokens of that sign-in and answers 204, whether
or not the token was known. The access token stays valid until it expires (at most 15 minutes). A
guest who logs out ends their guest session: they have no other way back in.
Browsers
The web client cannot keep a refresh token where a page script could read it, so it asks for the
browser shape: every request to /auth/* carries the header X-Canasta-Client: web and is sent
with credentials (fetch(…, {credentials: "include"})).
- Origins. The server lists the web client’s origins (
HOMEFELT_WEB_ORIGINS, exactscheme://host[:port], none by default). Only a listed origin gets CORS headers, credentials included, on the/auth/*,/tables*,/invites*and/meendpoints. A request with the header whoseOriginis missing or not listed answers 403forbiddenOrigin(kindauth) before anything else; any other value of the header answers 400badRequest. - Sign-in (
/auth/apple,/auth/google) answers the same JSON withoutrefreshToken, and sets the cookiehomefelt_refresh=<refresh token>; Path=/auth; Max-Age=<refreshExpiresIn>; HttpOnly; Secure; SameSite=Strict. - Refresh reads the token from that cookie, ignores the body, and answers like a sign-in (a new
cookie replaces the old). Without a cookie, or with a refused one, it answers 401
invalidRefreshTokenand clears the cookie (Max-Age=0). The cookie is used up like the body’s token: a browser refreshes one request at a time, across its tabs too. - Log out reads the token from the cookie, revokes its sign-in, clears the cookie and answers 204, with or without a cookie.
- A request without the header never reads or sets the cookie, so a form on another site, which can
send the cookie but not the header, gets 400
badRequestfrom/auth/refreshand/auth/logout, and nothing changes. - The access token is in the body only; the web client keeps it in memory and sends it as the
apps do (
Authorization: Bearerand the WebSocket hello). WebSockets are not subject to CORS; the hello’s token, not a cookie, is what admits a connection. SameSite=Strictmeans the web client and the server must be the same site (one registrable domain, such ascanasta.exampleandapi.canasta.example); otherwise the browser never sends the cookie.
Join as a guest
Someone without an account opens a table’s invite link and sits down as a guest: a name they type, a seat at that one table, and nothing else (Eduardo, 2026-11-25; decision 0018). Typed codes still need an account, so the guessing defences in “Redeem a code” keep their per-account budgets.
POST /auth/guest {"token":"<the link's token>","displayName":"Abuela"}, a browser request as for
sign-in (“Browsers”), answers 200 with a sign-in’s pair and the guest’s table:
{"tokenType":"Bearer","accessToken":"eyJ…","expiresIn":900,"refreshToken":"q3V…","refreshExpiresIn":2592000,"user":{"id":"6f1c…"},"created":true,"guest":{"table":"k7m2q9x4ab3c","game":"canasta","seat":2}}- The name follows “Set your name”’s rules (refused, not repaired), and is the guest’s chosen name
(
nameChosentrue). - The token seats them as it would seat anyone (“Redeem a code”), in the lowest free human seat,
and is used up. A group’s link makes no guest (403
guestNotAllowed): guests join no group. - A guest is an account with no sign-in identity. The access token’s
guestclaim names the table (“Hello”), and so does the refresh’s answer ({"guest":{"table":…,"game":…}}). Then the guest says hello on that table’s WebSocket. - A guest uses that table’s WebSocket,
GETandPATCH /me(guesttrue) andDELETE /account. Every other endpoint refuses them with 403guestNotAllowed: no tables to list, none to create, no invites to make or redeem, no join requests. A guest never takes the host role (“The host passes the role on” skips them); a table where only guests are left has no host until someone with an account sits down. - The guest keeps the seat across every hand of the game. The session ends, for good, when the
host removes them (
remove, “Host actions”), they leave the table or log out, their refresh token lapses unused, the game ends (the table closes), or the last player with an account leaves a table still in its lobby (nobody is left who could start it: each guest’s seat opens again). Then their refresh tokens are revoked, a refresh answers 401invalidRefreshToken, and a hello getsguestEnded(close 4410). A guest still connected when the game ends sees the end of it. - A guest’s account, with its name, is deleted 30 days after the session ended, as “Delete the account” deletes one, unless it has gained a sign-in by then (#262). A guest who just stops playing ends when the refresh token lapses, 30 days after their last refresh, so a guest of an abandoned table is gone within about 60 days.
- A guest whose seat the host removed while they were reconnecting gets
guestEnded, notnotSeated.
| Status | Code | When |
|---|---|---|
| 400 | badRequest (kind protocol) |
The body is not this JSON (unknown fields included) |
| 400 | invalidName (kind profile) |
The name breaks a rule |
| 404 | invalidInvite (kind invite) |
No such token, or it is revoked, expired or used |
| 403 | guestNotAllowed |
A group’s link |
| 409 | tableClosed (kind table) |
The game is over |
| 409 | tooManyGuests (kind seat) |
The table has 3 guests whose session goes on: sign in to join |
| 409 | tableFull, seatRefused (kind seat) |
No free human seat, or it could not be given |
| 429 | tooManyAccounts (with Retry-After) |
This IP made 10 accounts and guests in the last hour |
| 503 | authUnavailable |
The database did not answer; try again |
Delete the account
DELETE /account with Authorization: Bearer <access token> answers 204. The server revokes the
user’s Apple sign-in (each Apple token it holds for them, with the client id that token was issued
to: the bundle id for the app’s, the Services ID for the web’s), marks the account deleted and signs it
out everywhere. Signing in again with the same Apple or Google account creates a new account. 401
invalidToken or tokenExpired when the access token is refused.
Not yet
Avatars (a profile has no picture yet), reconnect tokens, spectators, reading a table over HTTP, giving a seat to another
person, a rematch at the same table (a guest’s scope is the table, so their seat would carry over while it stays open),
and turn timers arrive in later checkpoints. A table is saved when it is created, when a
seat is taken, given back or left, when the host starts it, when a hand ends or the next is dealt,
when the host acts or the role passes on, when its last player leaves, when it leaves memory and
when the server stops. Moves in between are queued for the move log (“Moves”); a crash loses only
the moves not yet written at that instant: the last few milliseconds’ worth while the database keeps
up, and at most a table’s share of the queue (HOMEFELT_MOVE_LOG_PER_TABLE, docs/server.md) while it
is behind.