# 계정 연동 단계별 가이드

게임에 자체 계정과 자체 서버가 있고, 로그인한 ZokoGames 플레이어가 실행할 때마다 올바른 게임 계정으로 들어가게 하고 싶다면 이 가이드를 사용하세요. [계정 통합 시나리오](https://docs.zokogames.com/kr/requirements/accounts)의 시나리오 4를 완전하게 다룬 버전입니다. 게임에 계정이 없거나 이름과 아바타만 필요하다면 [플레이어 계정과 백엔드](https://docs.zokogames.com/kr/guides/player-accounts)로 충분합니다.

핵심은 한 줄입니다. 서버는 오직 **검증된 토큰**만 신뢰합니다. 토큰에는 변하지 않는 `userId`가 들어 있습니다. 이 `userId`에서 자체 계정으로 가는 연결을 저장해 두면, 그 이후에는 ZokoGames 신원이 어떤 계정을 불러올지 결정합니다.

게스트, 토큰 같은 용어는 [용어집](https://docs.zokogames.com/kr/getting-started/glossary)에 있습니다. 예제는 `const SDK = window.ZokoGames.SDK;`를 전제로 합니다.

## 필요한 것

- 게임의 HTTPS 요청에 응답할 수 있는, 직접 관리하는 서버.
- 게임 ID(개발자 콘솔의 게임 페이지에 표시됨). 서버 설정에 `ZOKO_GAME_ID`로 저장합니다.
- `zoko_user_id`를 자체 계정 ID에 매핑하는 테이블. `zoko_user_id`는 고유하게 만들어, 한 명의 ZokoGames 플레이어가 두 계정에 연결되는 일이 없게 하세요.

## 흐름

```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
```

게스트는 언제나 플레이할 수 있어야 합니다. 로그인 때문에 게임을 막지 말고, 시작할 때 로그인 대화상자를 직접 열지도 마세요. [플레이어 행동에 로그인 제안하기](https://docs.zokogames.com/kr/guides/player-accounts#2-offer-sign-in-on-a-player-action)를 참고하세요.

## 1. 플레이어를 읽고 토큰 받기

```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),
  });
}
```

문자열을 직접 보관하지 말고 요청마다 `getUserToken()`을 호출하세요. SDK가 만료 1분 전에 토큰을 갱신합니다. HUD에 이름을 표시하는 용도로는 `getUser()`를 써도 되지만, 그 `__dangerousUserId`는 브라우저에서 위조할 수 있으므로 신원 증명으로 서버에 보내서는 안 됩니다.

## 2. 서버에서 토큰 검증하기

게임 토큰은 **RS256**으로 서명된 JWT입니다. 헤더에는 `alg: "RS256"`, `typ: "JWT"`, `kid`가 있습니다. 클레임은 다음과 같습니다.

| 클레임 | 값 |
| --- | --- |
| `iss` | 항상 `zokogames`. |
| `aud` | 게임 ID. 다른 게임용으로 발급된 토큰은 `aud`가 다릅니다. |
| `sub`, `userId` | 변하지 않는 플레이어 ID. 연결의 키로 사용하세요. |
| `gameId` | 다시 한번 게임 ID. |
| `username`, `profilePictureUrl` | 발급 시점의 표시 이름과 아바타. |
| `iat`, `exp` | 발급 시각과 만료 시각. 한 시간 간격입니다(1970년부터의 초). |

`https://www.zokogames.com/.well-known/jwks.json`(표준 JWKS)의 공개 키로 서명을 검증하고, 발급자, 대상(audience), 만료를 확인하세요. `jose`를 쓰면 호출 한 번으로 됩니다.

```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`은 키를 캐시하고 모르는 `kid`를 만나면 다시 가져오므로, 키가 교체되어도 서버 쪽에서 바꿀 것이 없습니다. 사용하는 JWT 라이브러리가 정적 키만 받는다면 `https://www.zokogames.com/.well-known/public-key.json`에서 같은 키를 PEM 문서로 가져오세요. 이 주소는 `{ "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");
```

정적 키는 포털이 키를 교체하면 동작하지 않습니다. 처음 보는 `kid` 때문에 검증이 실패하면 문서를 다시 가져오거나, 가급적 JWKS를 사용하세요. 로컬 모드(직접 띄운 `localhost` 페이지)는 서명되지 않은 테스트 토큰을 발급하며, 올바른 검증기는 이를 거부합니다. [모든 경로를 로컬에서 테스트하기](#5-test-every-path-locally)를 참고하세요. Python, C#, Go용 검증 예제는 [user 모듈 레퍼런스](https://docs.zokogames.com/kr/sdk/user#verifying-on-your-server)에 있습니다.

## 3. "이 플레이어는 연결되어 있는가?"에 응답하기

```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) });
});
```

`linked`가 `true`이면 ZokoGames 신원이 우선합니다. 그 계정을 불러오고, 다른 계정에 속한 로컬 진행 상황은 무시하세요.

## 4. 연결을 제안하고 저장하기

로그인했지만 아직 연결되지 않은 플레이어에게만 안내 창이 표시됩니다. 플레이 도중이 아니라 첫 세션 이후나 설정 화면처럼 차분한 순간에 물어보세요.

```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();
```

서버에서는 브라우저가 스스로에 대해 하는 말이 아니라 **검증된** `userId`만 연결하세요.

```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 });
});
```

세 가지 규칙이 안전을 지켜 줍니다.

- 진행 상황이 있는 두 계정을 합치기보다 **새 계정**에 연결하는 쪽을 택하세요. 합병이 불가피하다면 어느 진행 상황을 남길지 플레이어가 고르게 하세요.
- `userId`는 키로, `username`은 라벨로 다루세요. 라벨은 실행할 때마다 갱신하되, 계정을 찾는 데 쓰지 마세요.
- `/link`에서 게임 계정의 소유권은 직접 증명받으세요. 토큰은 ZokoGames 플레이어가 누구인지만 증명합니다.

## 5. 모든 경로를 로컬에서 테스트하기 {#5-test-every-path-locally}

직접 띄운 `localhost` 페이지에서는 SDK가 가짜 플레이어와 함께 로컬 모드로 동작하며, 위의 모든 단계를 URL 스위치로 강제할 수 있습니다.

| 경로 | URL 스위치 |
| --- | --- |
| 게스트 | `?user_response=logged_out` |
| 실행 시 로그인됨 | `?user_response=user1` |
| 플레이어가 연결 수락 | `?link_account_response=yes` |
| 플레이어가 연결 거절 | `?link_account_response=no` |
| 토큰 실패 또는 만료 | `?token_response=logged_out` / `?token_response=expired_token` |

로컬 토큰은 서명되지 않으므로 검증기가 거부해야 합니다. 서명된 경로는 [미리보기 도구](https://www.zokogames.com/kr/preview)나 실제 빌드로 테스트하세요. 전체 스위치 목록은 [user 모듈](https://docs.zokogames.com/kr/sdk/user#in-local-mode-as-a-guest-offline-or-ad-free)에 있습니다.

## 엔진에서

호출은 어느 엔진에서나 같고 이름만 다릅니다. Unity에서는 `User.GetUserToken(cb, ZokoSigningKeyType)`이 토큰을 반환하고, `User.ShowAccountLinkPrompt(cb)`는 수락 시 `true`로 콜백합니다. Unity, GameMaker, Defold, Godot 등의 대응표는 [엔진 개요](https://docs.zokogames.com/kr/engines/overview)와 각 엔진 페이지에 있습니다. 서버 코드는 바뀌지 않습니다.

## 체크리스트

- 게스트는 로그인 없이 플레이할 수 있으며, `userNotAuthenticated`로 실패한 `getUserToken()`은 오류를 표시하지 않음.
- 서버는 신원을 사용하는 모든 요청에서 서명, `RS256`, `iss`, `aud`, 만료, `gameId`를 검증함.
- 연결 테이블에서 `zoko_user_id`가 고유함.
- 연결된 플레이어는 실행할 때마다 연결된 계정을 불러옴.
- 안내 창을 거절해도 플레이어는 게스트로 게임에 남음.

## 다음 단계 {#next-steps}

- [플레이어 계정과 백엔드](https://docs.zokogames.com/kr/guides/player-accounts)
- [User 모듈](https://docs.zokogames.com/kr/sdk/user)
