# Collegamento degli account passo dopo passo

Usa questa guida quando il tuo gioco ha account propri e un server proprio, e vuoi che un giocatore ZokoGames connesso finisca nell'account di gioco giusto a ogni avvio. È la versione completa dello scenario 4 negli [scenari di integrazione degli account](https://docs.zokogames.com/it/requirements/accounts). Se il tuo gioco non ha account, o ti servono solo un nome e un avatar, bastano [account dei giocatori e il tuo backend](https://docs.zokogames.com/it/guides/player-accounts).

L'idea in una riga: il tuo server si fida solo di un **token verificato**. Il token porta uno `userId` stabile; tu memorizzi un collegamento tra quello `userId` e il tuo account, e da quel momento è l'identità ZokoGames a decidere quale account caricare.

Termini come ospite e token sono nel [glossario](https://docs.zokogames.com/it/getting-started/glossary). Gli esempi presuppongono `const SDK = window.ZokoGames.SDK;`.

## Cosa ti serve {#what-you-need}

- Un server sotto il tuo controllo che sappia rispondere a richieste HTTPS dal gioco.
- L'id del tuo gioco (mostrato nella pagina del gioco nella console sviluppatori), salvato nella configurazione del server come `ZOKO_GAME_ID`.
- Una tabella che associa `zoko_user_id` al tuo id di account. Rendi `zoko_user_id` univoco, così un giocatore ZokoGames non può mai essere collegato a due account.

## Il flusso {#the-flow}

```text
launch
  -> getUser()                         null: play as a guest, stop here
  -> getUserToken()  -> POST /session  server verifies the token, answers { linked }
        linked: true   -> load that game account (the ZokoGames identity wins)
        linked: false  -> showAccountLinkPrompt()
                              "yes" -> POST /link  server links userId to the game account
                              "no"  -> continue as a guest
```

Gli ospiti devono sempre poter giocare. Non bloccare mai il gioco dietro l'accesso e non aprire mai da solo la finestra di accesso all'avvio; vedi [proporre l'accesso in risposta a un'azione del giocatore](https://docs.zokogames.com/it/guides/player-accounts#2-offer-sign-in-on-a-player-action).

## 1. Leggere il giocatore e ottenere un token {#1-read-the-player-and-get-a-token}

```js
await SDK.init();

async function token() {
  try {
    return await SDK.user.getUserToken();      // cached by the SDK, valid for one hour
  } catch (e) {
    if (e.code === "userNotAuthenticated") return null;   // a guest
    throw e;
  }
}

async function api(path, body = {}) {
  const t = await token();
  return fetch(`https://api.example.com${path}`, {
    method: "POST",
    headers: {
      "content-type": "application/json",
      ...(t ? { authorization: `Bearer ${t}` } : {}),
    },
    body: JSON.stringify(body),
  });
}
```

Chiama `getUserToken()` prima di ogni richiesta invece di conservare tu la stringa: l'SDK la rinnova un minuto prima della scadenza. `getUser()` va bene per il nome nella tua HUD, ma il suo `__dangerousUserId` può essere falsificato nel browser, quindi non inviarlo mai al server come prova di identità.

## 2. Verificare il token sul tuo server {#2-verify-the-token-on-your-server}

Un token di gioco è un JWT firmato con **RS256**. La sua intestazione ha `alg: "RS256"`, `typ: "JWT"` e un `kid`. I suoi claim sono:

| Claim | Valore |
| --- | --- |
| `iss` | Sempre `zokogames`. |
| `aud` | L'id del tuo gioco. Un token emesso per un altro gioco ha un `aud` diverso. |
| `sub` e `userId` | L'id stabile del giocatore. Usalo come chiave del collegamento. |
| `gameId` | Ancora l'id del tuo gioco. |
| `username`, `profilePictureUrl` | Nome visualizzato e avatar al momento dell'emissione. |
| `iat`, `exp` | Momento di emissione e scadenza, a un'ora di distanza (secondi dal 1970). |

Verifica la firma con le chiavi pubbliche in `https://www.zokogames.com/.well-known/jwks.json` (un JWKS standard) e controlla emittente, audience e scadenza. Con `jose` basta una chiamata:

```js
// zoko-auth.js
import { createRemoteJWKSet, jwtVerify } from "jose";

const GAME_ID = process.env.ZOKO_GAME_ID;
const JWKS = createRemoteJWKSet(new URL("https://www.zokogames.com/.well-known/jwks.json"));

/** Returns { userId, username } for a valid token, or throws. */
export async function verifyZokoToken(raw) {
  const { payload } = await jwtVerify(raw, JWKS, {
    algorithms: ["RS256"],       // never accept anything else
    issuer: "zokogames",
    audience: GAME_ID,           // a token for another game fails here
    requiredClaims: ["exp", "iat", "aud"],
    clockTolerance: 5,           // seconds of clock drift
  });
  if (payload.gameId !== GAME_ID || payload.sub !== payload.userId) {
    throw new Error("malformed token");
  }
  return { userId: String(payload.userId), username: String(payload.username) };
}

/** Express middleware: req.player is null for a guest, 401 for a token that does not verify. */
export async function zokoAuth(req, res, next) {
  const raw = (req.headers.authorization || "").replace(/^Bearer /, "");
  if (!raw) {
    req.player = null;
    return next();
  }
  try {
    req.player = await verifyZokoToken(raw);
    next();
  } catch {
    res.status(401).json({ error: "invalid_token" });
  }
}
```

`createRemoteJWKSet` mette in cache le chiavi e le riscarica quando incontra un `kid` sconosciuto, quindi una rotazione delle chiavi non richiede modifiche da parte tua. Se la tua libreria JWT accetta solo una chiave statica, scarica la stessa chiave come documento PEM da `https://www.zokogames.com/.well-known/public-key.json`, che risponde `{ "alg": "RS256", "kid": "…", "publicKey": "-----BEGIN PUBLIC KEY-----…" }`:

```js
import { importSPKI, jwtVerify } from "jose";

const doc = await (await fetch("https://www.zokogames.com/.well-known/public-key.json")).json();
const key = await importSPKI(doc.publicKey, doc.alg);
const { payload } = await jwtVerify(raw, key, { algorithms: ["RS256"], issuer: "zokogames", audience: GAME_ID });
if (payload.gameId !== GAME_ID || payload.sub !== payload.userId) throw new Error("wrong game or subject");
```

Una chiave statica smette di funzionare quando il portale ruota la propria chiave. Riscarica il documento quando la verifica fallisce con un `kid` che non hai mai visto, oppure preferisci il JWKS. La modalità locale (la tua pagina su `localhost`) emette token di prova non firmati che un verificatore corretto rifiuta; vedi [collauda ogni percorso in locale](#5-test-every-path-locally). I verificatori per Python, C# e Go sono nel [riferimento del modulo user](https://docs.zokogames.com/it/sdk/user#verifying-on-your-server).

## 3. Rispondere a "questo giocatore è collegato?" {#3-answer-is-this-player-linked}

```js
// server.js
import express from "express";
import { zokoAuth } from "./zoko-auth.js";
import { db } from "./db.js";   // your own data layer

const app = express();
app.use(express.json());
app.use(zokoAuth);

app.post("/session", async (req, res) => {
  if (!req.player) return res.json({ guest: true, linked: false });
  const row = await db.links.findByZokoUser(req.player.userId);
  if (!row) return res.json({ guest: false, linked: false });
  // Keep the display data fresh, then load the account the link points to.
  await db.accounts.update(row.accountId, { displayName: req.player.username });
  res.json({ guest: false, linked: true, profile: await db.accounts.load(row.accountId) });
});
```

Quando `linked` è `true` vince l'identità ZokoGames: carica quell'account e ignora qualsiasi progresso locale che appartenga a un altro.

## 4. Proporre il collegamento, poi memorizzarlo {#4-offer-the-link-then-store-it}

Solo un giocatore connesso e non ancora collegato vede la richiesta. Chiedi in un momento tranquillo, per esempio dopo la prima sessione o in una schermata delle impostazioni, non nel mezzo della partita.

```js
async function onSignedIn() {
  const res = await (await api("/session")).json();
  if (res.guest || res.linked) return res.profile ?? null;

  try {
    const { response } = await SDK.user.showAccountLinkPrompt();
    if (response === "yes") {
      const out = await api("/link", { gameAccountId: currentAccountId() });
      if (out.status === 409) showMessage("That ZokoGames player is already linked to another account.");
    }
    // "no": stay a guest, the question can be asked again later
  } catch (e) {
    if (e.code !== "userNotAuthenticated" && e.code !== "showAccountLinkPromptInProgress") throw e;
  }
}

SDK.user.addAuthListener(onSignedIn);   // also runs when the player signs in from the portal header
onSignedIn();
```

Sul server, collega lo `userId` **verificato** e nient'altro di ciò che il browser dichiara di sé:

```js
app.post("/link", async (req, res) => {
  if (!req.player) return res.status(401).json({ error: "sign_in_required" });
  const accountId = String(req.body.gameAccountId || "");
  // Your own proof that the caller controls this game account (session cookie, password, device secret...).
  if (!(await db.accounts.callerOwns(req, accountId))) return res.status(403).json({ error: "not_your_account" });
  try {
    await db.links.insert({ zokoUserId: req.player.userId, accountId });   // zoko_user_id is UNIQUE
  } catch (e) {
    if (e.code === "unique_violation") return res.status(409).json({ error: "already_linked" });
    throw e;
  }
  res.json({ linked: true });
});
```

Tre regole lo mantengono sicuro:

- Preferisci collegare a un **account nuovo** piuttosto che unire due account che hanno entrambi dei progressi. Se un'unione è inevitabile, lascia scegliere al giocatore quali progressi tenere.
- Tratta `userId` come chiave e `username` come etichetta: aggiorna l'etichetta a ogni avvio, non usarla mai per trovare un account.
- Dimostra tu stesso, in `/link`, la proprietà dell'account di gioco. Un token prova soltanto chi è il giocatore ZokoGames.

## 5. Collaudare ogni percorso in locale {#5-test-every-path-locally}

Sulla tua pagina `localhost` l'SDK gira in modalità locale con un giocatore finto, e ogni passaggio qui sopra si può forzare con un parametro nell'URL:

| Percorso | Parametro URL |
| --- | --- |
| Ospite | `?user_response=logged_out` |
| Connesso all'avvio | `?user_response=user1` |
| Il giocatore accetta il collegamento | `?link_account_response=yes` |
| Il giocatore rifiuta il collegamento | `?link_account_response=no` |
| Il token fallisce o è scaduto | `?token_response=logged_out` / `?token_response=expired_token` |

Il token locale non è firmato, quindi il tuo verificatore dovrebbe rifiutarlo. Collauda il percorso firmato con lo [strumento Preview](https://www.zokogames.com/it/preview) o con una build live. L'elenco completo dei parametri è nel [modulo user](https://docs.zokogames.com/it/sdk/user#in-local-mode-as-a-guest-offline-or-ad-free).

## In un motore {#in-an-engine}

Le chiamate sono le stesse in ogni motore; cambiano solo i nomi. In Unity, `User.GetUserToken(cb, ZokoSigningKeyType)` restituisce il token e `User.ShowAccountLinkPrompt(cb)` richiama con `true` per il sì. La corrispondenza per Unity, GameMaker, Defold, Godot e altri è nella [panoramica dei motori](https://docs.zokogames.com/it/engines/overview) e in ciascuna pagina dedicata. Il codice del tuo server non cambia.

## Lista di controllo {#checklist}

- Gli ospiti giocano senza accedere, e un `getUserToken()` fallito con `userNotAuthenticated` non mostra mai un errore.
- Il server verifica firma, `RS256`, `iss`, `aud`, scadenza e `gameId` a ogni richiesta che usa l'identità.
- `zoko_user_id` è univoco nella tua tabella dei collegamenti.
- Un giocatore collegato carica l'account collegato a ogni avvio.
- Rifiutare la richiesta lascia il giocatore nel gioco come ospite.

## Prossimi passi {#next-steps}

- [Account dei giocatori e il tuo backend](https://docs.zokogames.com/it/guides/player-accounts)
- [Modulo user](https://docs.zokogames.com/it/sdk/user)
