Web UI¶
Vue 3 with <script setup> and TypeScript, built by Vite, served from the
server's wwwroot in production. It is the admin panel — there is no
player-facing UI.
Layout¶
web/src/
├── main.ts createApp + router + the global 401 handler
├── App.vue Shell: top bar, PlayFab-style sidebar with foldable groups, <router-view>
├── router.ts Routes, the nav menu source, the auth guard
├── api.ts The one fetch wrapper
├── style.css Theme tokens and element styles
├── pages/
│ ├── LoginPage.vue
│ ├── OverviewPage.vue The landing page: unique users, new users, logins
│ ├── AdminsPage.vue Owner-only admin management
│ ├── ServerKeysPage.vue Owner-only server keys: list, generate (shown once), revoke
│ ├── PlayersPage.vue Every player, searchable and sortable
│ └── PlayerPage.vue One player: Overview and Player Data tabs
├── playerData.ts Player data types and the same checks the server makes
└── components/
├── AppAlert.vue Shared message banner
├── AppCard.vue A panel with a header bar (title, filters, buttons)
├── DailyBars.vue A small one-series bar chart, one bar per day
└── ValueDialog.vue The bigger editor for one player data value
Four conventions hold this together. They are worth keeping:
- All HTTP goes through
api.ts. No page callsfetchdirectly. - One route table. The nav menu and the auth guard both derive from it.
- A page per route, in
pages/. Anything reused across pages goes incomponents/. - No component library. Styling is hand-written CSS driven by custom properties.
Why no Vuetify or similar?
The panel is three pages. A component library would be more code to learn and override than the ~90 lines of CSS it replaces, and the theme is a dozen custom properties. If the UI grows a data grid and a date picker, revisit.
api.ts — the single chokepoint¶
Every request funnels through one function, so a dead session is handled in exactly one place.
async function request<T>(method: string, path: string, body?: unknown, silent = false): Promise<T> {
const res = await fetch(path, { /* ... */ })
if (res.status === 401) {
currentUser.value = null
if (!silent) onUnauthorized?.()
throw new ApiError(401, 'not logged in')
}
if (!res.ok) throw new ApiError(res.status, await errorText(res))
// login, logout and delete all answer 204 with no body.
if (res.status === 204) return undefined as T
return (await res.json()) as T
}
Four details that each exist for a reason:
The 401 handler is a callback, not an import.
let onUnauthorized: (() => void) | null = null
export function setUnauthorizedHandler(fn: () => void) { onUnauthorized = fn }
main.ts sets it. If api.ts imported the router directly and the router
imported api.ts for its guard, that is a circular import. The callback breaks
the cycle.
204 is checked explicitly. Login, logout and delete all return no body, so
res.json() would throw on a successful call.
429 has no body, unlike the hand-written 4xx responses:
return res.status === 429
? 'Too many attempts. Wait a minute and try again.'
: `Request failed (${res.status})`
refreshSession() is silent, so it does not trigger the redirect itself:
export const currentUser = ref<Me | null>(null)
export async function refreshSession(): Promise<Me | null> {
try {
currentUser.value = await request<Me>('GET', '/api/admin/me', undefined, true)
} catch {
currentUser.value = null
}
return currentUser.value
}
The router guard calls this, and the guard decides where to send you. If
refreshSession fired the redirect too, they would fight.
currentUser is a module-level ref, which makes it reactive app-wide —
App.vue reads it for the username and to filter the nav, AdminsPage reads it
to check the role.
ApiError declares its field the long way
export class ApiError extends Error {
// Written out rather than a parameter property: tsconfig sets erasableSyntaxOnly.
status: number
constructor(status: number, message: string) {
super(message)
this.status = status
}
}
constructor(public status: number) would be shorter and will not
compile — see the strict settings.
router.ts — routes, nav and the guard¶
Route metadata is typed by augmenting vue-router's interface:
declare module 'vue-router' {
interface RouteMeta {
public?: boolean
nav?: string
owner?: boolean
}
}
So meta: { nav: 'Admins', group: 'Settings', owner: true } is checked rather
than stringly-typed. group files a link under a foldable sidebar heading, the
way PlayFab puts Players under Identity; a link without one stands alone.
const routes: RouteRecordRaw[] = [
{ path: '/login', name: 'login', component: LoginPage, meta: { public: true } },
{ path: '/', name: 'home', component: OverviewPage, meta: { nav: 'Overview' } },
{ path: '/players', name: 'players', component: PlayersPage, meta: { nav: 'Players', group: 'Identity' } },
{ path: '/admins', name: 'admins', component: AdminsPage, meta: { nav: 'Admins', group: 'Settings', owner: true } },
{ path: '/:pathMatch(.*)*', redirect: { name: 'home' } },
]
The sidebar comes from the array, not the router¶
navEntries walks the array in order: a link with no group becomes its own
entry, and links sharing a group gather under the group's first appearance.
Do not rewrite this as router.getRoutes()
getRoutes() returns routes sorted by path specificity, not declaration
order, so the menu would come out in an arbitrary order — "Admins" before
"Home". Deriving from the source array keeps the menu in the order you wrote
it.
The guard¶
router.beforeEach(async (to) => {
const user = currentUser.value ?? (await refreshSession())
if (to.meta.public) return user ? { name: 'home' } : true
if (!user) return { name: 'login', query: { next: to.fullPath } }
return true
})
/meis asked only when there is no cached answer — never on a timer. A stale cache costs one401from the page's own fetch, which redirects anyway.- A signed-in user hitting
/loginis bounced to home. - An anonymous user is sent to
/loginwith?next=, whichLoginPagehonours after a successful sign-in.
The guard is cosmetic — the server is the authority
A route guard runs in the browser and can be bypassed with curl, dev tools
or a hand-built request. Every endpoint it protects is independently guarded
server-side by .RequireAdmin() or RequireOwner. Never treat a
frontend check as enforcement; it exists to keep the UI coherent.
App.vue — the shell¶
The top bar (user label, theme toggle, logout), the sidebar, and
<router-view>. The sidebar is laid out like PlayFab's: always open on a screen
wider than 900px, with foldable groups (which ones are folded is remembered in
localStorage under hakutaku-folded-groups). On a narrower screen it hides
behind a ☰ button and closes after each navigation. Owner-only links are hidden
from other admins, and a group whose links are all hidden disappears with them.
A page under a link, such as /players/<id> under /players, keeps that link lit.
The login page renders bare — no nav for someone who is not signed in. Adding a page needs no change to this file, because the sidebar is derived.
Theme preference is persisted in localStorage under hakutaku-theme, and
absent a stored choice the OS preference wins:
function toggleTheme() {
const dark = forced.value ? forced.value === 'dark' : matchMedia('(prefers-color-scheme: dark)').matches
forced.value = dark ? 'light' : 'dark'
localStorage.setItem(THEME_KEY, forced.value)
apply()
}
Logout swallows a 401, because "the session was already gone" and "we just
ended it" have the same outcome.
The pages¶
LoginPage.vue¶
Username and password, posts to /api/admin/login, calls refreshSession(),
then honours ?next= or falls back to home. Errors surface through AppAlert.
await api.post('/api/admin/login', { username: username.value, password: password.value })
await refreshSession()
Login is by username, not email.
OverviewPage.vue¶
The landing page after sign-in, like PlayFab's Title Overview. It reads
GET /api/admin/stats once (Refresh reads it again) and shows:
- a Players card with the total and a link to the list;
- Unique users, New users and Logins cards. Each card's header bar is
also its table header (Amount / Change), the rows are the last 24 hours and
the last 30 days, and Change is the percentage against the period before, or
NAwhen that was zero, as PlayFab shows it; - under each,
components/DailyBars.vue: one bar per day for the chosen Time period (7, 14 or 30 days, remembered per browser), with a tooltip on hover or keyboard focus and a hidden table for screen readers.
A day is a rolling 24 hours counted back from when the numbers were made, not a calendar day; see the stats route in the API reference.
AdminsPage.vue¶
Owner-only. Lists every admin including deactivated ones, creates admins, and deactivates them. The file header records authorship and the key constraint:
<!-- Admins page - done by Sherwyn.
Owner-only: lists every admin (including deactivated ones), creates new
admins, and deactivates them. The server enforces all three with
RequireOwner, so the checks here are only to keep the UI honest. -->
The client-side rules mirror the server's rather than replacing them:
Deactivation warns about the part that is not obvious:
if (!confirm(`Deactivate "${a.username}"?\n\nThis cannot be undone, and the username can never be reused.`)) return
The Deactivate button is hidden for the owner and for already-disabled admins —
the server would answer 403 and there is nothing left to do, respectively.
ServerKeysPage.vue¶
Owner-only. Lists the server keys (name, created, expires, last used, and a status of Active, Expired or Revoked), generates one from a name and an optional expiry, and revokes one.
A new key is shown once. Right after it is made, a panel shows the key in a read-only box with a Copy button and the note "You won't see this key again". It stays until the owner clicks "I've saved it", and it never comes back: the list only ever has names and dates, because the server keeps just a hash.
created.value = await api.post<NewKey>('/api/admin/server-keys', {
name: name.value.trim(),
expiresAt: expires.value ? new Date(expires.value).toISOString() : undefined,
})
The client-side rules mirror the server's: a name is required, and an expiry has to be in the future. Revoking asks first, because it can't be undone and the game server using that key stops working at once. If the clipboard can't be used (it needs https or localhost), the page says so and the key can still be selected by hand.
PlayersPage.vue¶
Any admin. Identity → Players in the sidebar. Lists every player (display name,
id, created, last login, sign-in providers) from GET /api/players in a card,
with a search box that filters by name or id in the browser, since the server
returns the whole table. Newest first; the name, Created and Last login headings
sort. A row opens that player's page.
PlayerPage.vue¶
/players/:id, reached from the list (it has no menu entry), with two tabs like
PlayFab's player view. The tab is in the URL (?tab=data), so it can be linked.
Overview: cards for Player info (display name, id with Copy, created, last login), Linked accounts (provider, when linked, and Verified / Unverified for an email, never the address) and a count of keys per tier, each opening that tier.
Player Data: one card. Its header switches tier (Client writable, Read only,
Internal, each with a key count) and shows n / 100 keys; a toolbar under it has
+ Add key, Delete (the ticked rows), Discard and Save; then a
Key / Value / Last updated table with a checkbox on each row.
- Short single-line values are edited right in the table. Long, multi-line or
JSON values show a preview, and they open in
components/ValueDialog.vue, which has a byte counter against the 16 KB limit and Format JSON / Compact buttons. "+ Add key" opens the same dialog with the key editable. - Edits, new keys and deletions are held on the page per tier and marked
edited,newordeleted(with Undo), until Save, which asks first and sends that tier's changes as onePOST /api/players/{id}/data?tier=. Typing a value back to what is saved drops it from the changes. Refresh reloads from the server, asking first if anything is unsaved. - The rules in
playerData.tsmirrorPlayerDataRules.csandLimits.cs(key characters and length, 16 KB values, 10 changes a save, 100 keys a tier), so a problem shows before Save. The server still checks everything. - Leaving the page or closing the tab with unsaved changes asks first.
Styling¶
style.css defines the theme as custom properties, and dark mode redefines the
same names:
:root {
--matcha: #c3e1b5;
--bg: #ffffff;
--surface: #f4f9f0;
--accent: #5c8a48;
--text: #14170f;
/* ... */
}
#c3e1b5 is not a text colour
It hits only 1.4:1 against white, far below WCAG's 4.5:1 minimum. So the
brand green is used for surfaces and borders, with near-black text on top,
and --accent (#5c8a48) is a darkened matcha used wherever light text sits
on it. Do not swap one for the other.
Dark mode follows the OS unless the toggle has forced a theme, which needs the rule written twice — once guarded under the media query, once for the explicit override:
@media (prefers-color-scheme: dark) {
:root:not([data-theme='light']) { /* dark tokens */ }
}
:root[data-theme='dark'] { /* the same dark tokens */ }
Page-specific CSS lives in that page's <style scoped> block.
The strict TypeScript settings¶
npm run build runs vue-tsc -b before Vite, so a type error fails the build.
tsconfig.app.json turns on four checks beyond the defaults:
| Setting | Effect |
|---|---|
noUnusedLocals |
An unused variable is an error |
noUnusedParameters |
An unused parameter is an error |
noFallthroughCasesInSwitch |
A case without break is an error |
erasableSyntaxOnly |
Bans TypeScript syntax that has runtime behaviour |
That last one is the one that catches people. It rejects constructor parameter
properties, enum, and namespaces — anything that is not purely erasable type
annotation:
// error TS1294: This syntax is not allowed when 'erasableSyntaxOnly' is enabled
constructor(public status: number, message: string) { super(message) }
// fine
status: number
constructor(status: number, message: string) { super(message); this.status = status }
Use a const object with a union type instead of an enum.
Adding a page¶
- Create
pages/YourPage.vue. - Add one entry to the
routesarray inrouter.ts: Addowner: trueif it is owner-only. - Stop. The nav menu and the guard pick it up automatically.
App.vueneeds no change. - Fetch through
api.ts—api.get,api.post,api.del— neverfetch. - Surface errors with
AppAlert, and remember the server is the real guard.
Known rough edges¶
meta.publicmeans two things: "no auth required" and "bounce signed-in users away". That is correct for/login, and wrong for the first genuinely public page someone adds. Split it intopublicandguestOnlywhen that happens.- No tests. No Vitest, no component tests.
confirm()for destructive actions rather than a styled modal.- No loading skeletons — just a "Loading…" line.
index.htmlis cacheable, so after a deploy a returning browser can run the previous bundle from cache. Hashed asset filenames make the fix easy if it ever matters:Cache-Control: no-storeonindex.htmlonly.