mirror of
https://github.com/djdevin/recflare.git
synced 2026-09-08 14:41:28 -07:00
more endpoints, fix orientation on new accounts
This commit is contained in:
@@ -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
|
||||
}
|
||||
+75
-11
@@ -3,6 +3,7 @@ import { useWorkersLogger } from 'workers-tagged-logger'
|
||||
|
||||
import { logger, withNotFound, withOnError } from '@repo/hono-helpers'
|
||||
|
||||
import { createAccount } from './accounts-db'
|
||||
import { generateToken, TOKEN_TTL_SECONDS } from './jwt'
|
||||
|
||||
import type { App } from './context'
|
||||
@@ -25,6 +26,66 @@ const PLATFORM_TYPES: Record<number, string> = {
|
||||
8: 'Pico',
|
||||
}
|
||||
|
||||
/** New players start in the Orientation room (RoomId 13) — the new-user flow. */
|
||||
const ORIENTATION_ROOM_ID = 13
|
||||
/** Presence TTL (s) — matches the match worker; refreshed by each heartbeat. */
|
||||
const PRESENCE_TTL = 900
|
||||
|
||||
/**
|
||||
* Seed a freshly created account's match presence to the Orientation room. The
|
||||
* client is placed into Orientation by its new-user flow without a matchmake
|
||||
* call, so the match heartbeat would otherwise report no/stale (dorm) presence
|
||||
* and bounce the player out. We write the Orientation instance (built from the
|
||||
* shared rooms D1, matching the match worker's `roomInstanceFromRoom` shape) so
|
||||
* the heartbeat keeps them there.
|
||||
*/
|
||||
async function placeNewPlayerInOrientation(env: App['Bindings'], accountId: number): Promise<void> {
|
||||
const row = await env.DB.prepare('SELECT data FROM rooms WHERE room_id = ?1')
|
||||
.bind(ORIENTATION_ROOM_ID)
|
||||
.first<{ data: string }>()
|
||||
if (!row) return
|
||||
|
||||
const room = JSON.parse(row.data) as Record<string, unknown>
|
||||
const subRooms = room.SubRooms
|
||||
const sub = (Array.isArray(subRooms) ? subRooms[0] : undefined) as
|
||||
| Record<string, unknown>
|
||||
| undefined
|
||||
const str = (v: unknown, fallback = '') => (typeof v === 'string' ? v : fallback)
|
||||
const num = (v: unknown, fallback: number) => (typeof v === 'number' ? v : fallback)
|
||||
|
||||
const roomInstance = {
|
||||
roomInstanceId: ORIENTATION_ROOM_ID,
|
||||
roomId: ORIENTATION_ROOM_ID,
|
||||
subRoomId: num(sub?.SubRoomId, 1),
|
||||
roomInstanceType: 0,
|
||||
location: str(sub?.UnitySceneId),
|
||||
dataBlob: str(sub?.DataBlob),
|
||||
eventId: 0,
|
||||
clubId: 0,
|
||||
roomCode: '',
|
||||
photonRegion: 'us',
|
||||
photonRegionId: 'us',
|
||||
photonRoomId: `rec.${ORIENTATION_ROOM_ID}`,
|
||||
name: `^${str(room.Name, 'Orientation')}`,
|
||||
maxCapacity: num(sub?.MaxPlayers, 4),
|
||||
isFull: false,
|
||||
isPrivate: false,
|
||||
isInProgress: false,
|
||||
EncryptVoiceChat: false,
|
||||
}
|
||||
const presence = {
|
||||
roomInstance,
|
||||
statusVisibility: 0,
|
||||
deviceClass: 0,
|
||||
vrMovementMode: 1,
|
||||
platform: 0,
|
||||
appVersion: '20230302',
|
||||
}
|
||||
await env.MATCH_PRESENCE.put(`presence:${accountId}`, JSON.stringify(presence), {
|
||||
expirationTtl: PRESENCE_TTL,
|
||||
})
|
||||
}
|
||||
|
||||
const app = new Hono<App>()
|
||||
.use(
|
||||
'*',
|
||||
@@ -73,21 +134,24 @@ const app = new Hono<App>()
|
||||
const platformInt = typeof body.platform === 'string' ? Number.parseInt(body.platform, 10) : NaN
|
||||
const platform = Number.isNaN(platformInt) ? '' : (PLATFORM_TYPES[platformInt] ?? '')
|
||||
|
||||
// grant_type=create_account mints a brand-new account (the C# persists it
|
||||
// plus a dorm; with no DB we just allocate a random id — the accounts worker
|
||||
// synthesizes the account on demand). Otherwise use the posted account_id,
|
||||
// grant_type=create_account mints + persists a brand-new account (with an
|
||||
// auto-assigned random username — players don't choose one initially). The
|
||||
// token's `sub` is the new account's id. Otherwise use the posted account_id,
|
||||
// falling back to "1" (the cachedlogin stub hands the client account 1).
|
||||
const accountId =
|
||||
grantType === 'create_account'
|
||||
? String(Math.floor(Math.random() * (99999 - 10000 + 1)) + 10000)
|
||||
: typeof body.account_id === 'string' && body.account_id
|
||||
? body.account_id
|
||||
: '1'
|
||||
let accountId: string
|
||||
if (grantType === 'create_account') {
|
||||
const account = await createAccount(c.env.DB, { Platforms: platformInt || 0 })
|
||||
accountId = String(account.AccountId)
|
||||
// Place the new player in Orientation (they don't matchmake into it).
|
||||
await placeNewPlayerInOrientation(c.env, account.AccountId)
|
||||
} else {
|
||||
accountId = typeof body.account_id === 'string' && body.account_id ? body.account_id : '1'
|
||||
}
|
||||
|
||||
const accessToken = await generateToken(accountId, platformId, platform)
|
||||
|
||||
// TODO: once a DB binding exists, create the account + dorm on create_account
|
||||
// and remove any RoomInstance owned by accountId on login.
|
||||
// TODO: also create the player's dorm on create_account, and remove any
|
||||
// RoomInstance owned by accountId on login.
|
||||
|
||||
return c.json({
|
||||
access_token: accessToken,
|
||||
|
||||
@@ -2,7 +2,13 @@ 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. The `auth` worker owns the `accounts`
|
||||
// table (creates accounts on signup, seeds the system + Coach accounts).
|
||||
DB: D1Database
|
||||
// Shared match-presence KV (owned by the `match` worker). On account creation
|
||||
// the new player's presence is seeded to the Orientation room so the match
|
||||
// heartbeat keeps them there instead of bouncing them to the dorm.
|
||||
MATCH_PRESENCE: KVNamespace
|
||||
}
|
||||
|
||||
/** Variables can be extended */
|
||||
|
||||
@@ -1,10 +1,45 @@
|
||||
import { env } from 'cloudflare:test'
|
||||
import { exports } from 'cloudflare:workers'
|
||||
import { describe, expect, test } from 'vitest'
|
||||
import { beforeAll, describe, expect, test } from 'vitest'
|
||||
|
||||
import '../../auth.app'
|
||||
|
||||
import { SCHEMA_DDL } from '../../accounts-db'
|
||||
|
||||
import type { Env } from '../../context'
|
||||
|
||||
declare module 'cloudflare:test' {
|
||||
interface ProvidedEnv extends Env {}
|
||||
}
|
||||
|
||||
const ORIGIN = 'https://auth.rec.djdevin.net'
|
||||
|
||||
// The Orientation room (RoomId 13) new accounts are placed into on signup.
|
||||
const ORIENTATION_SCENE = 'c79709d8-a31b-48aa-9eb8-cc31ba9505e8'
|
||||
|
||||
// Apply the accounts schema so create_account can persist (mirrors the migration),
|
||||
// and seed the Orientation room (owned by the rooms worker) so signup can place
|
||||
// the new player there.
|
||||
beforeAll(async () => {
|
||||
for (const stmt of SCHEMA_DDL) await env.DB.prepare(stmt).run()
|
||||
await env.DB.prepare(
|
||||
`CREATE TABLE IF NOT EXISTS rooms (
|
||||
data TEXT NOT NULL,
|
||||
room_id INTEGER GENERATED ALWAYS AS (json_extract(data, '$.RoomId')) VIRTUAL
|
||||
)`
|
||||
).run()
|
||||
await env.DB.prepare('INSERT OR IGNORE INTO rooms (data) VALUES (?1)')
|
||||
.bind(
|
||||
JSON.stringify({
|
||||
RoomId: 13,
|
||||
Name: 'Orientation',
|
||||
IsDorm: false,
|
||||
SubRooms: [{ SubRoomId: 23, UnitySceneId: ORIENTATION_SCENE, MaxPlayers: 1 }],
|
||||
})
|
||||
)
|
||||
.run()
|
||||
})
|
||||
|
||||
/** Decode a JWT payload (no verification) for asserting claims. */
|
||||
function decodePayload(token: string): Record<string, unknown> {
|
||||
const part = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')
|
||||
@@ -87,11 +122,32 @@ describe('auth worker routes', () => {
|
||||
expect(payload.sub).toBe('1')
|
||||
})
|
||||
|
||||
test('POST /connect/token grant_type=create_account mints a new account id', async () => {
|
||||
test('POST /connect/token grant_type=create_account persists a new account', async () => {
|
||||
const payload = await tokenFor('grant_type=create_account&platform_id=steam-123')
|
||||
// The token's sub is the new account id, allocated above the system accounts.
|
||||
const sub = Number.parseInt(payload.sub as string, 10)
|
||||
expect(sub).toBeGreaterThanOrEqual(10000)
|
||||
expect(sub).toBeLessThanOrEqual(99999)
|
||||
expect(sub).toBeGreaterThanOrEqual(2)
|
||||
// The account exists in the DB with an auto-assigned (non-default) username.
|
||||
const row = await env.DB.prepare('SELECT data FROM accounts WHERE account_id = ?1')
|
||||
.bind(sub)
|
||||
.first<{ data: string }>()
|
||||
expect(row).not.toBeNull()
|
||||
const account = JSON.parse(row!.data) as { Username: string }
|
||||
expect(account.Username).not.toMatch(/^Player\d+$/)
|
||||
})
|
||||
|
||||
test('POST /connect/token create_account seeds the new player into Orientation', async () => {
|
||||
const payload = await tokenFor('grant_type=create_account&platform_id=steam-456')
|
||||
const sub = payload.sub as string
|
||||
const presence = await env.MATCH_PRESENCE.get<{
|
||||
roomInstance: { roomId: number; location: string; name: string }
|
||||
}>(`presence:${sub}`, 'json')
|
||||
expect(presence).not.toBeNull()
|
||||
expect(presence!.roomInstance).toMatchObject({
|
||||
roomId: 13,
|
||||
location: ORIENTATION_SCENE,
|
||||
name: '^Orientation',
|
||||
})
|
||||
})
|
||||
|
||||
test('POST /connect/token maps the platform int to its enum name', async () => {
|
||||
|
||||
Reference in New Issue
Block a user