more endpoints, fix orientation on new accounts

This commit is contained in:
Devin Zuczek
2026-06-15 22:39:24 -04:00
parent 5f3ec3b8c7
commit 335b4d68ce
16 changed files with 554 additions and 87 deletions
+118
View File
@@ -0,0 +1,118 @@
/**
* Account storage on the shared `rec-rooms` D1 database. Each account is a single
* JSON blob in the `data` column; queryable fields (AccountId, Username) are
* SQLite generated (virtual) columns extracted from that JSON and indexed —
* the same JSON-blob pattern the `rooms` worker uses.
*
* The `auth` worker owns this schema/migration (see migrations/0001_accounts.sql,
* applied with its own `migrations_table` so it doesn't clash with the rooms
* migrations that share the database). Other workers bind the table read/write
* and keep these helpers in sync.
*/
/** Schema DDL (mirror of migrations/0001_accounts.sql, sans the seed INSERTs). */
export const SCHEMA_DDL: string[] = [
`CREATE TABLE IF NOT EXISTS accounts (
data TEXT NOT NULL,
account_id INTEGER GENERATED ALWAYS AS (json_extract(data, '$.AccountId')) VIRTUAL,
username_lower TEXT GENERATED ALWAYS AS (lower(json_extract(data, '$.Username'))) VIRTUAL
)`,
`CREATE UNIQUE INDEX IF NOT EXISTS idx_accounts_account_id ON accounts (account_id)`,
`CREATE INDEX IF NOT EXISTS idx_accounts_username_lower ON accounts (username_lower)`,
]
/** Client-facing account shape (PascalCase, matches the C# `Account`). */
export interface Account {
AccountId: number
Username: string
DisplayName: string
ProfileImage: string
IsJunior: boolean
Platforms: number
PersonalPronouns: number
IdentityFlags: number
CreatedAt: string
}
interface AccountRow {
data: string
}
const parseOne = (row: AccountRow | null): Account | null =>
row ? (JSON.parse(row.data) as Account) : null
const parseAll = (rows: AccountRow[]): Account[] => rows.map((r) => JSON.parse(r.data) as Account)
/** Word lists for auto-assigned usernames (players don't pick one on signup). */
const ADJECTIVES = [
'Swift', 'Brave', 'Clever', 'Happy', 'Mighty', 'Lucky', 'Sunny', 'Cosmic',
'Witty', 'Nimble', 'Jolly', 'Bold', 'Gentle', 'Fuzzy', 'Speedy', 'Shiny',
]
const NOUNS = [
'Fox', 'Otter', 'Falcon', 'Panda', 'Tiger', 'Comet', 'Maple', 'Pixel',
'Robin', 'Wolf', 'Koala', 'Dragon', 'Penguin', 'Badger', 'Heron', 'Lynx',
]
/** A random, readable username (e.g. "SwiftFox4821"). */
export function randomUsername(): string {
const adj = ADJECTIVES[Math.floor(Math.random() * ADJECTIVES.length)]
const noun = NOUNS[Math.floor(Math.random() * NOUNS.length)]
const n = Math.floor(Math.random() * 10000)
return `${adj}${noun}${n}`
}
/**
* Build a full account object from an id, applying the C# fallbacks for any
* column the caller doesn't override. Used both to synthesize accounts that
* aren't in the DB and as the base for a freshly created account.
*/
export function defaultAccount(id: number, overrides: Partial<Account> = {}): Account {
return {
AccountId: id,
Username: `Player${id}`,
DisplayName: `Player${id}`,
ProfileImage: 'DefaultProfileImage.jpg',
IsJunior: false,
Platforms: 0,
PersonalPronouns: 0,
IdentityFlags: 0,
CreatedAt: new Date().toISOString(),
...overrides,
}
}
/** Look up a single account by AccountId. */
export async function getAccount(db: D1Database, id: number): Promise<Account | null> {
return parseOne(
await db.prepare('SELECT data FROM accounts WHERE account_id = ?1').bind(id).first<AccountRow>()
)
}
/** Look up multiple accounts by AccountId (order not guaranteed). */
export async function getAccountsByIds(db: D1Database, ids: number[]): Promise<Account[]> {
if (ids.length === 0) return []
const placeholders = ids.map((_, i) => `?${i + 1}`).join(',')
const { results } = await db
.prepare(`SELECT data FROM accounts WHERE account_id IN (${placeholders})`)
.bind(...ids)
.all<AccountRow>()
return parseAll(results)
}
/**
* Create and persist a new account. The id is the next free integer (above the
* seeded system accounts); the username is auto-assigned (players don't choose
* one initially) and the display name defaults to it.
*/
export async function createAccount(
db: D1Database,
overrides: Partial<Account> = {}
): Promise<Account> {
const row = await db
.prepare('SELECT COALESCE(MAX(account_id), 1) + 1 AS next FROM accounts')
.first<{ next: number }>()
const id = row?.next ?? 2
const username = overrides.Username ?? randomUsername()
const account = defaultAccount(id, { Username: username, DisplayName: username, ...overrides })
await db.prepare('INSERT INTO accounts (data) VALUES (?1)').bind(JSON.stringify(account)).run()
return account
}
+29 -53
View File
@@ -3,33 +3,21 @@ import { useWorkersLogger } from 'workers-tagged-logger'
import { withNotFound, withOnError } from '@repo/hono-helpers'
import { createAccount, defaultAccount, getAccount, getAccountsByIds } from './accounts-db'
import { validateAndGetAccountId } from './jwt'
import type { Context } from 'hono'
import type { App } from './context'
/**
* Ported from the C# `AccountsController`. Endpoints that the C# backs with EF
* Core (`AppDbContext`) are stubbed here — there's no DB binding yet, so reads
* return synthesized defaults (the C# fills every field with a fallback anyway)
* and writes accept-and-ack without persisting. Each stub is marked `TODO`.
* Ported from the C# `AccountsController`. Account reads/writes are backed by the
* shared `accounts` table in D1 (schema owned by the `auth` worker). Accounts not
* in the table fall back to a synthesized default (the C# fills every column with
* a fallback anyway). Profile mutations still accept-and-ack (marked `TODO`).
*
* Auth-gated routes still validate the Bearer JWT issued by the `auth` worker.
*/
/** Account shape returned by the public lookup endpoints. */
interface Account {
AccountId: number
ProfileImage: string
IsJunior: boolean
Platforms: number
PersonalPronouns: number
IdentityFlags: number
Username: string
DisplayName: string
CreatedAt: string
}
/**
* Resolve the account id from a Bearer token, mirroring the repeated
* auth-header check in the C#. Returns `null` when the header is missing,
@@ -37,7 +25,6 @@ interface Account {
*/
async function authedId(c: Context<App>): Promise<number | null> {
const authHeader = c.req.header('Authorization') ?? ''
console.log(authHeader)
if (!authHeader.toLowerCase().startsWith('bearer ')) return null
const token = authHeader.slice('Bearer '.length)
@@ -60,24 +47,6 @@ async function formField(c: Context<App>, name: string): Promise<string> {
return typeof value === 'string' ? value : ''
}
/**
* Synthesize an `Account` from an id using the same fallbacks the C# applies
* when a column is null. Stands in for `db.Accounts.FindAsync(id)`.
*/
function defaultAccount(id: number): Account {
return {
AccountId: id,
ProfileImage: 'DefaultProfileImage.jpg',
IsJunior: false,
Platforms: 0,
PersonalPronouns: 0,
IdentityFlags: 0,
Username: `Player${id}`,
DisplayName: `Player${id}`,
CreatedAt: new Date().toISOString(),
}
}
const app = new Hono<App>()
.use(
'*',
@@ -99,8 +68,8 @@ const app = new Hono<App>()
.get('/account/me', async (c) => {
const id = await authedId(c)
if (id === null) return unauthorized(c)
// TODO: load the real account; the C# 404s when the row is missing.
const account = defaultAccount(id)
// Load the stored account, falling back to a synthesized default.
const account = (await getAccount(c.env.DB, id)) ?? defaultAccount(id)
// The C# `SelfAccount` marks `JuniorState` (an enum) and `ParentAccountId`
// with `[JsonIgnore(WhenWritingNull)]`, so they're OMITTED when null —
// emitting `"juniorState":null` makes the client's enum parser throw
@@ -118,15 +87,18 @@ const app = new Hono<App>()
// ---- Bulk / single lookup ------------------------------------------------
// Register the static `bulk` path before the `/account/:id` param route.
.get('/account/bulk', (c) => {
.get('/account/bulk', async (c) => {
// C# reads repeated `id` query params; also accept a comma-separated list.
const ids = c.req
.queries('id')
?.flatMap((v) => v.split(','))
.map((s) => Number.parseInt(s.trim(), 10))
.filter((n) => !Number.isNaN(n))
// TODO: query Accounts for these ids instead of synthesizing.
return c.json((ids ?? []).map(defaultAccount))
const ids =
c.req
.queries('id')
?.flatMap((v) => v.split(','))
.map((s) => Number.parseInt(s.trim(), 10))
.filter((n) => !Number.isNaN(n)) ?? []
// Resolve stored accounts, synthesizing a default for any id not in the DB
// so every requested id is present in the response (matches the C#).
const stored = new Map((await getAccountsByIds(c.env.DB, ids)).map((a) => [a.AccountId, a]))
return c.json(ids.map((id) => stored.get(id) ?? defaultAccount(id)))
})
.get('/account/:id/bio', (c) => {
@@ -136,22 +108,26 @@ const app = new Hono<App>()
return c.json({ accountId, bio: '' })
})
.get('/account/:id', (c) => {
.get('/account/:id', async (c) => {
const accountId = Number.parseInt(c.req.param('id'), 10)
if (Number.isNaN(accountId)) return c.body(null, 400)
// TODO: load the real account; the C# 404s when the row is missing.
return c.json(defaultAccount(accountId))
// Load the stored account, falling back to a synthesized default.
return c.json((await getAccount(c.env.DB, accountId)) ?? defaultAccount(accountId))
})
// ---- Create --------------------------------------------------------------
.post('/account/create', async (c) => {
// Parsed for fidelity; unused until there's a DB to persist CachedLogins.
await formField(c, 'platform')
const platform = await formField(c, 'platform')
await formField(c, 'platformId')
const accountId = Math.floor(Math.random() * (99999 - 10000 + 1)) + 10000
const account = defaultAccount(accountId)
// TODO: persist the account + a dorm Room/SubRoom once a DB binding exists.
// Persist a new account with an auto-assigned random username (players
// don't choose one initially).
const platforms = Number.parseInt(platform, 10)
const account = await createAccount(c.env.DB, {
Platforms: Number.isNaN(platforms) ? 0 : platforms,
})
// TODO: also create a dorm Room/SubRoom for the new account.
return c.json({ success: true, value: account })
})
+3 -1
View File
@@ -2,7 +2,9 @@ import type { HonoApp } from '@repo/hono-helpers'
import type { SharedHonoEnv, SharedHonoVariables } from '@repo/hono-helpers/src/types'
export type Env = SharedHonoEnv & {
// add additional Bindings here
// Shared rooms/accounts D1 database (schema owned by the `auth` worker). Used
// to look up accounts in bulk/by id and to create new accounts.
DB: D1Database
}
/** Variables can be extended */
+43 -7
View File
@@ -1,10 +1,30 @@
import { env } from 'cloudflare:test'
import { exports } from 'cloudflare:workers'
import { describe, expect, test } from 'vitest'
import { beforeAll, describe, expect, test } from 'vitest'
import '../../accounts.app'
import { SCHEMA_DDL } from '../../accounts-db'
import type { Env } from '../../context'
declare module 'cloudflare:test' {
interface ProvidedEnv extends Env {}
}
const ORIGIN = 'https://accounts.rec.djdevin.net'
// Apply the accounts schema + seed the system (uid 0) and Coach (uid 1) accounts
// into the test D1 (mirrors apps/auth/migrations/0001_accounts.sql).
beforeAll(async () => {
for (const stmt of SCHEMA_DDL) await env.DB.prepare(stmt).run()
const insert = env.DB.prepare('INSERT OR IGNORE INTO accounts (data) VALUES (?1)')
await env.DB.batch([
insert.bind(JSON.stringify({ AccountId: 0, Username: 'RecRoom', DisplayName: 'Rec Room' })),
insert.bind(JSON.stringify({ AccountId: 1, Username: 'Coach', DisplayName: 'Coach' })),
])
})
// Mint a token the way the `auth` worker does, using the same dev secret, so the
// accounts worker's validation accepts it. Kept inline to avoid a cross-package
// import.
@@ -62,11 +82,15 @@ describe('public endpoints', () => {
expect(res.status).toBe(400)
})
test('GET /account/bulk returns one account per id', async () => {
test('GET /account/bulk resolves stored accounts and synthesizes the rest', async () => {
const res = await exports.default.fetch(`${ORIGIN}/account/bulk?id=1&id=2,3`)
expect(res.status).toBe(200)
const accounts = (await res.json()) as Array<{ AccountId: number }>
const accounts = (await res.json()) as Array<{ AccountId: number; Username: string }>
// Every requested id is present and in order.
expect(accounts.map((a) => a.AccountId)).toEqual([1, 2, 3])
// id 1 is the seeded Coach account; 2 and 3 fall back to synthesized defaults.
expect(accounts[0].Username).toBe('Coach')
expect(accounts[1].Username).toBe('Player2')
})
test('GET /account/:id/bio returns an empty bio', async () => {
@@ -74,13 +98,25 @@ describe('public endpoints', () => {
expect(await res.json()).toEqual({ accountId: 7, bio: '' })
})
test('POST /account/create returns a wrapped account', async () => {
test('POST /account/create persists a new account with a random username', async () => {
const res = await exports.default.fetch(`${ORIGIN}/account/create`, { method: 'POST' })
expect(res.status).toBe(200)
const body = (await res.json()) as { success: boolean; value: { AccountId: number } }
const body = (await res.json()) as {
success: boolean
value: { AccountId: number; Username: string; DisplayName: string }
}
expect(body.success).toBe(true)
expect(body.value.AccountId).toBeGreaterThanOrEqual(10000)
expect(body.value.AccountId).toBeLessThanOrEqual(99999)
// Id is allocated above the seeded system accounts (0, 1).
expect(body.value.AccountId).toBeGreaterThanOrEqual(2)
// Username is auto-assigned (not the synthesized "Player<id>" fallback) and
// the display name mirrors it.
expect(body.value.Username).not.toMatch(/^Player\d+$/)
expect(body.value.Username.length).toBeGreaterThan(0)
expect(body.value.DisplayName).toBe(body.value.Username)
// It's retrievable afterwards.
const lookup = await exports.default.fetch(`${ORIGIN}/account/${body.value.AccountId}`)
const found = (await lookup.json()) as { Username: string }
expect(found.Username).toBe(body.value.Username)
})
})
+9
View File
@@ -10,6 +10,15 @@
"custom_domain": true
}
],
// Shared D1 database. The `accounts` table schema/migrations are owned by the
// `auth` worker; this worker binds it read/write to look up and create accounts.
"d1_databases": [
{
"binding": "DB",
"database_name": "rec-rooms",
"database_id": "d44083e1-5bfe-4467-aa9a-f13c5c2496d5"
}
],
"logpush": false,
"upload_source_maps": true,
"observability": {