# AikaHub for developers > AikaHub (https://aikahub.com) is a Hungarian community site with a game space, the Játéktér ("Playground"). Games connect to it with > "Log in with AikaHub" (OAuth 2.0 authorization code + PKCE S256): the member's public profile and 3D VRM character, > achievements, entitlements, cloud saves, leaderboards, visits with preset gifts and "playing now" presence. The official > client is @aikahub/sdk 1.5.0 (ESM, no dependencies; browser / Cloudflare Workers / Node ≥ 18 / Deno). The Hub never > shares email addresses. Beginners make games without code in AikaHub Studio (https://studio.aikahub.com/). Developer home (EN/HU/DE): https://aikahub.dev/ — contact: info@aika.hu ## Start - [AikaHub Studio](https://studio.aikahub.com/): browser game maker, no install; starter games "Arena shooter", "My Little Shop", "Star Island"; one-button publishing to the Playground - [My first game](https://aikahub.dev/tutorial/): 15-minute step-by-step guide with a starter game on your own computer (Node ≥ 18, Mock Hub with test players, then the real Hub) - [Downloads](https://aikahub.dev/downloads/): starter-game ZIPs, SDK files, "Log in with AikaHub" button and badge ## Docs - [Docs](https://aikahub.dev/docs/): entry points, registering a game, scopes, trust levels, error codes, retry rules, privacy, brand - [SDK reference](https://aikahub.dev/docs/sdk/): the full @aikahub/sdk README (install, quickstart, cloud saves, leaderboards, visits, presence, errors) - [Publishing](https://aikahub.dev/publish/): review, sandbox, limits and the exact Content-Security-Policy of published games - [AGENTS.md](https://aikahub.dev/AGENTS.md): how an AI coding agent should build an AikaHub game - [llms-full.txt](https://aikahub.dev/llms-full.txt): everything above plus the SDK README and TypeScript types, as one plain-text file - [Developer console](https://aikahub.com/developers/console): self-service clients (login required, 18+, verified email) - [Developer Agreement](https://aikahub.com/developers/agreement) · [AikaHub SDK License](https://aikahub.com/developers/sdk-license) · [all versions](https://aikahub.com/developers/legal) - [OAuth discovery (RFC 8414)](https://aikahub.com/.well-known/oauth-authorization-server) ## SDK files (pinned, CORS-enabled; pin the exact version and check integrity) - [browser.js](https://aikahub.com/sdk/1.5.0/browser.js): `createClient({ clientId, redirectUri, scopes })` → `login()`, `handleCallback()`, `me()`, `character()`, `unlock(key)`, `entitlements()`, `cloudSave()`, `saves`, `scores`, `visits`, `presence`, `logout()` - [server.js](https://aikahub.com/sdk/1.5.0/server.js): `createServerClient({ clientId, clientKey })` → `verifyAccessToken(token)`, `unlock(sub, id)`, `entitlements(sub)`, `queue()`, saves and scores for a member - [same-origin.js](https://aikahub.com/sdk/1.5.0/same-origin.js): games hosted on aikahub.com — `createSameOriginClient({ game })` - [aikahub-sdk.js](https://aikahub.com/sdk/1.5.0/aikahub-sdk.js): everything in one file - [manifest.json](https://aikahub.com/sdk/1.5.0/manifest.json): sizes and SRI (sha384) hashes; `/sdk/v1/…` = newest 1.x (no fixed hash, never put `integrity` on it) ## Scopes `profile` (nickname, avatar, level, profile colour and link) · `character` (VRM file, thumbnail, licence flags) · `achievements` (unlock + read rewards) · `save` (cloud saves: 4 slots per member per game, ≤ 64 KB each, 2 MB per member) · `scores` (leaderboards; only a member's best counts; public) · `visits` (home snapshot ≤ 16 KB, neighbours, preset gifts) · `presence` ("playing now" heartbeat every 45–60 s: menu / playing / idle; only from the member's own client while playing) ## Rules for code you generate - The game's server key (`ahk_` + 64 hex) lives only on the game's server; the Hub stores only its SHA-256. Never put it in browser code, a build or a repo. - Browser tokens stay in memory (SDK default). Never write tokens to localStorage, cookies or logs. - Trust levels: `client` achievements (unlocked from the browser) ≤ 50 XP and never legendary; `server` achievements (unlocked with the server key) ≤ 250 XP, legendary allowed. - Always check on the server that an access token was issued to your game (`verifyAccessToken` checks `aud`). `sub` is pairwise per game. - Redirect URIs match exactly; loopback `http://127.0.0.1/` accepts any port. - Developer clients (`x-` ids) work for the owner and up to 5 testers until the game is published (publish request → review). Their achievements and scores are sandbox-only (no XP) until then. - Games published from the Studio run on `g-.aikahub.dev` with a strict CSP: no inline ` ``` ```js import { createClient } from '@aikahub/sdk/browser'; const hub = createClient({ clientId: 'x-my-game', redirectUri: location.origin + '/', scopes: ['profile', 'achievements'] }); loginButton.addEventListener('click', () => hub.login({ returnTo: '/' })); await hub.handleCallback(); // on the redirect page: checks state, exchanges the code const me = await hub.me(); await hub.unlock('first-win'); // idempotent: a repeat gives { new: false, xp: 0 } ``` Never use `/sdk/v1/…` with an `integrity` hash (v1 moves); never load the SDK or any library from a URL without an exact version. ## Rules — do not break these 1. **No secrets in browser code.** The server key (`ahk_…`) lives only on the game's own server (secret store or a git-ignored `.env.local`). Only its SHA-256 is uploaded in the Developer console. Never import `@aikahub/sdk/server` from browser code. 2. **Tokens stay in memory** (the SDK default). Do not write tokens to localStorage, cookies or logs; do not pass `storage: 'session'` unless the owner asks and understands the XSS trade-off. Never log `sub`. 3. **Achievements:** keys are 2–40 chars of `a-z 0-9 -`, each one must be declared (console or `aikahub.config.json`). `client` trust (unlocked from the browser): at most 50 XP each, never legendary, at most 50 achievements and 450 client XP per game. Valuable ones (`server` trust, up to 250 XP, legendary) only from the game's server with the key. 4. **Ask only for the scopes the game uses** — the member sees every scope on the consent page. Presence is sent only from the member's own client while they are actually playing. 5. **Handle errors**: every SDK error is an `AikaHubError` (`code`, `status`, `final`). `final: true` → do not retry. Use the server retry queue (`hub.queue()`) for server unlocks. ## If the game is published from AikaHub Studio (g-.aikahub.dev) The game is served as static files with exactly this Content-Security-Policy (the Studio preview uses the same one): ``` default-src 'self'; script-src 'self' 'wasm-unsafe-eval' blob:; style-src 'self' 'unsafe-inline'; img-src 'self' data: blob: https://aikahub.com; media-src 'self' data: blob:; font-src 'self' data:; connect-src 'self' https://aikahub.com; worker-src 'self' blob:; object-src 'none'; base-uri 'self'; form-action 'self' https://aikahub.com; frame-ancestors 'self' https://aikahub.com ``` So: - **No inline ``** — put code into `.js` files. The only allowed inline script is the import map (allowed by its exact SHA-256, computed at upload). ` ``` The hashes of every file are in [`/sdk/1.5.0/manifest.json`](https://aikahub.com/sdk/1.5.0/manifest.json). Where import maps with `integrity` are not supported, or for desktop / packaged games, **vendor the file** (copy it into your build) instead of loading it from the Hub. `https://aikahub.com/sdk/v1/…` always serves the newest 1.x (cached for a day) — handy while prototyping, but it cannot carry a fixed integrity hash. **SRI (`integrity`) only works with exact-version URLs** (`/sdk/1.5.0/…`): never put an integrity hash on a `/sdk/v1/` URL — it breaks as soon as a new 1.x ships. Files: `aikahub-sdk.js` (everything), `browser.js`, `same-origin.js`, `server.js`, `manifest.json` (sizes + SRI hashes). Note: the Hub is a single-page app, so a mistyped `/sdk/…` path may answer `200` with the Hub's `index.html` — the import then fails with a MIME-type / syntax error. Check the exact file name. From source: copy `packages/aikahub-sdk/` into your project (it is not on npm yet) and `import { createServerClient } from '@aikahub/sdk/server'`. ## 5-minute quickstart ### 0. Register your game For now: write to **info@aika.hu** with your game's name, website and the exact redirect URI(s) (`https://yourgame.example/auth/callback`; desktop games may use `http://127.0.0.1/` — any port is accepted). You get a `client_id`. Self-service registration in the AikaHub admin is coming. ### 1. Browser: log in ```js import { createClient } from 'https://aikahub.com/sdk/1.5.0/browser.js'; const hub = createClient({ clientId: 'yourgame', redirectUri: 'https://yourgame.example/auth/callback', scopes: ['profile', 'achievements', 'character'], }); // "Log in with AikaHub" button loginButton.onclick = () => hub.login({ returnTo: '/play' }); // on the /auth/callback page const session = await hub.handleCallback(); // checks state, exchanges the code with the PKCE verifier if (session) location.replace(session.returnTo || '/'); ``` Optional: the official button image (light / dark, SVG or PNG, EN/HU/DE — see [aikahub.com/developers#brand](https://aikahub.com/developers#brand) for the usage rules: at least 40 px tall, clear space around it, don't recolour it): ```html ``` ### 2. Use it ```js const me = await hub.me(); // { sub, nickname, avatarUrl, level, profileColor, profileUrl } — never an email const char = await hub.character(); // { vrmUrl, thumbUrl, name, license, games: { peaceful, arena } } await hub.unlock('first-steps'); // client-trust achievement (≤ 50 XP) const { entitlements } = await hub.entitlements(); // [{ value: 'yourgame:ship-skin', … }] await hub.logout(); // revokes the refresh token at the Hub ``` ### 3. Server: unlock with your game key ```sh KEY="ahk_$(openssl rand -hex 32)" # keep this in your server's secrets — never in a client or repo printf '%s' "$KEY" | sha256sum | cut -d' ' -f1 # upload ONLY this hash in the AikaHub Developer console (/developers/console) ``` ```js import { createServerClient } from '@aikahub/sdk/server'; // or https://aikahub.com/sdk/1.5.0/server.js const hub = createServerClient({ clientId: 'yourgame', clientKey: env.AIKAHUB_KEY }); // at login: your game client sends you its access token; check it was issued to YOUR game, store the sub const user = await hub.verifyAccessToken(accessTokenFromClient); await db.linkAikaHub(account.id, user.sub); // later, when your server has verified the event await hub.unlock(user.sub, 'yourgame:first-boss'); // server trust: up to 250 XP, legendary allowed const { entitlements } = await hub.entitlements(user.sub); ``` ### 4. Never lose an unlock: the retry queue ```js const queue = hub.queue({ store: myStore, onDrop: (job, err) => metrics.inc('aikahub_drop', { code: err?.code }) }); await queue.unlock(sub, 'yourgame:first-boss'); // tries now; on a transient error it stays queued // every minute (cron / setInterval): await queue.process(); ``` | Response | Outcome | |---|---| | 2xx | **done** — removed | | 409 `not_linked`, 403 (`insufficient_scope`, `wrong_game`, `server_key_required`), 400 | **drop** — final, removed, `onDrop` | | 401, 404, 408, 425, 429, 5xx, network error, timeout | **retry** — exponential backoff with jitter (2 s → 6 h), honours `Retry-After` (capped at `maxDelayMs`); dropped after `maxAttempts` (12) | Idempotency: the job key is deterministic (`unlock::`), so the same unlock is queued only once, and the Hub's unlock is idempotent (a repeat returns `{ new: false, xp: 0 }`) — at-least-once delivery never gives double XP. A `store` is any object with `get(key)`, `put(job)` (upsert), `remove(key)`, `list()` and, optionally, `claim(key, now, leaseUntil) → boolean`; `memoryStore()` is built in. Before sending, the queue claims the job. Without `claim()` it re-reads the job and skips it if it is gone or leased — safe inside one queue instance, but **if several processes share one store, implement `claim()` as an atomic conditional update**. A job removed while it was being sent is never written back. Example on Cloudflare D1: ```js // CREATE TABLE aikahub_jobs (key TEXT PRIMARY KEY, job TEXT NOT NULL, next_at INTEGER NOT NULL, lease_until INTEGER NOT NULL DEFAULT 0); const d1Store = (db) => ({ async get(key) { const r = await db.prepare('SELECT job, lease_until FROM aikahub_jobs WHERE key = ?').bind(key).first(); return r ? { ...JSON.parse(r.job), leaseUntil: r.lease_until } : null; }, async put(job) { await db.prepare(`INSERT INTO aikahub_jobs (key, job, next_at, lease_until) VALUES (?1, ?2, ?3, ?4) ON CONFLICT(key) DO UPDATE SET job = ?2, next_at = ?3, lease_until = ?4`) .bind(job.key, JSON.stringify(job), job.nextAt, job.leaseUntil).run(); }, async remove(key) { await db.prepare('DELETE FROM aikahub_jobs WHERE key = ?').bind(key).run(); }, async list() { const { results } = await db.prepare('SELECT job, lease_until FROM aikahub_jobs ORDER BY next_at LIMIT 500').all(); return results.map((r) => ({ ...JSON.parse(r.job), leaseUntil: r.lease_until })); }, // atomic: exactly one worker gets meta.changes === 1 async claim(key, now, leaseUntil) { const r = await db.prepare('UPDATE aikahub_jobs SET lease_until = ?1 WHERE key = ?2 AND lease_until <= ?3').bind(leaseUntil, key, now).run(); return r.meta.changes === 1; }, }); ``` Job keys contain the member's `sub`: do not log them. ### 5. Cloud saves (1.1.0, scope `save`) Ask for the `save` scope (`scopes: ['profile', 'save']`). Each game gets up to **4 slots per member** (`main` + 3 named, `[a-z0-9-]{1,32}`), each a **JSON object ≤ 64 KB**, at most **2 MB per member across all games**. A game only ever sees its own saves. The easy way is the helper — it keeps a guest save, migrates it on login, holds the "one active session" lock and flushes on exit: ```js const save = hub.cloudSave({ slot: 'main', // optional: when this device's save and the account save differ, the ACCOUNT wins unless you (the player) choose // 'local' here. `suggested` is only a hint (higher `progress`). Only 'local' replaces the account save (replace: true), // and the Hub then keeps the replaced one in the reserved 'backup' slot. resolveConflict: async ({ local, remote, suggested }) => ((await askPlayer(local, remote, suggested)) ? 'local' : 'remote'), onLockLost: (why) => showOverlay(why === 'taken_over' ? 'You continued on another device.' : 'Opened elsewhere.'), }); try { await save.start(); // tab lock (Web Locks) + Hub lease (90 s, heartbeat every 30 s) — call after login (stop() + start() when the member changes) } catch (e) { if (e.code !== 'locked') throw e; // "You're playing on another device — continue here?" if (await askTakeOver()) await save.start({ takeover: true }); } const r = await save.sync(); // { source: 'empty' | 'local' | 'remote', data, rev, conflict, backup } if (r.conflict) toast('We loaded your account save. This device’s progress is set aside — you can switch to it.'); startGame(r.data); save.stage(state, { progress: state.day }); // every frame/tick is fine: local at once, Hub on flush()/exit setInterval(() => save.flush(), 30_000); await save.save(state, { progress: state.day }); // or right now (e.g. after a level) save.backup(); // the side that lost the last merge (never discarded) … await save.restoreBackup(); // … swapped in on the player's explicit request (the current one becomes the backup) save.history(); // the last 3 local states that were overwritten from the account // shared computer: remove this game's local copies when the player logs out await hub.logout({ purge: true }); // or save.clearLocal() / save.clearLocal({ everyone: true }) ``` With a custom `storage` (not `localStorage`), `hub.logout({ purge: true })` cannot see it — call `save.clearLocal({ everyone: true })` yourself. If the account save was deleted on another device while this device still has unsent changes, the next `sync()` uploads them as a new save (unsent local progress wins over a remote delete — nothing is lost; delete again if that was meant). The helper's state (rev, lease, pending save) is bound to the member who was logged in at `sync()`: after a logout or a different member logging in, `save()` / `flush()` throw `session_changed` (or `not_synced`), `stage()` returns `false` and the exit flush sends nothing — call `sync()` again. Your own unsent changes (offline, closed tab) are uploaded on the next `sync()` only if the account save has not changed meanwhile; otherwise the account wins and they are set aside. The account list (`hub.saves.list()`) shows only this game's usage (`usage.bytes`) and a coarse `usage.full` flag, plus `backup` (the reserved slot: read / delete only, not one of the 4 slots, counts toward the 2 MB). Rules the Hub enforces (they came from real data-loss bugs in Rókafalu, so the codes are distinct on purpose): - Every write needs `If-Match: ` (`0` = "there is no save yet") — no blind overwrite (`428 rev_required`, `409 rev_conflict` with `details.rev`). - `saveId` (which world/run this is): a different one in the account → `409 other_save`; `progress` (your monotonic progress number): lower than the account's → `409 stale_progress`. Both need an explicit `replace: true`. - Lock: while another session holds a live lease, writes get `423 locked`; after a takeover the old session gets `423 taken_over` and must stop (the helper does); an expired lease nobody took is renewed (`lease_expired`, transparent). - `413 save_too_large` (> 64 KB), `413 quota_exceeded` (2 MB per member), `409 slot_limit` (4 slots). - Disconnecting your game keeps its saves for 30 days (reconnecting brings them back), then they are deleted; deleting the AikaHub account deletes them at once. Low level: `hub.saves.get/put/remove/list/lock/unlock/beacon`. From your server (the member must have granted `save` to your game): `server.getSave(sub, slot)`, `server.putSave(sub, slot, data, { rev })`, `server.deleteSave(sub, slot)`, `server.listSaves(sub)`. ### 6. Leaderboards (1.2.0, scope `scores`) Your game declares its boards (Developer console → Leaderboards, or the `boards` array of `aikahub.config.json`): `{ key, name: { hu, en?, de? }, sort: 'higher' | 'lower', format: 'points' | 'time_ms' | 'number', categories?: [...], trust: 'client' | 'server', reset: 'none' | 'weekly' | 'monthly', min?: 0, max }`. While your client is in development, scores go to a **sandbox** that only you and your testers see; it is cleared when the game goes live on the Playground. Changes to a live game's boards are reviewed, like achievements. ```js const hub = createClient({ clientId, redirectUri, scopes: ['profile', 'scores'] }); const r = await hub.scores.submit('high', 1234, { category: 'mobile' }); // { best, improved, rank, status } const top = await hub.scores.top('high', { category: 'mobile', period: 'current', limit: 10 }); // public when logged out const me = await hub.scores.me('weekly'); // { rank, value, status, around: [... ±5, your row has me: true] } ``` - Only each member's **best** per board × category × period is kept (`sort` decides what "best" means). A weekly board resets on Monday 00:00 UTC (ISO weeks, `2026-W46`); `period: 'previous'` reads last week / month. - Values: finite numbers, whole for `points` and `time_ms`; below `min` → `400 score_out_of_range`; above `max` on a `client` board → `400 score_out_of_range` (impossible value). A `server` board only takes scores from your server (`server.submitScore(sub, board, value, { category })`); from the browser it answers `403 server_key_required`. - Unusual results (above `max` on a server board, or a statistical outlier) are **held for review**: `status: 'review'`, not public until a moderator approves. You (the owner) and your testers never appear on your live boards (`status: 'hidden'`), the same rule as "no XP from your own game". - Entries show nickname, avatar and level only (never an id or e-mail); members can choose to appear anonymously. - Limits: 120 submissions per member per game per hour (`429 rate`); `top` ≤ 100 rows, cached for 30 s. From your server: `server.submitScore(sub, board, value, { category })`, `server.scoreRank(sub, board, opts)`, `server.topScores(board, opts)`; or durable: `server.queue().enqueue('score', { sub, board, value, category })`. ### 7. Visits + preset gifts (1.4.0, scope `visits`) Other players can visit your member's home in your game and leave a gift from **your preset list** — there is no free text anywhere. Declare the gifts in the Developer console → Gifts (or the `gifts` array of `aikahub.config.json`): `{ key, name: { hu, en?, de? } }`, and for pre-written cards `{ key: 'note-…', name, text: { hu, en?, de? } }`. Like boards, a development client uses the draft in a **sandbox** (you + testers), and changes to a live game are reviewed. ```js const hub = createClient({ clientId, redirectUri, scopes: ['profile', 'visits'] }); await hub.visits.publish({ furniture, garden, doing: 'fishing' }); // ≤ 16 KB JSON, at most once per 5 minutes const { homes } = await hub.visits.street(); // 6 neighbours: [{ handle, nickname, avatar, avatarUrl, level, updatedAt, followed }] const house = await hub.visits.visit(homes[0].handle); // { data, character, nickname, level, counted, … } — validate data yourself await hub.visits.gifts.send(homes[0].handle, 'note-thanks'); // { delivered, sentToday } const { gifts } = await hub.visits.gifts.inbox(); // [{ id, key, at, from: { handle, nickname, … } }] await hub.visits.gifts.ack(gifts.map((g) => g.id)); await hub.visits.settings.set({ visibility: 'followers' }); // 'all' (default) | 'followers' | 'none' const { visitors } = await hub.visits.stats(); // today's distinct visitors const { optedIn } = await hub.visits.overview(); // 1.4.1: true when the member's grant includes `visits` ``` Errors carry the Hub's extra fields in `AikaHubError.details` (1.4.1: on the same-origin path too): ```js try { await hub.visits.publish(snapshot); } catch (e) { if (e.code === 'publish_too_soon') scheduleAt(e.details.nextPublishAt); // also e.details.retryAfter / e.retryAfter (seconds) else if (e.code === 'invalid_snapshot') console.warn(e.details?.reason); // same-origin: 'depth' | 'string' | 'key' | 'markup' else throw e; } ``` | Error | `details` | | --- | --- | | `429 publish_too_soon` | `nextPublishAt`, `retryAfter` | | `429 rejoin_limit` (same-origin) | `rejoinAt` (next UTC day), `retryAfter` | | `400 invalid_snapshot` (same-origin) | `reason` | | `409 already_gifted` / `429 gift_limit` | `limits`, `sentToday` (gift_limit) | - The snapshot is **opaque** to the Hub (only size and JSON shape are checked): validate it with your schema when reading. - The Hub adds the host's public profile and Karakterem character (`character`, filtered like the explorer template: never Aika, never a licence that forbids peaceful games) — your game cannot forge them. - Other members are only known by an opaque **per-game `handle`**; you never get their `sub`, id or e-mail, and a handle from another game opens nothing in yours. - Visibility: `all` = every member who plays your game with `visits`; `followers` = only people who follow the host; `none`. Blocks are respected both ways; guests can never visit. - Limits: 1 gift per sender → host per day, 5 sent per day, 30 received per host per day (`delivered: false` above that); a visit counts once per visitor per day. The host gets at most one bell notification per day about visits and gifts. - Disconnecting the game (or re-authorising without `visits`) deletes the member's home, settings and gifts immediately. - From your server (game key): `server.publishHome(sub, data)`, `server.visitOverview(sub)`, `server.giftInbox(sub)`, `server.ackGifts(sub, ids)`. Street, visiting, sending gifts and settings need the member's own token (`403 user_token_required`). ### 8. Presence — "playing now" (1.5.0, scope `presence`) Shows "playing now" on the member's AikaHub profile. It is **on by default** for every member, seen **only by logged-in members** (never by guests or through a public API), and the member can turn it off in AikaHub Settings — then the Hub accepts your heartbeats but stores nothing. Your game's AikaHub page shows only an anonymous, rounded count ("5+ members playing now" — 5+, 10+, 25+; nothing below 5; your own and your testers' sessions never count). **Policy:** send presence only from the player's own client while they actually play. Keeping members "online" from a server (or by any other means) behind their back is a policy violation and can get your client's `presence` scope revoked. ```js const hub = createClient({ clientId, redirectUri, scopes: ['profile', 'presence'] }); const p = hub.presence.start({ state: 'menu' }); // a heartbeat now, then every ~50 s while the tab is visible p.setState('playing'); // 'menu' | 'playing' | 'idle' — no free text await p.stop(); // stop + clear (also sent as a keepalive DELETE on pagehide) // or by hand: await hub.presence.heartbeat('playing'); await hub.presence.leave(); ``` - The Hub keeps a member "playing" for ~90 s after the last heartbeat; send one every 45–60 s (`start()` does this, pauses while the page is hidden, and stops by itself on `401` / `403` / a final error — errors go to `onError`, never thrown). - One row per member — the last heartbeat wins (playing two games at once shows the latest). Same game + state within 30 s is not rewritten (`stored: false`). `visible: false` means the member turned presence off. - Other members see only the game's title on the profile — never the state or a timestamp. Blocks are respected both ways; banned and bot accounts never show. - A development client (sandbox) gets `{ stored: false, sandbox: true }`: test players never show as really playing. - Presence needs the **member's own token**: the game key (Basic) gets `403 user_token_required` — a server can't keep a member "online" behind their back. - Disconnecting the game (or re-authorising without `presence`) clears the member's presence for it immediately. ## Games hosted on aikahub.com (same-origin) ```js import { createSameOriginClient } from '/sdk/1.5.0/same-origin.js'; const hub = createSameOriginClient({ game: 'lidercfeny' }); const { user } = await hub.start(); // who is logged in + uploads unlocks collected as a guest const r = await hub.unlock('first-wave'); // never throws: { status: 'done' | 'queued' | 'dropped' } const perks = await hub.entitlements(); // ['lidercfeny:extra-card'] ``` 1.4.0: Hub-hosted games on the visits list (Engawa Days: `game: 'aikalife'`) get the same `hub.visits` API on the cookie session (`/api/games//visits…`). There is no consent screen on this path: **ask the member in-game first**, then send the first `publish(data, { consent: true })` (or `settings.set({ visibility, consent: true })`) — without it the Hub answers `403 consent_required`. `hub.visits.leave()` opts out (everything is deleted). Errors are thrown as `AikaHubError` (`code` = the Hub's code; 1.4.1: the Hub's error params in `details`, see the table above). 1.4.1: `overview()` returns `optedIn` (has the member consented in this game?) and, when true, `consentAt` — use it to decide whether to ask before the first publish. 1.5.0: `hub.presence` (the same API as above) on the cookie session (`/api/games//presence`) for the Hub's listed games (`lidercfeny`, `aikalife`). The Hub frame already sends presence while the member has the game open on aikahub.com, so a Hub-hosted game only needs `hub.presence.start({ state })` / `setState()` if it wants to report `menu` / `idle`. Cookie session, existing `/api` routes, client-trust achievements only. Guest unlocks wait in localStorage (only ids, never tokens) and are sent on the next logged-in start: up to 10 successes per start (the Hub allows 30 per hour per game), at most 30 attempts. Final errors — including `404 unknown_achievement`, since definitions ship with the Hub — drop the entry; a transient error moves it to the back of the queue, and after 8 tries it is dropped. Untagged (guest) entries go to whoever logs in next on that browser. Entries queued while a member was logged in carry a short hash of that member's nickname and are only sent for them (other members skip them; they are dropped after 30 days). ## Security notes - **State + PKCE (S256) are mandatory** and handled for you. The state and verifier live in `sessionStorage` for one tab, are single-use and expire after 10 minutes. - **Tokens live in memory** by default. `storage: 'session'` keeps them in `sessionStorage` so a reload does not log the player out — but then any XSS in your game can read them. The SDK never writes tokens to `localStorage`. - **Refresh is single-flight**: per instance, and across instances that share the stored session through `navigator.locks` (where available); inside the lock the stored tokens are re-read and adopted if another instance already rotated them. `logout()` waits for an in-flight refresh and revokes the newest token; a refresh that finishes after a logout or a new login is discarded (`session_changed`). Known limit: a *duplicated* browser tab copies `sessionStorage` and then lives on its own — a refresh in one tab makes the other tab's refresh token stale, and the Hub treats its reuse as theft (the family is revoked, the player logs in again). A short server-side grace period for refresh tokens is a Hub TODO. - **No open redirect**: the SDK never navigates after the callback; `returnTo` must be a same-origin relative path. - **`baseUrl`** must be https (http only for localhost). With `discovery: true` every endpoint must be on that origin. - The **game key** belongs on your server only. `createServerClient` refuses to run in a browser window or a browser worker (`importScripts`; an unknown `WorkerGlobalScope` — Cloudflare Workers and Deno are allowed), does not expose the key as a property, and the SDK logs nothing — no key, no `Authorization` header, no `sub`. - Always verify on your server that an access token was issued to your game (`verifyAccessToken` checks `aud`). - The `sub` is pairwise: the same member has a different `sub` in every game. The Hub never shares email addresses. ## Errors Every failure is an `AikaHubError` with `code`, `status` (0 for network / client-side checks) and `final` (`true` = retrying will not help). `classify(error)` returns `'done' | 'drop' | 'retry'`. | code | status | meaning | |---|---|---| | `invalid_token` | 401 | access token expired or revoked (the browser client refreshes once automatically) | | `invalid_client` | 401 | wrong game key (retried: may be a key rotation) | | `invalid_grant` | 400 | code or refresh token invalid / reused — log in again | | `insufficient_scope` | 403 | the member did not grant this scope | | `wrong_game` | 403 | the achievement belongs to another game | | `server_key_required` | 403 | server-trust achievement unlocked without the game key | | `not_linked` | 409 | the member unlinked your game — drop it | | `unknown_achievement` | 404 | not (yet) defined on the Hub | | `rate` | 429 | rate limited; see `retryAfter` | | `state_mismatch`, `login_expired` | 0 | callback did not match a login started in this tab | | `access_denied` | 0 | the member pressed "No" | | `wrong_audience` | 401 | the access token was issued to a different game | | `session_changed` | 0 | a refresh finished after logout / a new login; its result was discarded | | `network_error`, `timeout` | 0 | retry later | | `rev_required` | 428 | save write without `If-Match` (rev) | | `rev_conflict` | 409 | the save changed meanwhile — `details.rev` is the current one; read it again | | `other_save` / `stale_progress` | 409 | a different `saveId` / lower `progress` than the account's save — needs `replace: true` | | `slot_limit` | 409 | more than 4 save slots in this game | | `locked` / `taken_over` / `lease_expired` | 423 | another session plays now / this session was taken over / your lease expired | | `save_too_large` / `quota_exceeded` | 413 | save > 64 KB / member over 2 MB across all games | | `no_save` | 404 | empty slot (`get()` returns `null`) | ## License and agreement The SDK is licensed under the **AikaHub SDK License** (not open source): https://aikahub.com/developers/sdk-license (see `LICENSE.md`; all versions with SHA-256 fingerprints: https://aikahub.com/developers/legal). Connecting a game to AikaHub also requires the **AikaHub Developer Agreement**, accepted in the Developer console (https://aikahub.com/developers/console). Both are in Hungarian and English; the Hungarian version controls. ## Roadmap - Done (1.1.0, Hub Platform API 2a): cloud saves, save lock (one active session), guest → account save migration. - Done (1.2.0, Hub Platform API 2b): server leaderboards (`scores`), weekly / monthly periods, categories, sandbox. - Done (1.4.0, Hub Platform API 2d): visits (`visits`) — home snapshot, street, preset gifts, inbox; same-origin too. - Done (1.4.1): `optedIn` / `consentAt` in the visits overview; same-origin errors carry `details` (nextPublishAt, rejoinAt, reason, …). - Done (1.5.0, Hub Platform API 2c): presence (`presence`) — "playing now" heartbeats with Page Visibility; same-origin too. - TODO: `same-origin` leaderboards in the SDK (aikahub.com games call `POST /api/scores/submit` directly today). - TODO: `same-origin` cloud saves (games on aikahub.com use their own `/api` routes today). - Done (AikaHub 11.41): self-service client registration and key-hash upload in the Developer console. - TODO: publish to npm (under the AikaHub SDK License, from 1.0.1 on). `/sdk/1.0.0/` stays online unchanged and remains available under MIT, as published. ## Development ```sh (cd packages/aikahub-sdk && npm test) # unit tests (mocked fetch) node --test tests/sdk-*.test.mjs # against the Hub's real handlers + hosting checks (Node 22) npm run sdk:build # rebuild public/sdk/v1/ and public/sdk// ``` See [CHANGELOG.md](./CHANGELOG.md). ======================================================================== # @aikahub/sdk 1.5.0 — TypeScript types ======================================================================== --- # types/index.d.ts // @aikahub/sdk — everything in one entry. export * from './core.js'; export { createClient, safeReturnTo } from './browser.js'; export type { ClientOptions, AikaHubClient, Session, LoginOptions, SaveApi, SaveSide, CloudSaveOptions, CloudSave, SyncResult, ScoresApi } from './browser.js'; export { createCloudSave, resolveSaves, suggestSave } from './browser.js'; export { createSameOriginClient, ownerTag } from './same-origin.js'; export type { SameOriginOptions, SameOriginClient, SameOriginUser, SameOriginUnlock, UnlockedItem } from './same-origin.js'; export { createServerClient, createRetryQueue, memoryStore, backoff, looksLikeBrowser } from './server.js'; export type { ServerClientOptions, AikaHubServerClient, Job, JobStore, RetryQueueOptions, RetryQueue, AttemptResult } from './server.js'; --- # types/browser.d.ts // @aikahub/sdk/browser — public PKCE client. import type { Scope, UserInfo, Character, UnlockResult, EntitlementsResult, SaveData, SaveList, SaveRecord, SaveWriteOptions, SaveWriteResult, SaveLease, ScoreOptions, ScoreQuery, ScoreTop, ScoreSubmitResult, ScoreMe, VisitsApi, PresenceApi } from './core.js'; export { AikaHubError } from './core.js'; export interface ClientOptions { clientId: string; /** Exactly as registered for your game. */ redirectUri: string; /** Default: ['profile']. */ scopes?: Scope[] | string; /** Default: 'https://aikahub.com'. https only (http allowed for localhost). */ baseUrl?: string; /** * Where tokens live. 'memory' (default): gone on reload. 'session': sessionStorage, survives reloads in this tab, * but any XSS in your game can read it. Tokens are never written to localStorage. */ storage?: 'memory' | 'session'; /** Read endpoints from the discovery document (default false: derived from baseUrl). */ discovery?: boolean; fetch?: typeof fetch; /** Per-request timeout, default 15000 ms. */ timeoutMs?: number; } export interface Session { sub: string | null; scope: string[]; expiresAt: number; } export interface LoginOptions { /** A same-origin relative path ("/play") handed back by handleCallback(). Anything else is ignored. */ returnTo?: string; /** Override the client's scopes for this login. */ scopes?: Scope[] | string; } export interface AikaHubClient { readonly clientId: string; readonly baseUrl: string; /** Builds the authorize URL and stores state + PKCE verifier in sessionStorage. */ authorizeUrl(opts?: LoginOptions): Promise; /** Redirects the browser to the Hub's login/consent page. */ login(opts?: LoginOptions): Promise; /** * Call on the redirectUri page. Returns null if the URL is not a callback. Verifies state, exchanges the code * (with the PKCE verifier) and keeps the tokens. Removes code/state from the address bar by default. * Throws AikaHubError: state_mismatch, login_expired, access_denied, invalid_grant, … */ handleCallback(url?: string, opts?: { cleanUrl?: boolean }): Promise<(Session & { returnTo: string | null }) | null>; /** * Rotate tokens now. Single-flight per instance, and across instances that share the stored session via * navigator.locks when available; inside the lock the stored tokens are re-read and adopted if another instance * already rotated them. Rejects with `session_changed` if logout / a new login happened meanwhile. * Note: a duplicated browser tab copies sessionStorage and then diverges — refreshing in one tab invalidates the other. */ refresh(): Promise; /** Waits for an in-flight refresh, then revokes the newest refresh-token family at the Hub (best effort) and forgets the tokens. */ /** 1.1.0: `{ purge: true }` also removes this game's local cloud-save copies (shared computers). */ logout(opts?: { purge?: boolean }): Promise; /** Alias of logout(). */ revoke(opts?: { purge?: boolean }): Promise; /** A valid access token (refreshes when close to expiry). Send it to YOUR game server, which verifies it. */ getAccessToken(): Promise; isLoggedIn(): boolean; session(): Session | null; onChange(fn: (s: Session | null) => void): () => void; /** GET /oauth/userinfo */ me(): Promise; /** GET /oauth/character — needs the `character` scope. */ character(): Promise; /** POST /oauth/achievements/unlock — `client`-trust achievements only (≤ 50 XP); needs `achievements`. */ unlock(id: string): Promise; /** GET /oauth/entitlements — needs `achievements`. */ entitlements(): Promise; /** 1.1.0: low-level cloud-save calls (`save` scope). */ readonly saves: SaveApi; /** 1.1.0: guest → account migration, lock, exit flush. */ cloudSave(opts?: CloudSaveOptions): CloudSave; /** 1.2.0: server leaderboards (`scores` scope for submit / me; top is public). */ readonly scores: ScoresApi; /** 1.4.0: visits + preset gifts (`visits` scope). */ readonly visits: VisitsApi; /** 1.5.0: presence — "playing now" on the member's AikaHub profile, seen only by logged-in members (`presence` scope). */ readonly presence: PresenceApi; } export interface ScoresApi { /** POST /oauth/scores — only the member's best is kept. `server`-trust boards answer 403 server_key_required (use the server client). */ submit(board: string, value: number, opts?: ScoreOptions): Promise; /** GET /oauth/scores/ — logged in: with the token (needed for a developer client's sandbox); logged out: public. */ top(board: string, opts?: ScoreQuery): Promise; /** GET /oauth/scores//me — your rank and the entries around you. */ me(board: string, opts?: Omit): Promise; } export interface SaveApi { list(): Promise; /** null when the slot is empty. */ get(slot?: string): Promise | null>; put(slot: string, data: SaveData, opts: SaveWriteOptions): Promise; /** keepalive PUT for `pagehide` (current token, no refresh, body < 60 KB). false: not sent. */ beacon(slot: string, data: SaveData, opts: Omit): boolean; remove(slot: string, opts?: { rev?: number | '*'; lease?: string }): Promise<{ ok: true; sub: string; slot: string; rev: number }>; /** Take / renew (`lease`) / steal (`takeover`) the one-active-session lease (≈ 90 s). 423 locked / taken_over. */ lock(opts?: { lease?: string; takeover?: boolean }): Promise; unlock(lease: string): Promise<{ ok: true }>; } /** A local or account save as the merge sees it. */ export interface SaveSide { data: T; saveId?: string | null; progress?: number | null; /** local: ms */ savedAt?: number; /** account: ISO time */ updatedAt?: string; rev?: number | null; } export interface CloudSaveOptions { /** Default 'main'. */ slot?: string; /** Decide when this device's save and the account save differ. Default (undefined): the account wins; 'local' replaces it (explicit). */ resolveConflict?: (c: { local: SaveSide; remote: SaveSide; suggested: 'local' | 'remote' }) => 'local' | 'remote' | undefined | Promise<'local' | 'remote' | undefined>; /** Web Locks + Hub lease (default true). */ lock?: boolean; heartbeatMs?: number; onLockLost?: (reason: 'taken_over' | 'locked' | 'tab') => void; /** keepalive PUT on pagehide (default true). */ flushOnExit?: boolean; /** Default localStorage; null = no local storage. */ storage?: Storage | null; } export interface SyncResult { source: 'empty' | 'local' | 'remote'; data: T | null; rev: number | null; /** true: both sides existed and differed — the loser is in backup(). */ conflict: boolean; reason: string; backup: (SaveSide & { from: 'guest' | 'local' | 'remote' | 'swap'; at: number }) | null; } export interface CloudSave { readonly slot: string; /** Take the tab lock and the Hub lease. Throws AikaHubError 'locked' when another tab/device plays — ask, then start({ takeover: true }). */ start(opts?: { takeover?: boolean }): Promise<{ lease: boolean }>; stop(): Promise; sync(): Promise>; local(): (SaveSide & { dirty?: boolean }) | null; save(data: T, meta?: { saveId?: string; progress?: number }): Promise; /** false: refused (logged out / another member since sync()). */ stage(data: T, meta?: { saveId?: string; progress?: number }): boolean; flush(): Promise; flushOnExit(): boolean; backup(): (SaveSide & { from: string; at: number }) | null; /** Swap the backup in (the current one becomes the backup — nothing is lost). */ restoreBackup(): Promise<{ data: T; rev: number | null } | null>; discardBackup(): void; /** The last 3 local states overwritten from the account (newest first). */ history(): Array & { replacedAt: number }>; /** Remove local copies on this computer: this member's + the guest's for this slot, or `{ everyone: true }`: all of this game's. */ clearLocal(opts?: { everyone?: boolean }): number; status(): { rev: number | null; lease: boolean; lost: string | null; pending: boolean; loggedIn: boolean; boundTo: string | null }; } export declare function createCloudSave(hub: AikaHubClient, opts?: CloudSaveOptions): CloudSave; export declare function resolveSaves( local: SaveSide | null, remote: SaveSide | null, opts?: { choice?: 'local' | 'remote'; unchanged?: boolean }, ): { winner: 'none' | 'local' | 'remote'; upload: boolean; replace: boolean; backup: 'local' | 'remote' | null; conflict: boolean; reason: string }; /** A hint only: 'local' when both have `progress` and the local one is higher, else 'remote'. */ export declare function suggestSave(local: SaveSide | null, remote: SaveSide | null): 'local' | 'remote'; export declare function createClient(opts: ClientOptions): AikaHubClient; /** Returns p if it is a safe same-origin relative path, else null. */ export declare function safeReturnTo(p: unknown): string | null; --- # types/core.d.ts // @aikahub/sdk — shared types (hand-written). export declare const VERSION: '1.5.0'; export declare const DEFAULT_BASE_URL: 'https://aikahub.com'; export declare const KNOWN_SCOPES: readonly ['profile', 'character', 'achievements', 'save', 'scores', 'visits', 'presence']; export type Scope = 'profile' | 'character' | 'achievements' | 'save' | 'scores' | 'visits' | 'presence' | (string & {}); /** Outcome of one attempt: finished, give up for good, or try again later. */ export type Classification = 'done' | 'drop' | 'retry'; /** Every error the SDK throws. */ export declare class AikaHubError extends Error { constructor(code: string, init?: { status?: number; message?: string; description?: string; final?: boolean; retryAfter?: number }); readonly name: 'AikaHubError'; /** Machine-readable code: the Hub's `error` / `code` (e.g. `invalid_token`, `not_linked`, `rate`), or an SDK code * (`network_error`, `timeout`, `state_mismatch`, `login_required`, `session_changed`, `wrong_audience`, …), or `http_`. */ readonly code: string; /** HTTP status; 0 for network errors and client-side checks. */ readonly status: number; /** The Hub's human-readable description (may be Hungarian), or ''. */ readonly description: string; /** true: retrying will not help (409 not_linked, 403, 400, state mismatch…). */ readonly final: boolean; /** Seconds from a `Retry-After` header (429), when present; since 1.4.1 otherwise the error's `details.retryAfter`. */ readonly retryAfter?: number; /** * 1.1.0: extra fields of a save error (409 rev_conflict → rev, updatedAt; other_save → saveId; 423 locked → lockExpiresAt; …). * 1.4.1: also the visits errors (429 publish_too_soon → nextPublishAt, retryAfter; 429 rejoin_limit → rejoinAt, retryAfter; * 400 invalid_snapshot → reason; 409 already_gifted / 429 gift_limit → limits, sentToday) — on the OAuth path and on the * same-origin (cookie) path alike. Only allow-listed keys with simple values; absent when the Hub sent none. */ readonly details?: AikaHubErrorDetails; } export interface AikaHubErrorDetails { rev?: number; updatedAt?: string; saveId?: string; progress?: number; lockExpiresAt?: string; limit?: number; /** 1.4.1: ISO time of the next allowed publish (429 publish_too_soon). */ nextPublishAt?: string; /** 1.4.1: seconds to wait (429 publish_too_soon / rejoin_limit). */ retryAfter?: number; /** 1.4.1: ISO time from which the member can rejoin visits (429 rejoin_limit; the next UTC day). */ rejoinAt?: string; /** 1.4.1: why the snapshot was refused (400 invalid_snapshot on the same-origin path: 'depth' | 'string' | 'key' | 'markup'). */ reason?: string; /** 1.4.1: gifts sent today (429 gift_limit). */ sentToday?: number; /** 1.4.1: the daily gift limits (409 already_gifted / 429 gift_limit). */ limits?: Record; } /** Classify a response, a `{status}` object or an error. 2xx → done; 401/404/408/425/429/5xx/network → retry; other 4xx → drop. */ export declare function classify(x: AikaHubError | Response | { status: number; code?: string } | unknown): Classification; export interface Endpoints { authorize: string; token: string; userinfo: string; character: string; unlock: string; entitlements: string; /** 1.1.0: cloud saves (`save` scope). */ save: string; /** 1.2.0: leaderboards (`scores` scope). */ scores: string; /** 1.4.0: visits + preset gifts (`visits` scope). */ visits: string; /** 1.5.0: presence — "playing now" (`presence` scope). */ presence: string; revoke: string; } /** Fetch `/.well-known/oauth-authorization-server`; every endpoint must be on `baseUrl`'s origin. */ export declare function discover(opts?: { baseUrl?: string; fetch?: typeof fetch }): Promise<{ endpoints: Endpoints; scopes: string[]; document: Record }>; export interface PkcePair { verifier: string; challenge: string; method: 'S256'; } export declare function createPkcePair(): Promise; /** BASE64URL(SHA-256(verifier)) */ export declare function s256(verifier: string): Promise; /** Cryptographically random base64url string (default 32 bytes → 43 chars). */ export declare function randomString(bytes?: number): Promise; export type Localized = { hu: string; en: string; de: string }; /** GET /oauth/userinfo — never contains an email address. */ export interface UserInfo { /** Pairwise id: stable for this member in YOUR game, different in every other game. 32 hex chars. */ sub: string; /** The client id the token was issued to. Your server must check it equals your client id. */ aud: string; client_id: string; scope: string; nickname: string; avatar: string; avatarUrl: string; level: number; profileColor: string; profileUrl: string; } export interface CharacterLicense { name: string; violent: boolean; sexual: boolean; commercial: boolean; } /** The member's Karakterem VRM character. */ export interface Character { sub?: string; kind: 'roster' | 'custom'; slug: string | null; name: string; /** Absolute (OAuth) or Hub-relative (same-origin) URL of the .vrm file. CORS-enabled. */ vrmUrl: string; thumbUrl: string | null; license: CharacterLicense; mature: boolean; vrmVersion: 0 | 1; encoding?: string; credit?: unknown; /** Where the character may be used: peaceful games always, arena (violent) only if the license allows. */ games: { peaceful: boolean; arena: boolean }; [extra: string]: unknown; } export interface Reward { type: 'badge' | 'sticker' | 'color' | 'frame' | 'character' | 'entitlement'; value: string; } export interface UnlockResult { ok: true; sub: string; id: string; /** false when the member already had it (idempotent: no XP, no reward again). */ new: boolean; xp: number; unlockedAt: string; reward: Reward | null; rewards: Reward[]; /** Entitlement values the member now holds in your game, e.g. `['hyperscales:boost']`. */ entitlements: string[]; } export interface Entitlement { value: string; achievement: string; grantedAt: string; label: Localized | null; } export interface EntitlementsResult { sub: string; game: string | null; entitlements: Entitlement[]; } // ——— 1.1.0: cloud saves ——— export declare const SAVE_MAX_BYTES: 65536; /** Save data: any JSON object (≤ 64 KB as UTF-8 JSON). */ export type SaveData = Record; export interface SaveMeta { slot: string; /** Strictly increasing per slot; send it back as `rev` (If-Match) on the next write. */ rev: number; updatedAt: string; bytes: number; saveId: string | null; progress: number | null; } export interface SaveRecord extends SaveMeta { sub: string; data: T; } export interface SaveList { sub: string; slots: SaveMeta[]; /** This game's bytes only (incl. the backup slot) + a coarse flag: one more full-size save would not fit. */ usage: { bytes: number; full: boolean }; /** The Hub's reserved slot: the last save replaced with `replace: true` (read / delete only). */ backup: (SaveMeta & { of: string | null }) | null; limits: { slotBytes: number; slots: number; userBytes: number; leaseTtl: number }; lock: { active: boolean }; } export interface SaveWriteOptions { /** The rev you last read; 0 = "there is no save yet". Required. */ rev: number; /** Which save this is (world / run id). A different saveId in the account → 409 other_save unless `replace`. */ saveId?: string; /** Your monotonic progress number. Lower than the account's → 409 stale_progress unless `replace`. */ progress?: number; /** Explicitly overwrite another saveId / a higher progress. */ replace?: boolean; /** The session lease from lock(). */ lease?: string; } export interface SaveWriteResult { ok: true; sub: string; slot: string; rev: number; updatedAt: string; bytes: number; /** Set when an explicit replace moved the previous save into the reserved 'backup' slot. */ backup?: { slot: 'backup'; of: string }; lease?: { expiresAt: string }; } export interface SaveLease { lease: string; expiresAt: string; ttl: number; takenOver: boolean; } export declare function checkSlot(slot?: string): string; // ——— 1.2.0: leaderboards ——— export interface ScoreOptions { /** Required when the board declares categories (e.g. 'mobile' | 'desktop'). */ category?: string; } export interface ScoreQuery extends ScoreOptions { /** 'current' (default), 'previous', or an exact key: '2026-W46' (weekly) / '2026-11' (monthly). Ignored on never-resetting boards. */ period?: 'current' | 'previous' | (string & {}); /** 1–100, default 10. */ limit?: number; } export interface PublicBoard { key: string; name: { hu?: string; en?: string; de?: string }; sort: 'higher' | 'lower'; format: 'number' | 'time_ms' | 'points'; categories: string[]; trust: 'client' | 'server'; reset: 'none' | 'weekly' | 'monthly'; /** The current period key, or null. */ period: string | null; /** When the current period ends (ISO), or null. */ resetsAt: string | null; } /** A public entry: nickname / avatar / level — or anonymous. Never an id or an e-mail. */ export type ScoreEntry = | { rank: number; value: number; nickname: string; avatar: string; level: number; me?: true } | { rank: number; value: number; nickname: null; avatar: null; level: null; anonymous: true; me?: true }; export interface ScoreTop { board: PublicBoard; category: string | null; period: string | null; /** Set for a developer client: the sandbox (owner + testers only). */ sandbox?: true; entries: ScoreEntry[]; total: number; } export interface ScoreSubmitResult { ok: true; sub: string; board: string; category: string | null; period: string | null; value: number; /** The member's stored best on this board / category / period. */ best: number; improved: boolean; /** 'review': flagged for a moderator (not public yet); 'hidden': the game's owner / tester (never public on the live board). */ status: 'ok' | 'review' | 'hidden'; rank: number | null; sandbox?: true; insider?: true; } export interface ScoreMe { sub: string; board: string; category: string | null; period: string | null; sandbox?: true; value: number | null; rank: number | null; status: 'ok' | 'review' | 'hidden' | null; /** Up to 5 above and 5 below; your own row has `me: true`. */ around: ScoreEntry[]; } export declare function checkBoard(board: string): string; // ——— 1.4.0: visits + preset gifts ——— export type Visibility = 'all' | 'followers' | 'none'; export type VisitReportReason = 'inappropriate' | 'offensive' | 'spam'; /** Another member as the Hub shows them: an opaque per-game handle + public profile. Never an id, an e-mail or a `sub`. */ export interface VisitProfile { handle: string; nickname: string; avatar: string; avatarUrl: string; level: number; } export interface GiftDef { key: string; name: { hu: string; en?: string; de?: string }; /** Only for `note-*` keys: the pre-written card text. */ text?: { hu: string; en?: string; de?: string }; } export interface VisitOverview { sub?: string; /** * 1.4.1: does the member take part in visits in this game? OAuth path: the grant includes `visits` (always true on a * Bearer call). Same-origin (cookie) path: the member gave their in-game consent (a visit_optins row exists). */ optedIn: boolean; /** 1.4.1, same-origin path only, when `optedIn` is true: ISO time of the member's consent. */ consentAt?: string; handle: string; visibility: Visibility; home: { updatedAt: string; bytes: number } | null; nextPublishAt: string | null; today: { day: string; visitors: number; gifts: number; sent: number }; gifts: GiftDef[]; limits: { snapshotBytes: number; publishIntervalS: number; street: number; giftsSentPerDay: number; giftsReceivedPerDay: number; giftsPerHostPerDay: number }; banned: boolean; sandbox?: true; } export interface StreetHome extends VisitProfile { updatedAt: string; followed: boolean; } export interface VisitCharacter { kind: 'roster' | 'custom'; slug: string | null; name: string; vrmUrl: string; thumbUrl: string | null; license: { name?: string; violent: boolean; sexual: boolean; commercial: boolean }; mature: boolean; vrmVersion: number; encoding: string; credit: unknown; games: { peaceful: boolean; arena: boolean }; } export interface VisitResult> extends VisitProfile { /** The host's Karakterem character (added by the Hub, cannot be forged by the game); null when none / filtered (Aika, licence). */ character: VisitCharacter | null; /** The host's snapshot — opaque to the Hub: validate it with your own schema. */ data: T; updatedAt: string; /** true the first time today this visit counted for the host. */ counted: boolean; own: boolean; followed: boolean; } export interface GiftSendResult { ok: true; /** false: the host's daily cap is full (the gift is dropped and does not use up your quota). */ delivered: boolean; reason?: 'host_full'; key: string; sentToday: number; limits: { giftsSentPerDay: number; giftsReceivedPerDay: number; giftsPerHostPerDay: number }; } export interface GiftInbox { sub?: string; gifts: Array<{ id: string; key: string; at: string; from: VisitProfile }>; } export interface VisitsApi { overview(): Promise; /** Your home snapshot (JSON object, ≤ 16 KB, at most once per 5 minutes → 429 publish_too_soon with nextPublishAt). */ /** Hub-hosted games (cookie path): the member's FIRST publish / settings.set must pass `{ consent: true }` — only after you asked them in-game (else 403 consent_required). */ publish(data: Record, opts?: { consent?: true }): Promise<{ ok: true; handle: string; updatedAt: string; bytes: number; nextPublishAt: string; sandbox?: true }>; unpublish(): Promise<{ ok: true }>; /** Up to 12 (default 6) neighbours: people you follow first, then recently active players; stable order per day. */ street(opts?: { n?: number } | number): Promise<{ day: string; homes: StreetHome[]; sandbox?: true }>; visit>(handle: string): Promise>; /** Alias of visit() (the Engawa Days proposal's name). */ get>(handle: string): Promise>; report(handle: string, reason: VisitReportReason): Promise<{ ok: true }>; gifts: { send(handle: string, key: string): Promise; inbox(): Promise; ack(ids: string | string[]): Promise<{ ok: true; acked: number }>; }; gift(handle: string, key: string): Promise; inbox(): Promise; ack(ids: string | string[]): Promise<{ ok: true; acked: number }>; settings: { get(): Promise<{ visibility: Visibility }>; set(opts: { visibility: Visibility; consent?: true }): Promise<{ ok: true; visibility: Visibility }>; }; setVisibility(visibility: Visibility): Promise<{ ok: true; visibility: Visibility }>; stats(): Promise; } export declare function checkHandle(handle: string): string; export declare function checkGiftKey(key: string): string; // ——— 1.5.0: presence ——— /** What the member is doing in your game. No free text — only these values. */ export type PresenceState = 'menu' | 'playing' | 'idle'; export declare const PRESENCE_STATES: readonly ['menu', 'playing', 'idle']; /** Recommended heartbeat interval (ms). The Hub treats a member as playing for ~90 s after the last heartbeat. */ export declare const PRESENCE_INTERVAL_MS: 50000; export declare function presenceBody(state?: PresenceState | null): { state?: PresenceState }; export interface PresenceHeartbeatResult { ok: true; /** false: the member turned presence off in their AikaHub settings — nothing is stored (keep calling; it is harmless). */ visible: boolean; /** false when throttled (same game + state within 30 s), when hidden, or in the developer sandbox. */ stored: boolean; /** Suggested heartbeat interval in seconds (50). */ interval: number; /** Seconds the Hub keeps the member "playing" after a heartbeat (90). */ ttl: number; /** Development client: accepted but never stored as real presence. */ sandbox?: true; } export interface PresenceLoop { /** Change the state ('menu' | 'playing' | 'idle'); sends a heartbeat right away. */ setState(state: PresenceState): Promise; /** Stop the heartbeats and clear the presence (leave). */ stop(): Promise; } export interface PresenceApi { /** One heartbeat (POST). Without a state the Hub keeps the previous one for the same game ('playing' for a new game). */ heartbeat(state?: PresenceState): Promise; /** The member left the game: their presence for THIS game is cleared right away. */ leave(): Promise<{ ok: true; sandbox?: true }>; /** * Automatic heartbeats: one now, then every 45–60 s (default 50 s) while the page is visible (Page Visibility); * paused while hidden, a heartbeat right on return, and a keepalive DELETE on `pagehide`. Stops by itself on a final * error, 401 or 403 (errors go to `onError`, never thrown). A new start() stops the previous loop. */ start(opts?: { state?: PresenceState; intervalMs?: number; onError?: (e: AikaHubError) => void }): PresenceLoop; /** Stop the running loop (if any) and leave. */ stop(): Promise; /** Fire-and-forget keepalive DELETE (for your own `pagehide` handler). false: nothing was sent. */ beacon(): boolean; } export declare function presenceApi(call: (method: 'POST' | 'DELETE', body?: { state?: PresenceState }) => Promise, opts?: { beacon?: () => boolean }): PresenceApi; --- # types/server.d.ts // @aikahub/sdk/server — confidential game backend (server-to-server with the game key). import type { UserInfo, UnlockResult, EntitlementsResult, Classification, SaveData, SaveList, SaveRecord, SaveWriteOptions, SaveWriteResult, ScoreOptions, ScoreQuery, ScoreTop, ScoreSubmitResult, ScoreMe, VisitOverview, GiftInbox } from './core.js'; import { AikaHubError, classify } from './core.js'; export { AikaHubError, classify }; export interface ServerClientOptions { clientId: string; /** The game's server key (20–200 chars). A secret: never ship it to a client, a build or a repository. */ clientKey: string; baseUrl?: string; discovery?: boolean; fetch?: typeof fetch; timeoutMs?: number; /** Refuses to run where `window` + `document` exist unless set. Do not set it. */ dangerouslyAllowBrowser?: boolean; } export interface AikaHubServerClient { readonly clientId: string; readonly baseUrl: string; /** Unlock an achievement (client or server trust) for the member with this pairwise sub. Idempotent. */ unlock(sub: string, id: string): Promise; entitlements(sub: string): Promise; /** Verify an access token your game client sent you: userinfo + `aud === clientId`. Throws `wrong_audience`, or `invalid_token` (final) on 401. */ verifyAccessToken(accessToken: string): Promise; /** 1.1.0 cloud saves — only for members who granted `save` to your game (else 403 insufficient_scope). */ listSaves(sub: string): Promise; /** null when the slot is empty. */ getSave(sub: string, slot?: string): Promise | null>; putSave(sub: string, slot: string, data: SaveData, opts: SaveWriteOptions): Promise; deleteSave(sub: string, slot?: string, opts?: { rev?: number | '*'; lease?: string }): Promise<{ ok: true; sub: string; slot: string; rev: number }>; /** 1.2.0 leaderboards — only for members who granted `scores`; the only way to fill a `server`-trust board. */ submitScore(sub: string, board: string, value: number, opts?: ScoreOptions): Promise; scoreRank(sub: string, board: string, opts?: Omit): Promise; /** The public top list (no key sent; a developer client's sandbox is not readable this way). */ topScores(board: string, opts?: ScoreQuery): Promise; /** 1.4.0 visits — only for members who granted `visits`; only the member's OWN home / inbox / overview (street, other homes, sending gifts and settings need the member's own token). */ visitOverview(sub: string): Promise; publishHome(sub: string, data: Record): Promise<{ ok: true; sub: string; handle: string; updatedAt: string; bytes: number; nextPublishAt: string }>; giftInbox(sub: string): Promise; ackGifts(sub: string, ids: string | string[]): Promise<{ ok: true; sub: string; acked: number }>; /** A retry queue wired to this client's unlock() (and, 1.2.0, submitScore: enqueue('score', { sub, board, value, category })). */ queue(opts?: Omit & { handlers?: RetryQueueOptions['handlers'] }): RetryQueue; toJSON(): { clientId: string; baseUrl: string }; } export declare function createServerClient(opts: ServerClientOptions): AikaHubServerClient; /** true in a browser window or a browser worker (importScripts / unknown WorkerGlobalScope). Cloudflare Workers and Deno: false. */ export declare function looksLikeBrowser(g?: typeof globalThis): boolean; export interface Job

{ /** Deterministic idempotency key, e.g. `unlock::`. Contains the sub: do not log it. */ key: string; type: string; payload: P; attempts: number; /** Epoch ms of the next attempt. */ nextAt: number; createdAt: number; /** Epoch ms until which a worker holds the job. */ leaseUntil: number; lastError: { code: string; status: number } | null; reason?: 'final' | 'max_attempts'; } /** Persistence for the queue. Implement it on D1, SQLite, Redis, KV… (put = upsert by key). */ export interface JobStore { get(key: string): Promise; put(job: Job): Promise; remove(key: string): Promise; list(): Promise; /** * Optional atomic claim: set `leaseUntil` only if the job exists and is not leased (`leaseUntil <= now`); return * whether it succeeded. Required when several processes share the store; without it the queue re-reads the job * (safe within one queue instance only). */ claim?(key: string, now: number, leaseUntil: number): boolean | Promise; } export interface RetryQueueOptions { handlers: Record Promise>; store?: JobStore; /** Default 12. */ maxAttempts?: number; /** Default 2000 ms. */ baseDelayMs?: number; /** Default 6 h. Also caps Retry-After. */ maxDelayMs?: number; /** Default 60000 ms. */ leaseMs?: number; now?: () => number; random?: () => number; onDone?: (job: Job, result: unknown) => void | Promise; onDrop?: (job: Job, error: unknown) => void | Promise; } export interface AttemptResult { /** 'skipped': another worker holds the job. */ outcome: Classification | 'skipped'; job: Job; result?: unknown; error?: unknown; } export interface RetryQueue { enqueue(type: string, payload: unknown): Promise; /** Run the due jobs (call from a cron / timer). */ process(opts?: { limit?: number }): Promise<{ done: number; retry: number; drop: number; skipped: number }>; /** Enqueue and try immediately. */ unlock(sub: string, id: string): Promise; size(): Promise; readonly store: JobStore; } export declare function createRetryQueue(opts: RetryQueueOptions): RetryQueue; export declare function memoryStore(): JobStore; /** Exponential backoff with equal jitter: a value in [d/2, d], d = min(max, base·2^(attempt−1)). */ export declare function backoff(attempt: number, opts?: { baseDelayMs?: number; maxDelayMs?: number; random?: () => number }): number; --- # types/same-origin.d.ts import type { VisitsApi, PresenceApi } from './core.js'; // @aikahub/sdk/same-origin — games served from aikahub.com itself (cookie session). import type { Character } from './core.js'; import { AikaHubError } from './core.js'; import type { SaveApi, CloudSave, CloudSaveOptions } from './browser.js'; export { AikaHubError }; export interface SameOriginOptions { /** Your game id, e.g. 'lidercfeny'. Keys without a prefix get `:`. */ game: string; /** Default '' (same origin). */ baseUrl?: string; /** Max queued unlocks sent per flush/start (default 10; the Hub allows 30 per hour per game). */ maxFlush?: number; /** Queue storage; default localStorage, falls back to memory. Only achievement ids are stored, never tokens. */ storage?: Storage | null; fetch?: typeof fetch; } export interface SameOriginUser { nickname: string; avatar: string; level: number; xp: number; profileColor: string; profileUrl: string; } export interface UnlockedItem { id: string; name: { hu: string; en: string; de: string }; icon: string; xp: number; rarity: 'common' | 'rare' | 'epic' | 'legendary'; reward?: { type: string; value: string; label?: unknown } | null; [extra: string]: unknown; } export interface SameOriginUnlock { /** done: the Hub has it; queued: kept locally (guest / transient error), sent later; dropped: final error. */ status: 'done' | 'queued' | 'dropped'; id: string; new?: boolean; xp?: number; unlocked?: UnlockedItem[]; error?: AikaHubError; } export interface SameOriginClient { readonly game: string; /** Logged-in member's public data, or null for guests. */ me(): Promise; /** The member's character; for guests the guest character when guestSeed is given, else null. */ character(opts?: { guestSeed?: string }): Promise; /** Entitlement values in this game; [] for guests. */ entitlements(): Promise; /** Never rejects. */ unlock(id: string): Promise; /** * Send queued unlocks: up to `max` successes (and at most 3 × max attempts). Final errors (incl. 404) drop the entry; * transient ones move it to the back, after 8 tries it is dropped. Entries tagged for another member are skipped * (dropped after 30 days). Stops on 401 or 429. */ flush(opts?: { max?: number }): Promise<{ sent: number; dropped: number; left: number }>; /** me() + flush() when logged in. Call once when the game starts. */ start(): Promise<{ user: SameOriginUser | null; flushed: { sent: number; dropped: number; left: number } | null }>; pending(): string[]; onUnlocked(fn: (item: UnlockedItem) => void): () => void; /** null until the first call tells us. */ readonly loggedIn: boolean | null; /** * 1.3.0: cloud saves for Hub-hosted catalog games (cookie session, /api/games//saves…) — same contract as the * browser client's `hub.saves` (rev, lease, backup slot, 64 KB / 2 MB). Not for Fox Village (it has its own saves). */ readonly saves: SaveApi; /** 1.3.0: the cloud-save helper (guest save locally, reconcile on login, one active session). Call start() first. */ cloudSave(opts?: CloudSaveOptions): CloudSave; /** 1.4.0: visits + preset gifts on the Hub's own origin (/api/games//visits…). The member's first publish(data, { consent: true }) / settings.set({ visibility, consent: true }) records their explicit consent — send it only after asking them in-game (else 403 consent_required); leave() opts out and deletes everything. */ readonly visits: VisitsApi & { leave(): Promise<{ ok: true }> }; /** 1.5.0: presence on the Hub's own origin (/api/games//presence; only the Hub's listed games — lidercfeny, aikalife). */ readonly presence: PresenceApi; } export declare function createSameOriginClient(opts: SameOriginOptions): SameOriginClient; /** Short non-reversible tag of a nickname (FNV-1a, 8 hex) used to mark queue entries made while logged in. */ export declare function ownerTag(nickname: string): string;