# Add Arena54 sign-in and saves to this project

Goal: Let players of this game sign in with Arena54 and keep their progress, with no server of our own.

You are a coding agent working inside my project. Do the work. Do not ask me anything you can find out by reading the project. Do not invent an endpoint, a field or an error code that is not written below.

## 1. Look at the project first

- Find the framework and language, how the project is run and tested, and where the game starts, where its state lives (level, coins, settings) and where a round or a session ends.
- Find where the project keeps its public configuration.
- This is a plain web project: use `fetch`, and add no framework and no build step.
- The page must be served from an address registered for the game (https, or http://localhost while building). Opening the file from disk will be refused with `origin_not_allowed`.
- Tell me in two or three lines what you found and what you will change, then carry on.

## 2. The contract

Base URL: `https://developers.arena54.com/api/v1` (called $BASE below).

Every answer is JSON in one envelope:

```json
{ "success": true, "data": …, "meta": { "request_id": "req_…", "mode": "test" } }
{ "success": false, "error": { "code": "…", "message": "…" }, "meta": { "request_id": "req_…", "mode": "test" } }
```

Branch on `error.code`. Show `error.message` to a person; it is written for them. Log `meta.request_id` with any failure.

Calls:

- POST /play/test-token: A sample player. Test keys only.
    data: { "token": "a54p_…", "player": { "id": "pl_test_player", "name": "Test Player" } }
- GET /play/me: Who the token is: id, name, when it expires.
    data: { "id": "pl_…", "name": "Ada", "game": { "slug": "…", "name": "…" }, "expires_at": "2026-10-12T21:00:00.000Z" }
- DELETE /play/me: The player erases themselves from this game: saves, scores, achievements, items and the connection.
    data: { "player": "pl_…", "removed": { "saves": 3, "scores": 1, "achievements": 2, "items": 0, "connection": 1, "ledger_accounts_unlinked": 0 } }   (the player's token as X-Arena54-Player; erases them from this game, so sign them out after)
- GET /play/visit: For the game being visited: the player’s open visit and where they came from, or null.
    data: { "visit": "uuid", "from": { "slug": "home-game", "name": "Home Game" }, "brought_items": true, "agreed_at": "…", "arrived_at": "…" } | null
- POST /play/visit/end: For the game being visited: say the visit is over.
    data: { "ended": true }   (no request body)
- GET /play/visits: For the home game: where this player went, and whether each visit is over.
    data: [{ "visit": "uuid", "to": "other-game", "state": "started" | "arrived" | "ended" | "expired", "started_at": "…", "arrived_at": "…" | null, "ended_at": "…" | null }]
- POST /play/beat: Say the player is still playing. Call it about once a minute. Arena54 counts the time by its own clock.
    data: { "counted": true, "seconds": 5400, "sessions": 3 }   (no request body; a test key answers { "counted": false, "test": true })
- GET /play/playtime: How long this player has played this game, and when they last played.
    data: { "seconds": 5400, "sessions": 3, "last_played_at": "…" | null }
- GET /play/saves: The player’s saved values: names and sizes.
    data: [{ "key": "slot-1", "bytes": 24, "updated_at": "…" }]
- GET /play/saves/{key}: One value.
    data: { "key": "slot-1", "value": <what you saved>, "bytes": 24, "updated_at": "…" }
- PUT /play/saves/{key}: Write one value. Any JSON.
    data: { "key": "slot-1", "bytes": 24 }   (the request body is the value itself, any JSON)
- DELETE /play/saves/{key}: Remove one value.
    data: { "key": "slot-1", "deleted": true }

Keys and headers:

- The game’s PUBLISHABLE key (starts `a54_pub_test_` or `a54_pub_live_`) may sit in the page. It works only from the addresses registered for the game.
- Send `Authorization: Bearer <publishable key>` on every call, and `X-Arena54-Player: <token>` on every call that concerns a player.
- Never put a secret key in a page or a game build. A secret key starts `a54_test_` or `a54_live_`, with no `pub_`.
- Test and live data are kept apart. A test key gets a sample player from POST /play/test-token; a live key needs a real sign-in.
- The key’s calls a minute are shared by every player of the game (60 on the free plan), and each player has 120 a minute. Call on load and when a round ends, never on every frame.
- A 429 carries `Retry-After` in seconds, and a page can read it.
- `error.message` is sometimes written for you, the developer. For `invalid_player`, `origin_not_allowed` and `module_not_enabled`, show the player your own words.

Refusals:

- 409 not_for_sale: The item has no price.
- 409 price_out_of_range: The item’s price is outside the range Arena54 sells at.
- 400 bad_redirect: A purchase was started without a return address inside one the game registered.
- 502 provider_unavailable: The payment provider could not open a checkout. Nothing was charged.
- 503 payments_not_open: A real purchase was asked for while real payments are closed. Nothing was charged. Test purchases still work.
- 429 too_soon: An economy report arrived sooner after the last one than is allowed. Retry-After says how long to wait.
- 400 bad_transfer: A transfer was sent without the other game’s id or without a reference of your own.
- 409 no_route: No route both makers agreed takes that item to that game.
- 409 cannot_transfer: The player cannot move that item there: they do not own it, already own its match there, do not play that game, or have not turned on sharing. One answer for all four, so a game cannot learn where its player plays.
- 409 ref_reused: The transfer reference was already used for a different move.
- 429 transfer_limit: The player has moved as many items out of this game as one day allows.
- 401 missing_key: No Authorization header, or what follows “Bearer” is not shaped like a game’s key.
- 401 invalid_key: The key is shaped like one but is unknown or revoked, or its game is gone.
- 403 origin_not_allowed: The page’s address is not one the game registered.
- 403 module_not_enabled: The module is not ticked for this game in the dashboard.
- 503 module_off: Arena54 has switched the module off for now.
- 401 invalid_player: No player token, an expired or altered one, or one for another game or mode.
- 401 player_revoked: The player disconnected the game. Send them to sign in again.
- 403 test_only: A sample player was asked for with a live key.
- 400 bad_key: A save’s name is not 1 to 64 letters, digits, dots, dashes or underscores.
- 400 bad_json: The body is not JSON.
- 413 too_large: The value is over the plan’s size for one save.
- 409 too_many: The player already holds the plan’s number of saves. Replacing one still works.
- 404 not_found: No such save, board, achievement, item or address.
- 429 rate_limited: Too many calls this minute, for the key or for one player. Retry-After says how long to wait.

## 3. Do this, in order

1. Put the publishable key and the game’s slug in the project’s public config (for example ARENA54_PUBLISHABLE_KEY and ARENA54_GAME). A publishable key may sit in a page.
2. Write one small client: `arena(method, path, body)` sends `Authorization: Bearer <publishable key>`, a JSON body with `Content-Type: application/json` when there is one, and `X-Arena54-Player: <token>` when there is one. It returns `data` on success and throws an error carrying `error.code`, `error.message` and the `Retry-After` header on failure.
3. With the TEST key first: on start, call POST /play/test-token and keep `token`. This is one sample player shared by everyone using the test key; nobody signs in, and what it saves stays until you delete it.
4. Only if I ask for play time to be counted: once a minute while the game is running and its tab is in front, call POST /play/beat with no body. Never send how long the player played: Arena54 counts by its own clock. Stop calling when the game is paused or hidden. To show the player their time, call GET /play/playtime.
5. Load: GET /play/saves/slot-1. A 404 `not_found` means a new player: start fresh. Otherwise restore the game’s state from `value`.
6. Save: PUT /play/saves/slot-1 with the state as the body, when a round ends and at most once every few seconds. Keep the state small.
7. Then real players, for when the key is a LIVE one: a “Sign in with Arena54” control sends the browser to `https://arena54.com/play/authorize?game=<slug>&redirect=<this page’s address, URL-encoded>&state=<a random string you keep>`. On return the address ends `#a54_token=a54p_…&state=…`: check `state` matches, keep the token, and remove the fragment from the address bar with history.replaceState. Keep `state` in sessionStorage so it survives the trip. `redirect` must be inside an address registered for the game. A player who declines is simply not sent back. If the page is framed (`window.top !== window`, as in the Arcade or a city), never navigate the frame: Arena54, Google and X refuse to be framed and the frame goes dead. Open the same address with `window.open` instead; when that window comes back with the fragment and has `window.opener`, it posts the fragment to the opener with `postMessage(…, location.origin)` and closes, and the game checks `state` as above. If `window.open` returns null, show “Open the game in a new tab to sign in” with a link to the page.
8. On 401 `invalid_player` or `player_revoked`, drop the token and show the sign-in control again, in your own words to the player. A token lasts two hours. With a test key, ask for the sample player again in place of signing in.

## 4. Prove it works

Set `BASE=https://developers.arena54.com/api/v1` and `KEY` to the game’s test key. If I have not given you a key, ask me for a TEST key once, and for nothing else.

- Run: `curl -X POST "$BASE/play/test-token" -H "Authorization: Bearer $KEY"`. Expect HTTP 200 and a `token` starting `a54p_`.
- Run the first check again with `-H "Origin: <the address your page is served from>"`. Expect 200. A 403 `origin_not_allowed` means that address is not registered for the game in the Arena54 dashboard: tell me, and I will add it.
- With that token as $TOKEN: `curl -X PUT "$BASE/play/saves/slot-1" -H "Authorization: Bearer $KEY" -H "X-Arena54-Player: $TOKEN" -d '{"level":3}'` answers 200 with `"key": "slot-1"`, and a GET of the same address returns `"value": {"level": 3}`.
- In the game: play, reload the page, and the progress is still there.

Show me the output of each check.

## 5. Rules you must not break

- Never trust the page for anything of value. A player can change what a page sends, so a save, a score or a badge reported by a page is a claim. Do not unlock paid content, currency or prizes from it.
- No secret key in a page or a game build.
- On 401 `invalid_player` or `player_revoked`, drop the token and offer sign-in again. Do not loop.
- On 403, show the message and stop; retrying will not help.
- On 429, wait for `Retry-After` seconds. Never retry in a tight loop.
- On 503 `module_off`, keep the game playable without the feature.
- Keep the token in memory, or in sessionStorage so a reload keeps the player signed in. Never in localStorage, a save, a URL you share, or a log.

## 6. Done when

- Progress survives a reload with the test key.
- The sign-in control builds the authorize address and the return handler reads the token and clears the fragment.
- No secret key is anywhere in the project.
- Every refusal listed in the contract shows a plain message or a sensible fallback.

Then give me a short list of the files you changed and anything I must do by hand (for example: register this page’s address for the game in the Arena54 dashboard).

For a person, not needed for this task: https://developers.arena54.com/docs/reference · This prompt: https://developers.arena54.com/prompts/hosted-saves.web.md
