Files
OpenFrontIO/src/client/components/DesktopNavBar.ts
T
Evan 274b516ea3 feat(crazygames): backend login + surface the signed-in user (#4542)
Client-side CrazyGames login: exchange the SDK user token for our
session, then surface that identity in the UI. Implements the client
side of the [CrazyGames login handoff
guide](https://docs.crazygames.com/sdk/user/).

## Part 1 — Backend login (token exchange)

On CrazyGames we exchange the SDK's user token for our own session via
`POST /auth/crazygames`, instead of the cookie-based `/auth/refresh`
(the refresh cookie is `SameSite=Lax` and unusable from the CrazyGames
iframe).

- **`CrazyGamesSDK.ts`** — `getUserToken()` wrapper (awaits `ready()`,
gates on `isUserAccountAvailable`, returns `null` on throw / no
signed-in user).
- **`Auth.ts`** — `doRefreshJwt()` routes to `doCrazyGamesLogin()` when
on CrazyGames with a signed-in account; a `null` token (guest / no
account) falls through to the existing `/auth/refresh` flow.
`reauthAfterCrazyGamesChange()` drops the cached session on a
mid-session sign-in.
- **`Main.ts`** — `addAuthListener` re-runs auth + `getUserMe()` when
the player signs into CrazyGames mid-session.

Everything funnels through the existing `userAuth()` → `refreshJwt()`
path, so **startup login and the 15-min re-exchange on expiry come for
free** — no new expiry/polling code.

## Part 2 — Surface the signed-in user

- **Account button** shows the CrazyGames avatar + username when signed
in (clicking opens the account modal), or a **"Sign in"** that opens
CrazyGames' own `showAuthPrompt()` when a guest. Wired across every
entry point: the desktop nav pill, the mobile hamburger item (un-hidden
on CrazyGames by dropping `.no-crazygames`), and — since CrazyGames
renders below the `lg` breakpoint where the desktop nav is hidden — a
new button in the **homepage top bar's** right slot.
- **AccountModal** treats the CrazyGames user as logged-in: "Connected
as" avatar + username, currency/subscription, and stats/games/friends.
**No Discord/Google/email login+link buttons and no logout** (CrazyGames
owns the account). A guest who reaches the modal gets a CrazyGames
sign-in button, never Discord/Google.
- **`CrazyGamesSDK.ts`** — `getUserProfile()` + `showAuthPrompt()`
wrappers; `profilePictureUrl` added to the user type.

Identity comes from the SDK (`getUser()`), not `/users/@me`, which
doesn't surface CrazyGames identity yet.

## Behavior

- **Signed-in CrazyGames account** → real backend session; avatar +
username in the top bar; CrazyGames-only account modal.
- **CrazyGames guest / not signed in** → silent fallback to guest; "Sign
in" button opens `showAuthPrompt()`; auto-logged-in the moment they sign
in (via `addAuthListener`).
- **Not on CrazyGames** → completely unchanged.

## Testing

- `npx tsc --noEmit` — clean
- `npx eslint` on changed files — clean
- No new i18n keys (reuses `main.sign_in`, `account_modal.*`).
- No unit tests: this repo tests core sim only, and CrazyGames only
initializes inside a crazygames.com iframe, so the CG paths can't run
locally (the localhost SDK mock returns unsigned tokens the backend
rejects). **Needs a manual pass on the CrazyGames game page (gameId
`64178`)** covering: signed-in avatar/username + account modal, guest
"Sign in" → prompt, and mid-session sign-in.

## Assumptions to confirm (backend)

1. The `/auth/crazygames` JWT carries the same `iss` (`getApiBase()`)
and `aud` (`getAudience()`) as normal openfront.io tokens and satisfies
`TokenPayloadSchema` (incl. base64url `sub`) — otherwise `userAuth()`
will `logOut()`.
2. CrazyGames iframes our own origin (so `getApiBase()` →
`https://api.openfront.io`), consistent with the existing integration.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-09 08:02:45 -07:00

209 lines
7.5 KiB
TypeScript

import { LitElement, html } from "lit";
import { customElement } from "lit/decorators.js";
import { assetUrl } from "../../core/AssetUrls";
import { NavNotificationsController } from "./NavNotificationsController";
@customElement("desktop-nav-bar")
export class DesktopNavBar extends LitElement {
private _notifications = new NavNotificationsController(this);
createRenderRoot() {
return this;
}
connectedCallback() {
super.connectedCallback();
window.addEventListener("showPage", this._onShowPage);
const current = window.currentPageId;
if (current) {
// Wait for render
this.updateComplete.then(() => {
this._updateActiveState(current);
});
}
}
disconnectedCallback() {
super.disconnectedCallback();
window.removeEventListener("showPage", this._onShowPage);
}
private _onShowPage = (e: Event) => {
const pageId = (e as CustomEvent).detail;
this._updateActiveState(pageId);
};
private _updateActiveState(pageId: string) {
this.querySelectorAll(".nav-menu-item").forEach((el) => {
if ((el as HTMLElement).dataset.page === pageId) {
el.classList.add("active");
} else {
el.classList.remove("active");
}
});
}
render() {
window.currentPageId ??= "page-play";
const currentPage = window.currentPageId;
return html`
<nav
class="hidden lg:flex w-full bg-zinc-900/90 backdrop-blur-md items-center justify-center gap-8 py-4 shrink-0 z-50 relative"
>
<div class="flex flex-col items-center justify-center">
<div class="h-8">
<img
class="block h-full aspect-[1364/259]"
src=${assetUrl("images/OpenFrontLogo.svg")}
alt="OpenFront"
/>
</div>
<div
id="game-version"
class="l-header__highlightText text-center"
></div>
</div>
<button
class="nav-menu-item ${currentPage === "page-play"
? "active"
: ""} text-white/70 hover:text-malibu-blue font-medium tracking-wider uppercase cursor-pointer transition-colors [&.active]:text-malibu-blue "
data-page="page-play"
data-i18n="main.play"
></button>
<!-- Desktop Navigation Menu Items -->
<div class="relative">
<button
class="nav-menu-item ${currentPage === "page-news"
? "active"
: ""} text-white/70 hover:text-malibu-blue font-medium tracking-wider uppercase cursor-pointer transition-colors [&.active]:text-malibu-blue "
data-page="page-news"
data-i18n="main.news"
@click=${this._notifications.onNewsClick}
></button>
${this._notifications.showNewsDot()
? html`
<span
class="absolute -top-1 -right-1 w-2 h-2 bg-red-500 rounded-full animate-ping"
></span>
<span
class="absolute -top-1 -right-1 w-2 h-2 bg-red-500 rounded-full"
></span>
`
: ""}
</div>
<div class="relative no-crazygames">
<button
class="nav-menu-item ${currentPage === "page-item-store"
? "active"
: ""} text-white/70 hover:text-malibu-blue font-medium tracking-wider uppercase cursor-pointer transition-colors [&.active]:text-malibu-blue "
data-page="page-item-store"
data-i18n="main.store"
@click=${this._notifications.onStoreClick}
></button>
${this._notifications.showStoreDot()
? html`
<span
class="absolute -top-1 -right-1 w-2 h-2 bg-red-500 rounded-full animate-ping"
></span>
<span
class="absolute -top-1 -right-1 w-2 h-2 bg-red-500 rounded-full"
></span>
`
: ""}
</div>
<button
class="nav-menu-item text-white/70 hover:text-malibu-blue font-medium tracking-wider uppercase cursor-pointer transition-colors [&.active]:text-malibu-blue "
data-page="page-settings"
data-i18n="main.settings"
></button>
<button
class="nav-menu-item text-white/70 hover:text-malibu-blue font-medium tracking-wider uppercase cursor-pointer transition-colors [&.active]:text-malibu-blue "
data-page="page-leaderboard"
data-i18n="main.leaderboard"
></button>
<button
class="no-crazygames nav-menu-item text-white/70 hover:text-blue-500 font-medium tracking-wider uppercase cursor-pointer transition-colors [&.active]:text-blue-500"
data-page="page-clan"
data-i18n="main.clans"
></button>
<div class="relative">
<button
class="nav-menu-item text-white/70 hover:text-malibu-blue font-medium tracking-wider uppercase cursor-pointer transition-colors [&.active]:text-malibu-blue "
data-page="page-help"
data-i18n="main.help"
@click=${this._notifications.onHelpClick}
></button>
${this._notifications.showHelpDot()
? html`
<span
class="absolute -top-1 -right-1 w-2 h-2 bg-yellow-400 rounded-full animate-ping"
></span>
<span
class="absolute -top-1 -right-1 w-2 h-2 bg-yellow-400 rounded-full"
></span>
`
: ""}
</div>
<button
id="nav-account-button"
class="nav-menu-item relative h-10 rounded-full overflow-hidden flex items-center justify-center gap-2 px-3 bg-transparent border border-white/20 text-white/80 hover:text-white cursor-pointer transition-colors [&.active]:text-white"
data-page="page-account"
data-i18n-aria-label="main.account"
data-i18n-title="main.account"
>
<img
id="nav-account-avatar"
class="hidden w-8 h-8 rounded-full object-cover"
alt=""
data-i18n-alt="main.discord_avatar_alt"
referrerpolicy="no-referrer"
/>
<svg
id="nav-account-person-icon"
class="w-5 h-5"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="1.5"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="M20 21a8 8 0 0 0-16 0" />
<path d="M12 13a4 4 0 1 0-4-4 4 4 0 0 0 4 4Z" />
</svg>
<span
id="nav-account-email-badge"
class="hidden absolute bottom-1 right-1 w-4 h-4 rounded-full bg-slate-900/80 border border-white/20 flex items-center justify-center"
aria-hidden="true"
>
<svg
class="w-2.5 h-2.5 text-white/80"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
>
<path d="M4 4h16v16H4z" opacity="0" />
<path d="M4 6h16v12H4z" />
<path d="m4 7 8 6 8-6" />
</svg>
</span>
<span
id="nav-account-signin-text"
class="text-xs font-bold tracking-widest"
data-i18n="main.sign_in"
>
</span>
</button>
</nav>
`;
}
}