Skip to content

Game server

rust/canasta-server: Homefelt’s game server, today serving Canasta only. An Axum server that signs players in with Apple or Google, lets them create tables and invite friends over HTTP, seats them at tables over WebSockets with its own access tokens, runs every move through canasta-rules (the same engine the Rust CLI uses), and keeps accounts, games, groups and invites in Postgres. The wire protocol is spec/protocol/server.md, and its client half spec/online. This page covers how the server is built, how to run it, and how it stores what it knows.

Tables are saved in Postgres and survive a restart (“Persistence” below). In production it will run as one always-on Fly.io machine at https://api.homefelt.io, with Postgres on Neon; it is not deployed yet (#50) (deploy.md, “Game server”; decision 0012). The tests that need no database run tables on an in-memory store.

Shape

File Holds
src/app.rs The router (/health, /tables/{table}/ws) and the state handlers share
src/ws.rs One connection: size limits, the connection cap, hello within the timeout, access token check, the player’s seat, then a reader (rate limit, idle timeout, moves and host actions) and a writer (pings); every close finishes the close handshake
src/http_auth.rs The sign-in endpoints (/auth/*, DELETE /account), the per-IP rate limit and the body cap
src/http_tables.rs The table endpoints: POST /tables, POST /tables/{table}/invites, POST /invites/redeem, GET and DELETE /invites/requests/{id}, DELETE /invites/{code}, and GET /me/tables, with their own per-IP allowance
src/http_profile.rs GET /me and PATCH /me: the caller’s display name, served with the table endpoints (same token check and allowance)
src/sessions.rs Sign-in identities and refresh tokens in Postgres
src/table.rs One task per table. It owns the game and the seats (the only place a seat is given), caps card counts, applies moves and host actions one at a time, and leaves memory when idle; Tables creates, loads and finds them; each connection’s bounded outbox
src/web.rs The web client: the allowed origins and CORS on the HTTP routes, the refresh cookie and the origin check that guards it
src/view.rs What one seat may see: an allowlist that fails closed, drops seed/stream and other hands; the own hand’s points, meldable marks (left out while the host turned aids off) and per-connection order
src/auth/jwks.rs Identity token checks against a provider’s JWKS: one algorithm per issuer, caching, a refetch cooldown, single flight
src/auth/providers.rs Apple’s and Google’s issuers, keys and audiences, and the nonce check
src/auth/tokens.rs The server’s own ES256 access tokens
src/auth/apple.rs Apple’s token exchange and revocation, for account deletion, as the app’s bundle id or the web Services ID
src/auth/config.rs The sign-in settings
src/protocol.rs The message types and close codes
src/config.rs Settings from the environment, and the rule set loader
src/games.rs The fixed list of games a table can hold (canasta); a table keeps its game, saved in tables.game, and one of a game the server does not run is never loaded
src/store.rs TableStore, the trait a table task saves through, and NoStore (memory only)
src/move_log.rs The move log’s bounded queue, which every table hands its accepted moves to, and its one writer, which appends them to the store in order
src/db/ Postgres: the pool and migrations (mod.rs), PgStore, users and account deletion, tables and results, friendships
src/guests.rs Guests from invite links (“Guests”): making one from a link and a name, ending guest sessions, where a guest stands for the hello, and the hourly deletion of ended guests
src/groups.rs, src/invites.rs Groups and membership; invites (link tokens and typed codes), redeeming them, join requests and trust (“Invites”)
src/alerts.rs The inviteFailures and untrustedCode alerts, the move log’s moveLogBehind, moveLogConflict and tableDamaged (Persistence, “The move log”), and connectionsHigh: structured log lines, counts in the metrics, and pushes through ntfy for all but untrustedCode
src/metrics.rs The Prometheus metrics: connections and their peak, tables in memory, moves and refusals by code, move and save latency, the move log’s queue; served on HOMEFELT_METRICS_ADDR only
src/notify.rs Push alerts to ntfy: off without HOMEFELT_NTFY_TOPIC, once per kind per interval, in the background, the topic never logged
migrations/ The schema, as sqlx migrations, compiled into the binary
src/bin/canasta-dev-seed.rs bin/dev seed: dev players’ group and table (dev-auth builds only; development.md)
  • One writer per table. Connections never touch game state. They send commands to the table’s task over a channel, and the task answers each seat on that seat’s own outbox. Two players acting at once are serialised by the channel, so there are no locks around the game and no lost updates.
  • Fail-closed view. The view starts from an empty object and copies only listed keys. A new key in game_screen::state_json stays hidden until someone adds it to view.rs on purpose. seed and stream are never sent: with them a player could replay the PCG32 shuffle and read every hand.
  • Randomness is injected. Tables takes a Seeds function. main.rs reads 16 bytes from the OS’s secure random source (aws_lc_rs::rand); tests pass the parity deal (seed 15, stream 54).
  • Seats belong to players. A seat is held by the access token’s sub (our users.id), not by the connection, so a dropped phone gets its seat back. A second connection by the same player replaces the first (4409).
  • One seat authority. Only a table’s task gives seats: to the host when it creates the table, and to whoever redeems an invite, which asks the task (loading the table if it must). The task saves the seat, the snapshot and the invite’s use in one transaction, so Postgres and memory never disagree about who sits where. Postgres never seats anyone on its own.

Configuration

Variable Default Meaning
DATABASE_URL required postgres://user:password@host:5432/db: the Postgres the server keeps users, sessions, tables, groups and invites in
HOMEFELT_DB_MIGRATE true Run migrations/ on start-up; false when migrations are applied separately
HOMEFELT_DB_MAX_CONNECTIONS 5 Pool size, shared by sign-in and the tables. A table task uses one connection while it saves
HOMEFELT_TOKEN_KEY or HOMEFELT_TOKEN_KEY_FILE required The server’s P-256 private key in PEM (PKCS#8 or SEC 1), inline or as a file path (for a mounted secret). It signs our access tokens
HOMEFELT_TOKEN_ISSUER homefelt iss and aud of our access tokens
HOMEFELT_ACCESS_TOKEN_SECS 900 Access token lifetime (15 minutes)
HOMEFELT_REFRESH_TOKEN_DAYS 30 Refresh token lifetime; each refresh starts it again
HOMEFELT_APPLE_BUNDLE_ID dev.edsancha.homefelt.canasta The iOS app’s bundle id: an accepted aud of Apple identity tokens, and the client_id for Apple’s token API
HOMEFELT_APPLE_SERVICE_IDS none More accepted Apple audiences, comma separated (a Services ID, for Sign in with Apple on the web or Android). Their codes are not traded; the web one goes in HOMEFELT_APPLE_WEB_SERVICES_ID
HOMEFELT_APPLE_WEB_SERVICES_ID, HOMEFELT_APPLE_WEB_REDIRECT_URI none Sign in with Apple on the web: the Services ID the web client signs in with (its VITE_APPLE_SERVICES_ID) and the return URL registered for it (its VITE_APPLE_REDIRECT_URI, https://, its origin in HOMEFELT_WEB_ORIGINS). Both or neither. The Services ID is an accepted audience, and its codes are traded as it (with the Apple key below) so deleting a web account revokes its Apple token (“The web client”)
HOMEFELT_GOOGLE_CLIENT_IDS none Accepted aud of Google ID tokens, comma separated: the iOS client id, and the web (server) client id the Android app passes to Credential Manager. Empty turns Google sign-in off
HOMEFELT_APPLE_TEAM_ID, HOMEFELT_APPLE_KEY_ID, HOMEFELT_APPLE_PRIVATE_KEY or HOMEFELT_APPLE_PRIVATE_KEY_FILE none The Sign in with Apple key (.p8) for revoking Apple tokens on account deletion, for the bundle id and the web Services ID alike. All three or none; without them revocation is skipped with a logged TODO
HOMEFELT_AUTH_PER_MINUTE 20 Requests to /auth/* and DELETE /account per client IP per minute (burst of the same size); more get 429
HOMEFELT_SIGN_UPS_PER_IP 10 New accounts one client IP (IPv6 by /64) may create by Apple or Google sign-in, or as guests (POST /auth/guest), in an hour; more get 429 tooManyAccounts. Existing accounts always sign in; the dev sign-in has no limit
HOMEFELT_GUESTS_PER_TABLE 3 Guests whose session goes on at one table (“Guests”); one more is refused with 409 tooManyGuests
HOMEFELT_GUEST_DAYS 30 Days a guest whose session ended is kept before the hourly job deletes it (unless it gained a sign-in, #262); the privacy page says so
HOMEFELT_TRUST_PROXY off 1: take the client IP from the last X-Forwarded-For entry, for every per-IP limit (sign-in, table endpoints, WebSocket upgrades, invite failures). Turn it on only behind exactly one trusted proxy that appends the client’s address as the last X-Forwarded-For entry, with the server’s own port not reachable from the internet; otherwise any client can name any IP and every per-IP limit is void. Leave it off in every other setup, Fly.io included (its last entry is the app’s own address)
HOMEFELT_CLIENT_IP_HEADER none A header the one trusted proxy in front sets to the client’s address and clients cannot set, read instead for every per-IP limit: fly-client-ip on Fly.io (fly.toml). A missing or unreadable value falls back to the TCP peer. Not with HOMEFELT_TRUST_PROXY, and never X-Forwarded-For or Forwarded
HOMEFELT_APPLE_JWKS_URL, HOMEFELT_GOOGLE_JWKS_URL, HOMEFELT_APPLE_API_URL Apple’s and Google’s Overrides for tests or a proxy. Must be https; http is allowed only for localhost, 127.0.0.1 and [::1]
HOMEFELT_WEB_ORIGINS none The web client’s origins, comma separated and exact (https://canasta.example; http:// only for localhost, 127.0.0.1, [::1]; no path, no wildcard). They get CORS headers on the HTTP routes and may use the refresh cookie (“The web client”). Empty: no CORS headers and no web sign-in
HOMEFELT_DEV_AUTH off 1: serve POST /auth/dev (see “Local development”). Only in a build with the dev-auth feature; a default build refuses to start with it
HOST, PORT 0.0.0.0, 8080 Where to listen
HOMEFELT_SPEC spec The spec folder; rule sets load from <spec>/rulesets
HOMEFELT_RULE_SET family The rule set of a new table when POST /tables names none. Every rule set in <spec>/rulesets can be asked for
HOMEFELT_PLAYERS 4 Seats of a new table when POST /tables names no count; checked against the rule set at start-up
HOMEFELT_CONTROLLERS every seat human Who plays each seat when POST /tables names nobody, comma-separated: human, easy or normal (for example human,easy,normal,easy). Seat 0 is the host’s and must be human. Computer seats are played inside the table task and are never free; the list must name one per seat
HOMEFELT_RECONNECT_SECS 120 How long a player who dropped has to come back before the host may hand their seat to a computer
HOMEFELT_TABLE_IDLE_SECS 600 A table with nobody connected for this long is saved and leaves memory; the next join loads it
HOMEFELT_MAX_TABLES 1000 Tables in memory at once. New tables stop at 90% (serverBusy); the rest is kept for loading tables people already sit at, which are refused only at the full count
HOMEFELT_TABLES_PER_HOST 10 Tables one host has that are not finished
HOMEFELT_TABLES_PER_HOUR 10 Tables one host creates in an hour
HOMEFELT_MOVE_LOG_QUEUE 1024 Moves the move log’s queue holds while its writer is behind (Persistence, “The move log”); a move that finds it full is refused with saveBacklog
HOMEFELT_MOVE_LOG_PER_TABLE 64 Moves one table may have waiting in that queue at once, so one table cannot fill it; more are refused with saveBacklog
HOMEFELT_REDEEM_FAILURES_PER_USER, _PER_IP, _GLOBAL 20, 60, 1000 Failed invite redemptions allowed in the last hour per user and per client IP (IPv6 by /64). Past the global count the server refuses only users and IPs with a failure in that hour
HOMEFELT_REDEEM_BACKOFF_AFTER 3 After this many failures in an hour, a user waits 2 seconds before the next attempt, doubling with each failure, up to 5 minutes
HOMEFELT_NEW_ACCOUNT_DAYS, HOMEFELT_REDEEM_FAILURES_PER_NEW_USER 7, 5 An account younger than this many days has this per-user failure budget instead of HOMEFELT_REDEEM_FAILURES_PER_USER
HOMEFELT_REDEEM_FAILURES_TRUSTED 100 The per-user and per-IP budget of someone the host trusts typing a good code for that host’s table or group; the other budgets, the backoff and the global degrade do not apply to it
HOMEFELT_INVITE_CODE_MINUTES 30 A typed code expires this long after its invite is made (the invite and its link last 7 days)
HOMEFELT_JOIN_REQUEST_MINUTES 30 A join request lapses this long after it is made
HOMEFELT_ALERT_FAILURES_PER_HOUR 50 Failed redemptions in the last hour, server-wide, that raise the inviteFailures alert
HOMEFELT_CONNECTIONS_PER_USER 5 WebSocket connections one player may have open at once; more close with 4428
HOMEFELT_HELLOS_PER_MINUTE 30 WebSocket upgrades per client IP (more get HTTP 429) and hellos per player (more close with 4428) per minute
HOMEFELT_API_PER_MINUTE 60 Requests to the table and invite endpoints per client IP per minute (burst of the same size)
HOMEFELT_HELLO_TIMEOUT_SECS 10 Time a new connection has to send its hello
HOMEFELT_MIN_CLIENT_VERSIONS none Each app platform’s minimum date version, ios=2026.12.3,android=2026.12.3 (YYYY.M.D, no leading zeros; decision 0013). A hello from an older app, from another protocol major (protocol in spec/protocol/version.json), or without client is refused with updateRequired (close 4426). A platform left out has no minimum; the web never has one. Raise it the day a required update is published (docs/app-status.md)
HOMEFELT_IDLE_TIMEOUT_SECS 60 After the hello, a connection with no frame for this long is closed (4408). The server pings every third of it, and clients answer pings on their own
HOMEFELT_MAX_CONNECTIONS 200 WebSocket connections open at once across all tables; more get HTTP 503
HOMEFELT_MOVES_PER_SECOND 20 do messages per connection per second (burst of the same size); more get rateLimited
HOMEFELT_METRICS_ADDR 0.0.0.0:9091 Where GET /metrics (Prometheus text) listens; off for none. Must not be the game port: Fly scrapes it privately (fly.toml [metrics]), and the game router has no /metrics
HOMEFELT_ALERT_CONNECTIONS 100 Open connections that raise connectionsHigh, the load the scaling rule counts (decision 0017); 0 turns it off
HOMEFELT_NTFY_TOPIC none The private ntfy topic for push alerts (a secret: fly secrets, never [env]). Unset, no pushes; the log and metrics still record every alert
HOMEFELT_NTFY_URL https://ntfy.sh The ntfy server (https only)
HOMEFELT_NTFY_EVERY_MINS 30 Least time between two pushes of the same alert kind
RUST_LOG info Log filter (tracing-subscriber syntax)

It stops cleanly on Ctrl-C or SIGTERM: every table is saved and its players are closed with 1001. GET /health answers without touching Postgres or the providers.

What Eduardo configures

Where these go in production, and in what order: #133, section 9, and deploy.md “Game server”. Each is a fly secrets set (secrets) or an [env] line in fly.toml (the rest).

  1. The server signing key. Make one and keep it as a secret (it signs every access token; anyone holding it can sign in as anyone): openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out homefelt-token-key.pem. Pass it as HOMEFELT_TOKEN_KEY_FILE (a mounted secret file) or HOMEFELT_TOKEN_KEY. Changing it signs everyone out of the WebSocket within 15 minutes; refresh tokens keep working. The production key lives in 1Password only, never under a repository path: make it outside the repository, store it, delete the local file, and give it to Fly from 1Password (deploy.md, “Game server”, step 3).
  2. Apple. The App ID dev.edsancha.homefelt.canasta (one app per game, docs/architecture.md) with the Sign in with Apple capability. Android signs in with Apple through Apple’s web sign-in, which needs its own Services ID with domain play.homefelt.io and return URL https://play.homefelt.io/auth/apple/android: list it in HOMEFELT_APPLE_SERVICE_IDS (the web’s goes in item 6) and give the app the same id as the Gradle property homefelt.appleServicesId. The return route, web/public/.well-known/assetlinks.json (the release key’s SHA-256) and the app’s switch (OnlineConfig.APPLE_ON_ANDROID, off until then) wait for #285.
  3. Apple key for revocation. Apple Developer → Certificates, Identifiers & Profiles → Keys → a new key with Sign in with Apple, linked to the App ID (its primary App ID). Set HOMEFELT_APPLE_TEAM_ID, HOMEFELT_APPLE_KEY_ID and the downloaded .p8 as HOMEFELT_APPLE_PRIVATE_KEY_FILE. Until then, account deletion skips the revocation App Review asks for and logs a TODO. The same key signs the web Services ID’s client secrets, as long as that Services ID is grouped with this App ID.
  4. Google. In Google Cloud → APIs & Services → Credentials, an OAuth client for iOS (bundle id dev.edsancha.homefelt.canasta), one for Android (package name and signing certificate SHA-1) and one of type Web application, whose id the Android app passes as the server client id. Put the iOS and web client ids in HOMEFELT_GOOGLE_CLIENT_IDS (Android’s tokens carry the web id as aud).
  5. Postgres as DATABASE_URL: Neon’s direct endpoint with sslmode=verify-full in production (sqlx checks the certificate against its built-in Mozilla roots). The server is its only client; no app connects to it.
  6. The web client (#38, #48). Its origin in HOMEFELT_WEB_ORIGINS (for example https://canasta.example), hosted on the same site as the server (api.canasta.example), or the refresh cookie is never sent. For Sign in with Apple on the web, a Services ID (<services-id>) with Sign in with Apple turned on, grouped with the App ID as its primary App ID, the site’s domain (<site-domain>) and its return URL (https://<site-domain>/). Set them as HOMEFELT_APPLE_WEB_SERVICES_ID and HOMEFELT_APPLE_WEB_REDIRECT_URI on the server and build them into the web client as VITE_APPLE_SERVICES_ID and VITE_APPLE_REDIRECT_URI (the same two values); the key from item 3 serves it. For Google, the Web application client id (already in HOMEFELT_GOOGLE_CLIENT_IDS) as VITE_GOOGLE_CLIENT_ID, with the site’s origin among its authorised JavaScript origins. See web/README.md “Online play”.

Sign-in

The server checks Apple’s and Google’s identity tokens itself and then speaks only its own tokens. No other service sees the database.

sequenceDiagram
    participant App
    participant Provider as Apple or Google
    participant Server as canasta-server
    participant DB as Postgres
    App->>App: raw nonce = 32 random bytes#59; hashed = SHA-256 hex
    App->>Provider: sign in with nonce = hashed
    Provider-->>App: identity token (nonce = hashed) [+ Apple authorizationCode]
    App->>Server: POST /auth/apple or /auth/google {idToken, nonce: raw [, authorizationCode]}
    Server->>Provider: JWKS (cached 10 min)
    Server->>Server: RS256, iss, aud, exp, nbf, sub#59; SHA-256(raw) = token nonce
    opt Apple key configured and a code was sent
        Server->>Provider: POST /auth/token (code, client_id = token aud) → Apple refresh token
        Server->>DB: keep it with its client id, for revocation
    end
    Server->>DB: find or create the user by (provider, sub)#59; new refresh token family
    Server-->>App: accessToken (15 min), refreshToken (30 days)
    App->>Server: WebSocket hello {token: accessToken}
    App->>Server: POST /auth/refresh {refreshToken}
    Server->>DB: mark it used, add the next one to its family
    Server-->>App: new accessToken and refreshToken
    App->>Server: DELETE /account (Bearer accessToken)
    Server->>Provider: POST /auth/revoke (each Apple refresh token, with its client id)
    Server->>DB: users.deleted_at, identities and refresh tokens gone

Identity tokens (auth/jwks.rs, auth/providers.rs)

  • One verifier per issuer, each pinned to RS256. The header’s alg is checked, never trusted to pick the check, so an HS256, ES256 or alg: none token is refused.
  • Apple: keys from https://appleid.apple.com/auth/keys, iss https://appleid.apple.com, aud the bundle id or a configured Services ID. Google: keys from https://www.googleapis.com/oauth2/v3/certs, iss https://accounts.google.com or accounts.google.com, aud one of the configured client ids.
  • exp, iss, aud and a non-empty sub are required, and nbf is checked when present. 30 seconds of clock skew are allowed.
  • Nonce. The token’s nonce must be the SHA-256 (lowercase hex) of the raw nonce the app sends with it (16 to 128 visible ASCII characters). A token minted for another sign-in, or another app, is refused.
  • The server uses only sub. It reads no email, so it needs no email_verified check.
  • Keys are cached for 10 minutes. After that, or when a token names an unknown kid (a key rotation), they are refetched, but never within 30 seconds of the last attempt, whether it worked or failed. Fetches are single flight, and the cache lock is never held across the network. If a refetch fails, cached keys keep working; only an empty cache fails, with authUnavailable.
  • JWKS entries of another type, size (RSA under 2048 bits), algorithm or use are skipped one by one.
  • Clients get one generic message per code (invalidToken, tokenExpired, authUnavailable); which check failed is logged.

Our tokens (auth/tokens.rs, sessions.rs)

  • Access token: an ES256 JWT signed with HOMEFELT_TOKEN_KEY; iss and aud homefelt, sub our users.id, iat, exp 15 minutes later, and the key id in the header. The WebSocket hello and DELETE /account take it. It is checked with the same pinning, so a token signed by any other key or algorithm is refused.
  • Refresh token: 32 random bytes in base64url, stored only as its SHA-256 with an expiry, a family id and used_at/revoked_at. Each sign-in starts a family. A refresh marks the token used and returns the next one in the family, with a fresh 30-day expiry. A used token presented again means it was copied: the whole family is revoked and the user signs in again. Two refreshes with one token count as reuse too, so apps must not refresh in parallel.
  • Apple tokens (auth/apple.rs, table apple_tokens). A code is traded as the client id the identity token was issued to (aud): the bundle id for the app, HOMEFELT_APPLE_WEB_SERVICES_ID with redirect_uri HOMEFELT_APPLE_WEB_REDIRECT_URI for the web. The client secret is an ES256 JWT (iss the team, sub that client id, five minutes). Each code is tried once and never retried; a refusal or a network error leaves the sign-in working with no token kept, and logs Apple’s error code only (never the code, token or secret). The code is bound to the sign-in: Apple’s token answer carries an id_token, and the refresh token is kept only when its sub is the sub of the identity token the server just verified and its aud is the client id the code was traded as (iss https://appleid.apple.com). Otherwise it is discarded and only that is logged, so someone holding another user’s unused code cannot tie that user’s Apple token to their own account (and later revoke that user’s Apple link by deleting it). The id_token came straight from Apple over TLS in answer to our authenticated request, so its claims are read without a second signature check. One token is kept per Apple account and client id, so someone on both the app and the web has two.
  • Logout revokes the token’s family. Account deletion revokes each stored Apple token with the client id it was issued to (when the Apple key is configured), then deletes the account as “Persistence” describes: identities and refresh tokens go with everything else, so signing in again creates a new account. Access tokens are not tracked: one issued before a logout or deletion still opens a WebSocket until it expires, at most 15 minutes.
  • Expired refresh tokens are deleted an hour after start-up and every hour after.

Endpoints (http_auth.rs, specified in spec/protocol/server.md “Accounts”): bodies are capped at 8 KiB, identity tokens at 4 KiB, and every route shares one per-IP allowance (HOMEFELT_AUTH_PER_MINUTE; IPv6 clients by /64).

The web client

The browser app (web/README.md “Online play”) signs in and plays like the apps, with two differences the server makes for it (src/web.rs; spec “Browsers”):

  • CORS for listed origins only. HOMEFELT_WEB_ORIGINS lists the web client’s exact origins. A request from one of them gets Access-Control-Allow-Origin with that origin, Access-Control-Allow-Credentials: true and Vary: Origin; a preflight is answered for the methods GET, POST, PATCH, DELETE and the headers content-type, authorization, x-canasta-client, and Retry-After is exposed. Any other origin gets no CORS header at all, so its pages cannot read an answer. With no origins listed (the default) the server sends none, as before.
  • The refresh token in a cookie. A page script must never hold the refresh token (an XSS would steal a 30-day session), so a web request (X-Canasta-Client: web) gets it as an HttpOnly; Secure; SameSite=Strict cookie scoped to /auth, and /auth/refresh and /auth/logout read it from there. The path is /auth, not /auth/refresh, so that logout can revoke the session it names; the sign-in routes ignore it.
  • CSRF. The cookie is ambient: a browser sends it with any request to /auth, from any page. The server uses it only on a web request, which must carry the custom header and an Origin in the list (else 403 forbiddenOrigin). A cross-site form cannot set a header, and a cross-site fetch with one triggers a preflight that unlisted origins fail; SameSite=Strict keeps the cookie off cross-site requests besides. Sign-in checks the same, so another site cannot sign a browser in to the attacker’s account either.
  • Not changed. Access tokens are still returned in the body and sent as Authorization: Bearer, so the table endpoints need no CSRF check (nothing ambient authorises them). WebSockets are not covered by CORS; the hello’s access token admits a connection, so another site’s page cannot use a visitor’s session there.
  • Limits. The cookie cannot take the __Host- prefix (that needs Path=/), so a sibling subdomain under someone else’s control could plant its own homefelt_refresh cookie for the domain; host the server and the site on subdomains only Eduardo controls. And a refresh whose answer is lost leaves the browser with the used token, so its next refresh counts as reuse and signs that browser out (the same for the apps).
  • Apple on the web. The web client sends Sign in with Apple JS’s authorization.code with the identity token. When that token’s aud is HOMEFELT_APPLE_WEB_SERVICES_ID, the server trades the code as that Services ID, with the registered return URL from its own config (never one the page sends), and only for a web request whose Origin is that URL’s origin. A web code from any other request, or a code for another Services ID, is not traded. So deleting an account made only on the web revokes its Apple token with the Services ID, as App Review asks. Without HOMEFELT_APPLE_WEB_SERVICES_ID (or without the Apple key) web codes are ignored, and such an account has nothing to revoke.

Display names

A first sign-in names the account Player; Apple and Google give the server no name it keeps. The player names themselves with PATCH /me (spec “Profile”), and GET /me says whether they have (nameChosen), so a client asks after a sign-in until they do. Every seat and join request carries the same flag (DisplayName in store.rs, read as name_chosen_at is not null), and while it is false clients name the seat by its number in the viewer’s language (“Jugador 2”), never the stored English Player.

  • One set of name rules. db/mod.rs holds them: is_hidden_char (every control and format character, line and paragraph separators, and the blank fillers U+115F, U+1160, U+3164, U+FFA0, U+2800), is_visible_char (a letter, number or symbol) and MAX_MARKS_IN_A_ROW (2), read with unicode-properties after NFC (unicode-normalization; both already came in through sqlx). clean_text repairs by them (group names too), users::clean_name repairs provider and dev names (Player when nothing visible is left), and users::valid_name refuses a typed name that breaks one (400 invalidName), so the player sees the name they get. The profiles check constraints hold the bidi characters and a list of the other hidden ones in Postgres, as a backstop; both are not valid, so rows written before them are not rechecked. Names need not be unique, at a table or anywhere.
  • Renames are limited and targeted. PATCH /me allows one rename every 5 seconds per player (http_profile::renames, a KeyedLimiter with a burst of 1; refused names do not count), then 429 tooManyRenames. Tables::renamed asks the store which tables the player holds a seat at or has a pending join request for (TableStore::tables_of) and sends a Rename to those that are in memory; each updates and sends its table message. No other table hears of it, and tables not in memory read the name when they next open. A table task keeps its players’ names in memory, read when it opens and on each hello.
  • No avatars yet. profiles.avatar_url exists, but nothing sets it and no endpoint returns it: a picture URL that every other player’s client fetches would tell its host their IP addresses, so avatars wait for an upload or a fixed set to choose from.

Tables

A table is made by POST /tables and nowhere else (spec “Tables”): the caller names a game (canasta, the default and the only one so far; anything else is unknownGame, decision 0016), a rule set, a player count and a controller per seat, the server checks them, the host’s limits and the process’s table cap, and saves the table, in its lobby, with the caller as host in seat 0 before answering its id (12 random symbols, 60 bits). Friends get seats only through invite codes, which the host or a seated player makes; redeeming one asks the table’s task for the lowest free human seat. The WebSocket hello then only finds the seat its player holds: an unknown id is noSuchTable and a stranger is notSeated, and neither creates anything (an unknown id does not even leave an empty slot in memory).

Your tables (#78). GET /me/tables (db::tables::of_player) reads the caller’s seats and waiting requests from Postgres, so a table that left memory is listed too. Whose turn it is comes from the table’s task when the table is in memory (Tables::turn, which never loads one), since moves between saves are not in the snapshot; otherwise from the snapshot’s game, read on the server and never sent. Seats carry state and display name only, and a waiting request no seats at all, since the host has not let that person in.

The lobby (#65). A new table waits, its seats shown to everyone (state: human, computer, pending for a waiting join request, open), until the host sends start. Until then tables.started_at is null and the task holds the deal to come only so the snapshot has a game to save: it is never sent, and start deals afresh from a new OS seed with the seats’ controllers as they are then (open seats become computers at the host’s chosen level, or the start is refused with openSeats). The host fills seats with handOver and frees a computer’s with openSeat. A player who sends leave gives the seat up for good: in the lobby it is open again (SaveReason::Left writes it back to open, the only save that frees a person’s seat); once started a Normal computer takes it. Tables::start with OpenSeats::KeepOpen deals with seats left open, for tests and tools that seat players after the deal; the host’s start never does.

The host passes the role on (#65). The task keeps a second clock beside the idle one: while the host is away and someone else is connected, the role passes to the next connected seat in seat order once the host has been gone HOMEFELT_RECONNECT_SECS. A host who leaves for good or deletes their account hands it on at once (to the next connected seat, else the next held one). The table message says so, and the save writes tables.host_id (never a deleted account), so trust and join requests follow the new host. A leave frees the seat and hands the role on in one save (SaveReason::Left); when that save fails, the task puts everything back and answers tableUnavailable. A table left with no host (its host left alone) gives the role to whoever next holds a seat there, saved with the seat. pending seat states go to the host’s copy only, like the requests themselves.

The PRD’s table life (the “Real-time multiplayer” section):

  • A player who drops has 2 minutes to come back, and the game waits. Their seat stays theirs; nothing plays it. The task notes when they left (or when it loaded the table after a restart).
  • After that the host can hand the seat to a computer player. The host’s handOver puts an Easy or Normal computer in the seat as a stand-in, saved as the seat’s stand_in. The seat still belongs to the person: their next hello gives it back and the computer stops. The same action on an empty human seat makes it a computer seat for good, which is how a host fills seats nobody took (“empty seats can be filled by computer players”).
  • A game can be paused and continued another day. The host’s pause stops moves and is saved (tables.paused_at), so it survives restarts and evictions; resume lets play go on.
  • The host can turn beginner aids off (#194). aidsAllowed on POST /tables and the aids host action (lobby only) set tables.aids_allowed; while it is false view.rs leaves the own seat’s meldable out of every node, so no client can show the marks.
  • Closing the app and reopening it returns you to your game: reconnecting is a hello with a fresh access token.

Lifetime. A table task whose table has nobody connected for HOMEFELT_TABLE_IDLE_SECS saves the table, removes itself from the registry and stops; commands that reach it meanwhile get no answer, and their callers (a join, a redemption) open the table again from Postgres, up to three times. A failed save keeps the table in memory and tries again later. Without a store (NoStore, tests only) tables never leave memory, since that is all they have. A task that stopped any other way (a panic included) is noticed the same way, and the table comes back from its last save, never re-dealt and never with fresh seats.

Deleted accounts. An access token outlives DELETE /account by up to 15 minutes, so a hello checks that the account still exists, and the deletion tells every table in memory to make the player’s seat anonymous and close their connections (4401).

What players see of each other. The table message names players by their profile’s display name and marks the viewer’s own seat; it never carries another player’s user id.

Anonymous Supabase users (#27) no longer apply: the server issues its own tokens after Apple or Google sign-in, and every sub is a real users row. A guest (“Guests”) is one too, with no identity.

Guests

Someone without an account opens a host’s invite link and sits down as a guest (#255, spec “Join as a guest”, decision 0018).

  • Redeeming (POST /auth/guest, guests::redeem). One transaction checks the link’s invite (a table’s, usable, the table not finished), takes a per-table advisory lock, counts the table’s live guests against HOMEFELT_GUESTS_PER_TABLE, counts the IP in sign_ups (the sign-up budget), and inserts the users row with guest_table and a profile whose name is chosen. Then the table’s task seats them with the token (Via::Token), as for anyone opening a link. A guest that gets no seat is deleted at once (users::delete_account). The answer is a sign-in’s pair.
  • Scope. The access token’s guest claim names the table (auth/tokens.rs). Every table and invite route and /me/tables refuse it (http_tables::caller, 403 guestNotAllowed); /me and DELETE /account take it. Redemption also refuses a guest by the row (users::lock_account), and the hello reads the row (TableStore::standing): another table is guestNotAllowed (4403), an ended session guestEnded (4410). A refresh keeps the claim.
  • Seats and the host. The table message marks a guest’s seat (guest), read with the names (DisplayName.guest). The host role never passes to a guest (Table::next_host). The host’s remove ends the guest’s session (TableStore::end_guest), then frees the seat as a leave does (SaveReason::Left), and closes the guest’s connection with 4410.
  • The session ends (guests::end_session: users.guest_ended_at, refresh tokens revoked) when the host removes them, they leave or log out, the game ends (db::tables::record_game ends every guest of the table in the save’s transaction), the last player with an account leaves a lobby (Table::end_lonely_guests: their seats open, their connections close with 4410), or the hourly job finds all their refresh tokens lapsed. A table never seats, joins or opens without reading who is a guest (a failed name lookup is tableUnavailable), so a guest never hosts by accident. A guest still connected at the end of the game sees it; their next hello is refused.
  • Retention. The hourly job (guests::prune, with the refresh token prune) deletes a guest HOMEFELT_GUEST_DAYS after the session ended, unless it has an identity, through users::delete_account (name gone, seats deleted, results kept nameless), and the tables in memory forget them. A guest who just stops playing lapses 30 days after their last refresh, so an abandoned table’s guests are gone within about 60 days. A guest who gets no seat is deleted at once and gives back its sign-up. #262 keeps a guest by adding an identity and clearing guest_table.
  • Not yet. There is no rematch at a table: a guest keeps the seat across the hands of a game, and a later rematch must keep its table open (not finished) for its guests to stay.

Invites

An invite to a group or a table has two secrets (spec “Invite to a table”, “Redeem a code”). Chosen in #66 (measures 1, 2, 5 and 6 of the research there) so that guessing codes stops paying without ever locking the family out:

  • Link token (measure 2). 16 bytes from aws_lc_rs::rand, base64url, stored only as its SHA-256 (invites.token_hash, unique), used once (token_used_at). It seats or joins at once, whoever opens it, and never touches the failure budgets. It lives as long as the invite, 7 days.
  • Typed code. The 6-symbol code is the fallback and expires after HOMEFELT_INVITE_CODE_MINUTES (invites.code_expires_at). Few codes are live at any moment, so a guess almost never hits: with 10 live codes and 1,000 guesses an hour (the global budget), about one hit in 11 years.
  • Host approval (measure 1). A good code typed by someone the host does not trust seats nobody: it makes a join_requests row (pending, lapsing after HOMEFELT_JOIN_REQUEST_MINUTES), which the table’s task shows to the host in the table message (name and account age) and closes when the host sends approve or deny. Approving seats the person through the same transaction as an invite (PgStore::claim with Via::Approved): the request must still be pending and the invite usable, and the seat, the invite’s use and the request’s approved are written together. Group requests have repository functions only (invites::group_requests, decide_group_request), like the rest of groups. The requester polls GET /invites/requests/{id}, and may withdraw it with DELETE (invites::withdraw, status withdrawn), which tells the table’s task to read its requests again; the row lock it takes orders it with an approval, so only one of the two wins. At most 10 wait per table or group; one person has one request per table or group, and typing again returns it.
  • Trust (measure 5). A person trusts the host when they share a group with them (for a group code: with its owner or the code’s creator). They skip approval, and typing a good code for that host they have a budget of HOMEFELT_REDEEM_FAILURES_TRUSTED per user and per IP instead of the usual ones, so a stranger guessing from the family’s home IP cannot lock them out. The check looks the code up before deciding, but refuses everyone else exactly as before, so a refused stranger learns nothing about the code. A refused attempt is recorded as a failure too (while the person has fewer than the trusted budget), so nobody gets free guesses while refused: without that, a member of a big group could probe codes for free and learn which ones belong to its hosts. A code’s creator counts for trust, and decides group requests, only while still in the group. Deleting an account keeps its failures (nameless, with their IP) until the daily prune, so it does not reset the IP and server-wide budgets. Accounts younger than HOMEFELT_NEW_ACCOUNT_DAYS have a smaller budget (HOMEFELT_REDEEM_FAILURES_PER_NEW_USER), and one IP makes at most HOMEFELT_SIGN_UPS_PER_IP accounts an hour (sign_ups, counted and inserted under a per-IP advisory lock in the sign-in transaction), so farming Apple or Google accounts does not multiply the per-user budgets.
  • Alerts (measure 6, src/alerts.rs). A WARN log line with alert="inviteFailures" while the last hour’s failures are at or over HOMEFELT_ALERT_FAILURES_PER_HOUR (at most once a minute), and one with alert="untrustedCode" for each join request a typed code makes (user, table or group, account age, IP key; never the code or token). The process counts both (alerts::counts()); there is no metrics endpoint to expose them on yet, so the log is where an alert rule matches.

What this adds to review (the attack surface): the token lookup (token_hash, and a token that is not 22 base64url characters is refused before the database); the join request lifecycle (who may approve: the host’s connection for a table, the owner or the code’s creator for a group; an approval rechecks request and invite in the seating transaction); the trusted budget (the only way past a spent budget, and only for good codes to a host the person shares a group with); the requests list in the table message, sent to the host’s copy only (display names and account ages of people asking); GET and DELETE /invites/requests/{id}, answered only to the requester (404 to anyone else, so ids are not probed); GET /me/tables (below); and the sign_ups IP records, deleted after a day with failed redemptions.

Local development

A default build has no way to sign in without Apple or Google. For running the server and the apps on one machine, the dev-auth cargo feature adds POST /auth/dev {"name":"alice"}: it finds or creates the user with identity ("dev", name) (names are [a-z0-9-]{1,32}), names a new one after it (“abuela” → “Abuela”), and answers the same token pair as a real sign-in (or, for a web request, the cookie). It is served only when the binary is built with the feature and HOMEFELT_DEV_AUTH=1, answers only requests from a loopback address with no X-Forwarded-For or Forwarded header, and logs a warning at start-up. CI checks that a default release binary does not contain the route.

bin/setup and bin/dev set this up and run it: Postgres, homefelt_dev, a local P-256 key, HOMEFELT_DEV_AUTH=1, HOST=127.0.0.1 and the dev-auth build, plus seeded players and a table to join. See development.md.

Tests

cargo test -p canasta-server runs everything offline: freshly generated RSA and EC keys, local JWKS endpoints standing in for Apple and Google, a local Apple token API, and servers on free ports. The Apple stand-in is as strict as Apple: a code trades once, only as the client id (and return URL) it was issued to, and a token revokes only with its own client id. Nothing leaves 127.0.0.1. Tests that need Postgres read DATABASE_URL, make a schema of their own and drop it at the end; without DATABASE_URL they print a skip note and pass, except in CI (CI set), where they fail. CI runs a postgres:17 service; see “Persistence” for running them locally. --features dev-auth adds the dev sign-in tests.

Limits

Each connection and the process as a whole are bounded, so one client cannot exhaust the server:

  • Messages and frames from a client are at most 8 KiB. A larger one ends the connection.
  • An input names at most 108 cards across cards and melds (every card of a two-deck table); more is invalidInput before the engine sees it.
  • Each connection’s outbox holds 64 messages. A client that reads too slowly to drain it is closed (4429) instead of making the server buffer without limit.
  • Moves per second, idle time and open connections are capped by the settings above.
  • Tables: at most HOMEFELT_MAX_TABLES in memory (idle ones leave after HOMEFELT_TABLE_IDLE_SECS), new ones only up to 90% of it, with the count and the slot’s reservation under one lock; and per host at most HOMEFELT_TABLES_PER_HOST that are not finished and HOMEFELT_TABLES_PER_HOUR created in an hour. The host’s count and the insert run in one transaction under a per-host lock, so parallel requests cannot overrun them. A table is loaded only for someone with a seat there, and each player has at most HOMEFELT_CONNECTIONS_PER_USER connections and HOMEFELT_HELLOS_PER_MINUTE hellos a minute, so a few accounts cannot fill memory with tables.
  • Invites: 20 open invites per group or table, 20 live invites per person across all of them, typed codes that expire in 30 minutes, 10 join requests waiting per table or group, 10 new accounts (and guests) per IP an hour, HOMEFELT_GUESTS_PER_TABLE live guests per table, and the failure budgets for typed redemptions (above): per user (smaller for new accounts) and per IP, a per-user backoff that doubles with each failure, and a global count (“Invites” has the trusted budget). Every live code is one of about 10⁹. Past the global count the server degrades rather than stops: it refuses every user and IP with a failure in the last hour (logged as a warning), while people who have not failed still redeem. Guessing on past it then costs a fresh account and a fresh IP per guess. Failures (with their IP) are deleted after a day.
  • The table endpoints have their own per-IP allowance (HOMEFELT_API_PER_MINUTE).
  • Errors sent to clients carry generic messages for unreadable JSON, refused tokens and JWKS failures; the detail goes to the log. Tokens never appear in logs (ClientMessage‘s Debug redacts the hello’s token; the signing keys’ Debug is redacted too).

tests/providers.rs covers the identity token checks against local JWKS endpoints, tests/accounts.rs the sign-in endpoints and sessions, tests/websocket.rs the whole game protocol (tables created over HTTP, host actions, closes) against a real server on a free port, tests/tables_api.rs the table and invite endpoints with Postgres, tests/guests.rs guest seats end to end with Postgres, and tests/store.rs the table task’s saves, seats and eviction against an in-memory store.

Persistence

Plain Postgres (decided 18 November 2026). Only the server connects to it; no app ever does, so the schema has no row level security and no grants, and every rule below is enforced by the server’s repository functions. Queries are plain sqlx::query with bound parameters (no query! macros), so building needs no database. In production the database is a Neon project in AWS US East, reached on its direct endpoint over TLS with sslmode=verify-full (deploy.md, “Game server”).

erDiagram
    users ||--o| profiles : has
    users ||--o{ group_members : "belongs to"
    groups ||--o{ group_members : has
    groups ||--o{ removals : remembers
    users ||--o{ friendships : "user_a / user_b"
    groups |o--o{ tables : "plays at"
    users |o--o{ tables : hosts
    tables ||--|{ seats : has
    users |o--o{ seats : "sits in"
    tables ||--o| game_snapshots : "saved as"
    tables ||--o{ table_moves : "logs"
    tables ||--o{ hand_results : scores
    tables ||--o| game_results : ends
    groups |o--o{ invites : "invites to"
    tables |o--o{ invites : "invites to"
    invites |o--o{ invite_redemptions : "redeemed by"
    users ||--o{ invite_redemptions : tries
    invites ||--o{ join_requests : "asked with"
    users ||--o{ join_requests : asks
Table Holds
users An id, created_at, deleted_at, and for a guest guest_table (the one table) and guest_ended_at (“Guests”). Sign-in inserts only the id, so every other column has a default. Its identities and refresh_tokens come in the later 20261119000000_sessions.sql (see “Migrations” below)
profiles Display name (1 to 40 characters, trimmed, no control or bidirectional formatting characters), an https avatar URL (nothing sets one yet), and name_chosen_at, when the player last named themselves (PATCH /me; null while the name is the server’s). Sign-in creates it as Player on a first sign-in
groups, group_members A family or club; exactly one owner while it has members
removals People an owner removed from a group; an invite cannot bring them back
friendships One row per pair, user_a < user_b
tables, seats A table (its id is the one in the WebSocket URL), its host (who passes the role on), rules, status, paused_at (the host paused it), aids_allowed (false once the host turned beginner aids off) and started_at (null while it waits in its lobby); each seat’s side and who sits there: open, human (a user, with a computer stand_in while the host has handed the seat over), computer (with level easy or normal) or deleted
game_snapshots The whole game (rules, position, every hand and the stock) and the shuffle’s seed and stream as numeric(20, 0) (a u64 does not fit a bigint), and in saved the same game as a saved game (saved_game::save_json), with the hand’s move log and every seat’s bot random source. Never sent to a client
table_moves The move log: each move a person made since the table’s last save (hand_number, sequence, seat, action, input), keyed by (table_id, sequence), appended by the move log’s writer and deleted by the save that covers it. game_snapshots.moves_logged is the last sequence a snapshot covers, and game_snapshots.restore_seats the seats a restore has not told yet
hand_results, game_results Each hand’s totals per side with its whole score sheet row, and the game’s winning sides (all that tie) and final scores
invites, invite_redemptions Invites to a group or a table: the link token’s hash and when it was used, the 6-character code and its own expiry; every redemption that joined, seated, or failed (a failure with the client’s IP, for a day)
join_requests A typed code from someone the host does not trust: pending until the host approves or denies it, the requester withdraws it, or it lapses
sign_ups When each client IP (IPv6 by /64) made an account, for the sign-up limit; deleted after a day

What is saved when. A table task saves the whole table (its row, its seats and its snapshot with the hand number and the score sheet so far, in one transaction) when it is created (with the host’s limits checked in the same transaction), when a player takes a seat (with the invite’s use, in the same transaction) or comes back to a seat a computer stood in for, when a hand ends (handOver), when the host starts it, when a player leaves for good, when the next hand is dealt, when the host pauses, continues, hands a seat over or opens one, when the host role passes on, when the last connected player leaves (the table is paused), when it leaves memory, and on a graceful shutdown. A save that finds the hand over also records its score in hand_results (once per hand), and when the game is over its winners and final scores in game_results, and marks the table finished. Moves in between are kept in the move log (below), so a crash loses none. Computer seats are saved as computer seats with their level, so a restored table keeps its computer players whatever HOMEFELT_CONTROLLERS says now. The snapshot’s saved game holds the hand’s move log and the bots’ random sources as they are, so a restored table’s computer players play on exactly as they would have without the restart (#54; a_restored_table_replays_its_computer_players_exactly in tests/store.rs and tests/db/store.rs). A snapshot from before saved games (saved null) restores with an empty log and the sources made afresh for the hand; a saved game that does not load makes the table tableUnavailable. Seat controllers still come from seats. A table is restored the first time someone joins it (or redeems an invite to it) after a restart or an eviction, not at start-up, so idle tables cost nothing. A table row without a snapshot was never dealt and cannot be joined. Loading happens outside the lock that finds a table, so a slow load holds up only joins at that table, and they share one load. If the database cannot say whether a table exists, the join is refused (tableUnavailable) rather than dealing over a saved game. A failed save is logged and play goes on; the next save writes everything. The task holds the store behind TableStore, so tests and a server without DATABASE_URL run on NoStore.

The move log (#253; spec/protocol/server.md “Moves”). Every move a person makes is queued, not written, before anyone is answered: one bounded queue per process (HOMEFELT_MOVE_LOG_QUEUE, 1024 moves) that one writer (src/move_log.rs) appends to table_moves in batches of up to 64, oldest first. A turn never waits for Postgres, so a Neon compute waking up slows only the log (Eduardo’s decision, 26 November 2026). The price is a small window: a crash between a move’s answer and its write loses that move, which is a few milliseconds’ worth while Postgres keeps up.

  • Refusals. A move is refused with saveBacklog (and changes nothing) when the queue is full, when its table already has HOMEFELT_MOVE_LOG_PER_TABLE (64) moves waiting (so one busy table cannot fill the queue for everyone), or when the table’s last save failed and cannot be made again yet. A change such as a pause, a seat left or handed over, or a stand-in returning a seat is not in the log, so moves wait until a save records it; each refused move tries the save again first.
  • Writing. A failed write is tried again with a growing wait (from 250 ms up to 30 s) and never dropped, and raises the moveLogBehind alert (logged at most once a minute). Rows are keyed by (table_id, sequence); a row already there with the same move (a retry after an unknown result) is left alone, and a different move under the same number keeps the first and raises moveLogConflict. What is logged is the decoded move written out again (move_log::canonical), never the client’s own JSON. The computer seats’ moves are not logged: the save holds their random sources, so replaying the people’s moves plays theirs again exactly.
  • Saves. Each save records the last sequence it covers (game_snapshots.moves_logged) and deletes the rows up to it in the same transaction; a load deletes any that a late write put back.
  • Loading. Before a load, the writer writes everything this process queued, for up to 5 seconds (else the load is refused with tableUnavailable), so a reopened table numbers its moves on from the last one. Then the snapshot, then the computers due to act in it play (as they did live: a seat left to a computer plays before the next person’s move), then the rows after the snapshot are replayed in order (game_screen::update, the same path as a live move). A table that replayed anything is saved at once (SaveReason::Restored), which covers the log again, and the table message tells each held seat once that it was restored; the seats still to tell are kept in game_snapshots.restore_seats.
  • A damaged table. A gap in the sequence or a row the game refuses stops the load with tableDamaged (final, close 4403) and raises the tableDamaged alert with the reason. To repair it, look at the rows after the snapshot (select * from table_moves where table_id = $1 and sequence > (select moves_logged from game_snapshots where table_id = $1) order by sequence), and if they cannot be saved, delete them (delete from table_moves where table_id = $1 and sequence > …): the table then loads at its last save, without those moves.
  • Stopping. A graceful shutdown saves every table (which covers the log) and then waits up to 5 seconds for the writer to write what is still queued.

Tests: a_crash_mid_hand_loses_no_move_and_the_seats_are_told_once, a_seat_left_to_a_computer_before_a_crash_replays_exactly, a_failed_save_holds_moves_until_a_save_succeeds, a_full_move_log_refuses_the_move_until_it_drains, a_log_that_does_not_replay_is_refused_for_good and seats_a_restore_did_not_tell_are_told_after_another_restart in tests/store.rs; the queue’s flush and per-table share and the canonical form in src/move_log.rs; and logged_moves_survive_a_crash_and_the_save_after_the_replay_clears_them and a_move_written_twice_keeps_the_first_and_a_retry_is_harmless in tests/db/store.rs.

Migrations. 20261118120000_initial_schema.sql (this schema) runs before 20261119000000_sessions.sql (sign-in), although sign-in was written first; 20261120000000_table_access.sql adds tables.paused_at, seats.stand_in and the failures’ ip; 20261121000000_invite_defences.sql adds the invites’ token and code expiry, join_requests and sign_ups; 20261122000000_lobby.sql adds tables.started_at (tables from before were started when they were made). 20261128090000_apple_tokens.sql moves Apple refresh tokens from identities.provider_refresh_token to apple_tokens, one per Apple account and client id (those kept before were all the bundle id’s). 20261129000000_withdrawn_requests.sql lets a join request close as withdrawn. 20261130000000_aids_allowed.sql adds tables.aids_allowed, true for the tables from before. 20261201000000_table_game.sql adds tables.game, and 20261202000000_move_log.sql adds table_moves, game_snapshots.moves_logged (0 for the snapshots from before) and game_snapshots.restore_seats. No environment has ever run the sessions migration on its own, so the order is safe to keep; its create table if not exists users matches this users and does nothing after it. A test runs both from an empty schema. Once a database is deployed, migrations are only ever added, never edited.

Rules the server enforces, carried over from the closed Supabase design (#26):

  • Invite codes are 6 symbols from 23456789ABCDEFGHJKLMNPQRSTUVWXYZ (no 0, O, 1 or I), drawn without bias from the OS’s random source, about 10⁹ codes. A code expires 30 minutes after it is made, its invite (and the invite’s single-use link token) after 7 days, and an invite may cap its uses.
  • Any member invites to a group; the host or a seated player invites to a table. At most 20 open (unrevoked, unexpired) invites per group or table. The creator, the group owner or the table host revokes.
  • A user may fail to redeem a typed code 20 times an hour (5 for an account younger than 7 days; no such code, revoked, expired, used up), an IP 60 times and the whole server 1,000 times (configurable). Tokens are never counted. Redeeming returns a status rather than failing, so the failure is always recorded, and one user’s, and one IP’s, redemptions run one at a time, so parallel guesses cannot overrun the limit. A person has at most 20 live codes.
  • A table code is checked in Postgres (budgets, revoked, expired), then the table’s task picks the seat and saves it with the use; the invite’s row lock in that transaction orders its last use.
  • A deleted account joins nothing: redeeming and taking a seat lock the user’s row and refuse a deleted one, so an access token that has not expired yet adds nothing after DELETE /account, and a redemption racing the deletion either finishes first (and is undone) or is refused.
  • Joining a group happens only through an invite. Someone the owner removed gets removed; someone who left on their own can come back.
  • One seat per person per table (a unique index), and two people redeeming the last seat at once get one seated and one full: the table task takes them one at a time.
  • Friendships only between people who share a group or have sat at the same table; either ends it.
  • A person owns at most 50 groups.

Deleting an account (DELETE /account, db::users::delete_account) happens in one transaction: the profile, sign-in identities, refresh tokens, friendships, join requests and removals go; redemptions lose their user (failures keep their IP until the daily prune, so the IP and server-wide budgets still count them; failures without an IP go), and successful ones keep counting, so a used-up invite stays used up; every membership ends as if they left (an owner’s group passes to its longest-standing member who has not deleted their account, a group left empty is deleted); their open invites are revoked and every invite, group and table forgets its creator or host; their seats become deleted, so results stay with nobody named. The users row stays with deleted_at, so an old result never points at a new person. A running table that still holds the deleted id cannot name them again: saves never seat a deleted user.

Tests. tests/db/ gives each test its own schema in DATABASE_URL’s database, migrated from scratch, and drops it afterwards. Without DATABASE_URL those tests pass without running and say so on stderr; with CI set and no DATABASE_URL they fail, so CI always runs them (the Rust job has a postgres:17 service). Locally, bin/dev test runs them against the homefelt_test database bin/setup makes (development.md); any Postgres works with DATABASE_URL=… cargo test -p canasta-server.

tests/store.rs checks when a table task saves, against an in-memory store.

Postgres connection findings (from the spike)

The spike looked at sqlx with Supabase’s connection options, when Supabase was the plan. The lessons hold for any pooler in front of Postgres.

Findings

  1. Supabase offers three ways in. A direct connection (port 5432) is the one it recommends for “persistent backends, such as virtual machines and long-running containers”, but it is IPv6 only unless the project buys the IPv4 add-on. Supavisor session mode (port 5432 on the pooler host) is the IPv4 alternative for the same kind of server. Supavisor transaction mode (port 6543) is meant for serverless and edge functions that open many short-lived connections. [1]
  2. Transaction mode does not support prepared statements on the shared pooler; Supabase tells you to turn them off in the driver. Session mode and direct connections support them. [1][2]
  3. sqlx prepares every query at the protocol level. By default each statement is prepared once and kept in a per-connection cache (statement_cache_capacity, default 100). .persistent(false) closes a statement after it runs, but it is still prepared. [3][4]
  4. That is why sqlx breaks on Supavisor transaction mode: a statement prepared on one backend connection is missing, or already exists, on the next. The open Supavisor issue on named prepared statements reports exactly this for sqlx, tokio-postgres and pgx (prepared statement "…" does not exist / already exists). A June 2026 Supavisor commit touches prepared statement handling, but the issue is still open. [5]

Recommendation

  • Run the server as one long-lived process and connect sqlx to the direct connection if the host has IPv6, otherwise to Supavisor session mode. Do not use transaction mode with sqlx.
  • Keep the pool small (max_connections of 2 to 5). One game server needs few connections, and session mode holds one backend connection per client connection.
  • Write whole game states (the GameState JSON plus seed, stream and seats) in one row per table. Moves are already serialised by the table task, so a single writer per table needs no row locks.
  • Use sqlx::query with bound parameters. The compile-time query! macros need a database at build time.

Sources

  1. Supabase, “Connect to your database”: https://supabase.com/docs/guides/database/connecting-to-postgres
  2. Supabase, “Disabling prepared statements”: https://supabase.com/docs/guides/troubleshooting/disabling-prepared-statements-qL8lEL
  3. sqlx PgConnectOptions::statement_cache_capacity: https://docs.rs/sqlx/latest/sqlx/postgres/struct.PgConnectOptions.html
  4. sqlx Query::persistent: https://docs.rs/sqlx/latest/sqlx/query/struct.Query.html
  5. supabase/supavisor#239, “Named prepared statements not working”: https://github.com/supabase/supavisor/issues/239

Checked 2026-11-18.

Not built yet

  • HTTP endpoints for profiles, groups, group invites and friends, and for reading a table or a user’s tables: the repository functions exist, the routes do not yet. DELETE /account runs the full account deletion. Table invites, redemption of any code and revoking are served.
  • Giving a seat to another person (beyond a computer stand-in, or leaving it to a computer) is not designed yet. Seat 0 always deals the first hand.
  • 8-character codes (#27 suggests them): codes stay 6 symbols, as the PRD says, with the defences in “Invites”. The host’s name as a second factor and proof-of-work after failures (#66 measures 3 and 4) wait unless the alerts show guessing.
  • Spectators and turn timers. Deploys run by hand (deploy.md, “Game server”).

The protocol is no longer a draft: spec/online pins the client half, and bin/test online-server plays a hand against a local server through the web’s machines (#257).