User module
Purpose: SDK.user tells your game who is playing (a signed-in player or an anonymous guest), lets you ask a guest to sign in, and gives your own server a signed token to verify that identity. Your game must work for both kinds of player.
At a glance#
Every member of SDK.user, with its signature and the SDK version that added it. The sections below describe each call's errors and how it behaves in local mode, for guests and offline.
| Signature | Resolves to | Can fail with | Since |
|---|---|---|---|
getUser(): Promise<PortalUser | null> |
The signed-in player, or null for a guest. |
timeout, sdkNotInitialized, sdkDisabled. Never userNotAuthenticated. |
1.0.0 |
readonly systemInfo: SystemInfo |
The player's country, locale, device, OS, browser and app type, at once. | Throws sdkNotInitialized or sdkDisabled. |
1.0.0 |
readonly isUserAccountAvailable: boolean |
false when there are no portal accounts here (kids mode). |
Throws sdkNotInitialized or sdkDisabled. |
1.0.0 |
addAuthListener(fn: (user: PortalUser) => void): () => void |
A function that removes this listener; calling it twice is harmless (returned nothing before SDK 1.6.4). | Throws invalidArgument (not a function), sdkNotInitialized, sdkDisabled. |
1.0.0 |
removeAuthListener(fn: (user: PortalUser) => void): void |
Nothing. | Throws sdkNotInitialized or sdkDisabled. |
1.0.0 |
listFriends(options: { page: number; size: number }): Promise<FriendsPage> |
One page of friends who also play this game. | invalidArgument, requestInProgress, rateLimited, userNotAuthenticated, unexpectedError, timeout, sdkNotInitialized, sdkDisabled. |
1.0.0 |
getUserToken(options?: { signingKeyType?: SigningKeyType }): Promise<string> |
A signed token (cached until a minute before it expires). | invalidArgument, userNotAuthenticated, rateLimited, unexpectedError, timeout, sdkNotInitialized, sdkDisabled. |
1.0.0 |
showAuthPrompt(): Promise<PortalUser> |
The player who signed in. | userCancelled, userAlreadySignedIn, showAuthPromptInProgress, sdkNotInitialized, sdkDisabled. timeout only if the portal does not say within 10 seconds who is signed in (the SDK asks first); the prompt itself has no timeout. |
1.0.0 |
showAccountLinkPrompt(): Promise<{ response: "yes" | "no" }> |
The player's answer. | userNotAuthenticated, showAccountLinkPromptInProgress, userCancelled, sdkNotInitialized, sdkDisabled. No timeout. |
1.0.0 |
submitScore(options: { encryptedScore: string; score: number; delayed?: { encryptedScore: string; earnedAt: number } }): Promise<void> |
Nothing, also when nothing was recorded. | invalidArgument, rateLimited, timeout, sdkNotInitialized, sdkDisabled. |
1.0.0 (delayed: 1.6.4) |
getXsollaUserToken(): Promise<string> |
The purchase token (same as SDK.store.getPurchaseToken()). |
userNotAuthenticated, rateLimited, unexpectedError, timeout, sdkNotInitialized, sdkDisabled. |
1.1.0 (deprecated) |
Types in the declaration file described in the SDK introduction: UserApi, PortalUser, Friend, FriendsPage, SystemInfo, SigningKeyType and LeaderboardEntry.
Lifecycle#
init() resolves
-> getUser() null for a guest
-> player presses "Sign in" -> showAuthPrompt() -> auth listener fires -> new PortalUser
-> getUserToken() only for a signed-in player
-> send the token to YOUR server -> server verifies it with the public keys -> trusted userIdErrors every call can raise (sdkNotInitialized, sdkDisabled, timeout, invalidArgument) are in errors. The tables below list the module-specific codes for each call.
System information#
readonly isUserAccountAvailable: boolean
readonly systemInfo: SystemInfoisUserAccountAvailable is false when the game is embedded somewhere without portal accounts. Hide sign-in UI when it is. Both members are synchronous and throw sdkNotInitialized before init() resolves.
interface SystemInfo {
countryCode: string; // "US"
locale: string; // "en-US"
device: { type: "desktop" | "tablet" | "mobile" };
os: { name: string; version: string };
browser: { name: string; version: string };
applicationType: "web" | "pwa" | "google_play_store" | "apple_store";
}In the portal these values describe the player's real browser; in local mode they are read from your browser's user-agent string (countryCode is always "US", applicationType always "web"). Use device.type to decide on mobile controls, not "ontouchstart" in window, and locale to pick a language. See control pitfalls.
getUser#
getUser(): Promise<PortalUser | null>
interface PortalUser {
username: string;
profilePictureUrl: string;
__dangerousUserId: string;
}Returns the signed-in player or null for a guest. It asks the portal each time, so it also picks up a sign-in that happened in the portal's own header. Errors: only the general ones (it never rejects with userNotAuthenticated: a guest is null). Over the call limit (30 in a burst, 10 a second) it resolves the previous answer again. The double-underscore name is deliberate: __dangerousUserId comes from the browser, so anyone can fake it. Use it for display and local state only, and never to decide whose save to load on your server. Server-side identity comes from the token.
Update stored usernames and avatars whenever you see them change.
Friends#
listFriends(options: { page: number; size: number }): Promise<FriendsPage>
interface FriendsPage { friends: Friend[]; page: number; size: number; hasMore: boolean; total: number }
interface Friend { id: string; username: string; profilePictureUrl: string }page is an integer starting at 1 and size an integer from 1 to 50; anything else (including a missing options object) rejects with invalidArgument. Only one request may run at a time (requestInProgress) and calls closer than 250 ms apart fail with rateLimited; the portal can also answer rateLimited when you call too often overall. Guests get userNotAuthenticated. Any other failure is unexpectedError. profilePictureUrl is a full address you can put in an <img>.
let page = 1, more = true;
while (more) {
const res = await SDK.user.listFriends({ page, size: 20 });
render(res.friends);
more = res.hasMore;
page++;
await new Promise((r) => setTimeout(r, 300));
}Tokens#
getUserToken(options?: { signingKeyType?: "IN_GAME_AUTH" | "IN_GAME_AUTH_LEGACY" }): Promise<string>Returns a signed JWT (a token, a compact text string signed by the portal) that proves the player's identity to your server. It is valid for one hour. The SDK caches it and fetches a new one when less than a minute of life remains, so call it freely before each backend request (the cache is dropped when the player signs in). Without a signed-in player it rejects with userNotAuthenticated: let that player continue as a guest. The same code answers a signed-in player whose account has no confirmed 13+ birthday, and every call in kids mode or in a kids' game. A game cannot tell that player from a signed-out one, on purpose: getUser() also resolves null for both, so treat both as a guest and keep the game playable. Offering showAuthPrompt is right for both: for an account without a confirmed birthday it opens the sign-in flow as for a guest instead of rejecting with userAlreadySignedIn, and addAuthListener fires once the account is eligible. Other errors: rateLimited (the portal allows 60 token requests a minute per player), unexpectedError (for example a game that is not live and not yours to test), invalidArgument (a signingKeyType other than the two listed). Calls made while a token request is already running share its result.
The signingKeyType option is accepted so code ported from other portals keeps working, but ZokoGames signs every token the same way: with one RS256 key. IN_GAME_AUTH and IN_GAME_AUTH_LEGACY return equivalent tokens, so there is nothing to migrate and new games should omit the option. The SDK caches one token per signingKeyType value. The argument must be an object: passing the string "IN_GAME_AUTH" is ignored and the default key is used, and since SDK 1.6.3 the console prints one warning per page that names the type you passed (never the value). An object whose signingKeyType is anything but those two names rejects with invalidArgument.
The token is a JWT signed with RS256. Its header carries alg: "RS256", typ: "JWT" and a kid that names the signing key. It carries these claims, plus iat (issue time), exp (iat plus 3,600 seconds), iss (zokogames), aud (your game id) and sub (the player id):
| Claim | Meaning |
|---|---|
userId |
Stable player id. Use it as the key of your own account record. |
gameId |
Your game's id. Check it matches, otherwise a token minted for another game could be replayed against yours. |
username |
Display name at the time of issue. |
profilePictureUrl |
Avatar URL at the time of issue. |
Times are in seconds and there is no nbf. aud is one string, not an array, and sub always equals userId. userId is a UUID (36 characters), the same in every game and equal to __dangerousUserId from getUser(). The game id is the UUID in your game's console address (/developer/games/<id>): it is set when the draft is created and stays the same after launch. From SDK 1.6.2 the game can read it as SDK.game.gameId; your server should still keep its own copy in its configuration.
Verifying on your server#
Never trust a token you did not verify, and never act on getUser() data sent from the browser. Fetch the public keys from the JWKS endpoint and verify the signature, the expiry, the issuer (zokogames) and the audience (aud, which must equal your game id). Every sample below does all four, pins RS256, and also compares the gameId claim (the same value as aud) and checks that sub equals userId. Where your game id comes from: the UUID in the game's console address (/developer/games/<id>), fixed when the draft is created and unchanged after launch. The same id is used to encrypt scores, and userId here is the id that goes into that encryption as well.
https://www.zokogames.com/.well-known/jwks.jsonThe key set is a standard JWKS with RS256 signature keys (use: "sig"). The response is served with cache-control: public, max-age=3600, stale-while-revalidate=86400 and open CORS, so an hour of caching is what we expect.
Key rotation. A token's kid names the key that signed it. When the signing key is replaced, new tokens carry the new kid and the JWKS lists it; tokens already issued (valid for one hour) keep verifying while their key is still listed. So: cache the set, and when a token arrives with a kid you do not have, refetch the set once (rate-limit that refetch, for example once a minute, so a forged kid cannot make you hammer the endpoint) and then fail if it is still unknown. jose, PyJWT's PyJWKClient and keyfunc do this for you; the C# sample refreshes hourly, so on an unknown kid clear its cache and verify once more. Do not hard-code a key in your server.
Using the token on a WebSocket or in a long session. A browser cannot set an Authorization header on a WebSocket, so send the token as the first message after the connection opens (a token in the address ends up in server logs) and close the connection if it does not verify within a few seconds. The token lives for one hour, so a connection that outlives it must send a fresh one from getUserToken() before it expires. A guest has no token: let a guest play with an id you create yourself, and ask the player to sign in before you link that id to a ZokoGames account. Your server needs to reach https://www.zokogames.com to read the keys; cache them as described above.
If your JWT library only takes a static key, fetch the same key as PEM from https://www.zokogames.com/.well-known/public-key.json. It returns { "publicKey": "-----BEGIN PUBLIC KEY-----…", "kid": "…", "alg": "RS256" }. When a token's kid no longer matches the stored one, the key was rotated: fetch it again. Prefer the JWKS, which handles rotation for you.
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) };
}import os
import jwt # PyJWT >= 2.8, with the "crypto" extra
jwks_client = jwt.PyJWKClient("https://www.zokogames.com/.well-known/jwks.json", cache_keys=True)
GAME_ID = os.environ["ZOKO_GAME_ID"]
def verify_zoko_token(token: str) -> dict:
signing_key = jwks_client.get_signing_key_from_jwt(token)
claims = jwt.decode(
token,
signing_key.key,
algorithms=["RS256"],
audience=GAME_ID,
issuer="zokogames",
options={"require": ["exp", "iat"]},
leeway=5,
)
if claims.get("gameId") != GAME_ID or claims.get("sub") != claims.get("userId"):
raise ValueError("token is for a different game")
return claimsusing System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;
public sealed class ZokoTokenVerifier
{
private static readonly HttpClient Http = new();
private JsonWebKeySet? _keys;
private DateTime _fetched = DateTime.MinValue;
public async Task<JwtSecurityToken> VerifyAsync(string token, string gameId)
{
if (_keys is null || DateTime.UtcNow - _fetched > TimeSpan.FromHours(1))
{
var json = await Http.GetStringAsync("https://www.zokogames.com/.well-known/jwks.json");
_keys = new JsonWebKeySet(json);
_fetched = DateTime.UtcNow;
}
var parameters = new TokenValidationParameters
{
ValidAlgorithms = new[] { SecurityAlgorithms.RsaSha256 }, // RS256 only
IssuerSigningKeys = _keys.GetSigningKeys(),
ValidateIssuer = true,
ValidIssuer = "zokogames",
ValidateAudience = true,
ValidAudience = gameId, // the token's `aud` is your game id
ValidateLifetime = true,
ClockSkew = TimeSpan.FromSeconds(5),
};
new JwtSecurityTokenHandler().ValidateToken(token, parameters, out var validated);
var jwt = (JwtSecurityToken)validated;
string? Claim(string type) => jwt.Claims.FirstOrDefault(c => c.Type == type)?.Value;
if (Claim("gameId") != gameId || Claim("sub") != Claim("userId"))
throw new SecurityTokenException("token is for a different game or malformed");
return jwt;
}
}package zoko
import (
"errors"
"os"
"time"
"github.com/MicahParks/keyfunc/v3"
"github.com/golang-jwt/jwt/v5"
)
// NewDefault fetches the key set, caches it and refreshes it in the background.
var jwks, _ = keyfunc.NewDefault([]string{"https://www.zokogames.com/.well-known/jwks.json"})
func VerifyToken(raw string) (jwt.MapClaims, error) {
claims := jwt.MapClaims{}
_, err := jwt.ParseWithClaims(raw, claims, jwks.Keyfunc,
jwt.WithValidMethods([]string{"RS256"}),
jwt.WithExpirationRequired(),
jwt.WithIssuer("zokogames"),
jwt.WithAudience(os.Getenv("ZOKO_GAME_ID")),
jwt.WithLeeway(5*time.Second),
)
if err != nil {
return nil, err
}
if claims["gameId"] != os.Getenv("ZOKO_GAME_ID") {
return nil, errors.New("token is for a different game")
}
return claims, nil
}Send the token with each request, for example Authorization: Bearer <token>:
const token = await SDK.user.getUserToken();
const res = await fetch("https://api.example.com/save", {
method: "POST",
headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
body: JSON.stringify(saveGame),
});Local mode issues an unsigned token (alg: none). A correct verifier rejects it. For local backend development, add a clearly separated test-only bypass that is impossible to enable in production. There is no signed test token and no test key: to run your verifier against a real signed token, sign in with an account of your studio and open the game's build preview in the console (the portal issues tokens for a game that is not live yet to its studio's members).
Testing your verifier without a live player. There is no signed test token and no shared test key, on purpose. Three ways, from cheapest:
- Unit-test the checks themselves: generate your own RSA key pair in the test, sign tokens with it and give your verifier that public key instead of the JWKS. Cover a valid token, a wrong
aud, a wrongiss, an expiredexp,alg: none, a signature from another key, andsubdifferent fromuserId. - Against the real keys: in the console open the game's build preview signed in as a member of your studio. Call
SDK.user.getUserToken()there and send the token to your staging server; the portal issues real signed tokens for a game that is not live yet to its studio's members. - Locally:
?token_response=user1issues an unsigned token that a correct verifier must reject; use it to test the rejection path.
In local mode the token has the claims userId, gameId ("local-game"), username, profilePictureUrl, iat, exp and local: true, but no iss, aud or sub, and its header says alg: none. You can steer it with ?token_response=: logged_out rejects with userNotAuthenticated, user1 or user2 issue a token for that mock player, and expired_token issues one whose exp is already in the past, so you can test your backend's expiry path. Any other token_response value is ignored and the current mock player gets a token. Switch values are case-sensitive and a misspelled one is not an error: ?user_response=User1 or ?user_response=guest simply starts the game as a guest, and a wrong show_auth_prompt_response or link_account_response is read as a cancel or as yes. Since SDK 1.6.3 the console prints one warning per page that names the wrong switch and the values it accepts.
Sign-in prompt#
showAuthPrompt(): Promise<PortalUser>
addAuthListener(fn: (user: PortalUser) => void): () => void
removeAuthListener(fn: (user: PortalUser) => void): voidAsks the player to sign in. The portal first shows a small invitation over the game ("Sign in" or "Not now"); choosing Sign in opens the portal's own sign-in dialog, and "Not now" rejects with userCancelled. Only call it in response to a player action, such as pressing a "Sign in to save your progress" button, never automatically at start. It resolves with the new user, or rejects:
| Code | Meaning |
|---|---|
userAlreadySignedIn |
Someone is already signed in. Check with getUser() first. |
showAuthPromptInProgress |
The invitation or the dialog is already open. |
userCancelled |
The player chose Not now or closed the dialog, or sign-in is not offered here (for example in a kids' game). Carry on as a guest. |
Before it opens anything, showAuthPrompt asks the portal who is signed in, so a stale answer from before a sign-out cannot give userAlreadySignedIn; that one question is the only step that can reject with timeout (10 seconds). The prompt itself has no timeout. addAuthListener throws invalidArgument if the argument is not a function; removeAuthListener ignores a function that was never added. The portal opens at most three prompts per page view and none for 60 seconds after the player chose Not now or closed the dialog; a call in either case rejects with userCancelled at once. In a kids' game the portal answers userCancelled at once. The auth listener also fires when the player signs in through the portal's own header while your game is open, so register one and update your UI there instead of relying only on the promise. The listener only ever receives a signed-in PortalUser, never null, and nothing is sent when the player signs out: signing out of the portal does not call it. If your game stays open across a sign-out, do not rely on the listener; call getUser() again when you need to know who is playing, and treat null as a guest.
SDK.user.addAuthListener((user) => { hud.setName(user.username); syncProgress(); });
signInButton.onclick = async () => {
try { await SDK.user.showAuthPrompt(); }
catch (e) { if (e.code !== "userCancelled") console.warn(e.code); }
};Deprecated#
getXsollaUserToken(): Promise<string> is a deprecated alias that returns the purchase token (the same value as SDK.store.getPurchaseToken()); use the new name instead (see in-game purchases). It fails with userNotAuthenticated for guests.
Account linking#
showAccountLinkPrompt(): Promise<{ response: "yes" | "no" }>For games with their own accounts. Ask a signed-in player whether to link their ZokoGames identity to the game's existing account. Link the userId from the verified token on your server only when the response is "yes", and prefer linking to fresh accounts over merging two accounts with progress. A player with no signed-in portal user (and every player in a kids' game) gets userNotAuthenticated, and a second call while the prompt is open rejects with showAccountLinkPromptInProgress. The same limits as for the sign-in prompt apply (three per page view, a 60-second pause after a "no"), and a call over them rejects with userCancelled. The call has no timeout because the player decides when to answer. See account integration scenarios.
Submitting scores#
submitScore(options: { encryptedScore: string; score: number; delayed?: { encryptedScore: string; earnedAt: number } }): Promise<void>Posts a leaderboard score from the client. It rejects with invalidArgument unless encryptedScore is a string and score is a finite number, and with rateLimited when the player submits too often. A guest does not get an error; see leaderboards for that and for the encryption scheme. The optional delayed copy keeps a score that was earned offline and sends it when the player is back online (SDK 1.6.4); how to seal it is in Offline scores.
In local mode, as a guest, offline or ad-free#
| Member | Local mode | Guest | Offline |
|---|---|---|---|
isUserAccountAvailable |
true; false with ?user_account_available=false (then the player is a guest) |
true in the portal |
true |
getUser |
A mock player: ?user_response=user1 (default) or user2; any other value (such as logged_out) means a guest |
null |
A saved game started offline uses the last signed-in player on this device |
listFriends |
12 mock friends, paged | userNotAuthenticated |
Needs the portal; fails with unexpectedError |
getUserToken |
Unsigned test token (see token_response above) |
userNotAuthenticated |
Needs the portal; fails with unexpectedError |
showAuthPrompt |
Signs in at once as ?show_auth_prompt_response= (user1 default, user2); any other value rejects with userCancelled; userAlreadySignedIn if already signed in |
Shows the invitation, then opens the portal's sign-in dialog | Needs the portal; fails or never answers until back online |
showAccountLinkPrompt |
?link_account_response=yes (default) or no; logged_out or a guest gives userNotAuthenticated |
userNotAuthenticated |
Needs the portal; fails or never answers until back online |
submitScore |
Resolves, records nothing; SDK 1.6.3 logs one console line per call. Offline with a signed-in player and delayed, SDK 1.6.4 shows "Score saved offline" |
Resolves without recording, and the score is not kept. When it would place in the top 10 of the current week's board, the portal invites the player to sign in, at most once per game per page view. Submit the score again after sign-in if it should count. | Resolves without recording. Offline, the score is not lost if you also pass delayed: a copy sealed at the end of the run with earnedAt = Date.now(), additional data `zoko-score-v3 |
| Ad blocker / ad-free | No effect on this module |
In basic launch nothing in this module changes: a basic-launch game is live, so players can sign in, list friends and get tokens as in full launch.
Common mistakes. The ones reviewers and the Preview tool report most often:
| Mistake | Result | Fix |
|---|---|---|
getUserToken() is called for a guest |
userNotAuthenticated |
Check getUser() first, or catch the code and continue as a guest. |
__dangerousUserId or username is sent to your server as proof of identity |
Anyone can fake it | Send the token from getUserToken() and verify it on the server, with the iss, aud and gameId checks. |
The token is verified without checking aud or gameId |
A token from another game is accepted | Check both, as in the samples. |
A local-mode token (alg: none) reaches production verification |
Correctly rejected | Use the test-only bypass for local work only. |
showAuthPrompt() runs at start or on a timer |
userCancelled after the first refusal, and none for 60 seconds |
Call it from a button press ("Sign in to save"). |
The userCancelled rejection is shown as an error |
A scary message after "Not now" | Treat it as a normal answer and carry on as a guest. |
showAuthPrompt() is called for a player who is already signed in |
userAlreadySignedIn |
Check getUser(), or just handle the code. |
The game only uses the promise of showAuthPrompt |
A sign-in from the portal header is missed | Register addAuthListener as well. |
listFriends is called in a tight loop |
requestInProgress or rateLimited |
One request at a time, 250 ms or more apart, size 1 to 50. |
submitScore is called every frame |
rateLimited |
Submit once per run. |
| Sign-in UI is shown in kids mode | isUserAccountAvailable is false and the prompt answers userCancelled |
Hide it when isUserAccountAvailable is false. |
systemInfo or isUserAccountAvailable is read before init() |
sdkNotInitialized |
Read them after await SDK.init(). |
Full runnable example:
await SDK.init();
let user = await SDK.user.getUser();
SDK.user.addAuthListener((u) => { user = u; hud.setName(u.username); });
async function loadProfile() {
if (!user) return null; // guest: play without a profile
try {
const token = await SDK.user.getUserToken();
const res = await fetch("https://api.example.com/profile", {
headers: { authorization: `Bearer ${token}` },
});
return res.json();
} catch (e) {
if (e.code === "userNotAuthenticated") return null;
throw e;
}
}Kids mode. init reports no user and isUserAccountAvailable is false, getUser resolves null, getUserToken, listFriends and showAccountLinkPrompt reject with userNotAuthenticated, and showAuthPrompt rejects with userCancelled. Branch on isUserAccountAvailable, not on the codes; the full list is in kids mode.