mirror of
https://github.com/djdevin/recflare.git
synced 2026-09-09 15:11:29 -07:00
add playersettings, img, more match endpoints
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
import type { HonoApp } from '@repo/hono-helpers'
|
||||
import type { SharedHonoEnv, SharedHonoVariables } from '@repo/hono-helpers/src/types'
|
||||
|
||||
export type Env = SharedHonoEnv & {
|
||||
/** Per-player settings store. Key `player:<id>` → JSON map of `{ key: value }`. */
|
||||
PLAYER_SETTINGS: KVNamespace
|
||||
}
|
||||
|
||||
/** Variables can be extended */
|
||||
export type Variables = SharedHonoVariables
|
||||
|
||||
export interface App extends HonoApp {
|
||||
Bindings: Env
|
||||
Variables: Variables
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
* Default player settings seeded on a player's first read, ported verbatim from
|
||||
* the C# `PlayerSettingsController.GetPlayerSettings`. Ordered; written to KV the
|
||||
* first time a player has no stored settings.
|
||||
*/
|
||||
export const DEFAULT_SETTINGS: Array<{ Key: string; Value: string }> = [
|
||||
{ Key: 'Recroom.OOBE', Value: '77' },
|
||||
{
|
||||
Key: 'SplitTestAssignedSegments',
|
||||
Value:
|
||||
'1|{"SplitTesting+PhotonMaxDatagrams_2021_01_11":"Off","SplitTesting+Curated_Rooms_2020_08_06":"Off","SplitTesting+RoomRecommendationsType_2020_08_14":"Aug14MinVisitors35000"}',
|
||||
},
|
||||
{ Key: 'PlayerSessionCount', Value: '13' },
|
||||
{ Key: 'TUTORIAL_COMPLETE_MASK', Value: '11' },
|
||||
{ Key: 'BACKPACK_FAVORITE_TOOL', Value: '1' },
|
||||
{ Key: 'VoiceChat', Value: '2' },
|
||||
{ Key: 'VRAUTOSPRINT', Value: '1' },
|
||||
{ Key: 'VR_MOVEMENT_MODE', Value: '0' },
|
||||
{ Key: 'COMFORT_SPRINT', Value: '0' },
|
||||
{ Key: 'COMFORT_WALK', Value: '0' },
|
||||
{ Key: 'COMFORT_VEHICLES', Value: '0' },
|
||||
{ Key: 'COMFORT_FLY', Value: '0' },
|
||||
{ Key: 'COMFORT_ROTATE', Value: '0' },
|
||||
{ Key: 'COMFORT_FORCES', Value: '0' },
|
||||
{ Key: 'COMFORT_FALL', Value: '0' },
|
||||
{ Key: 'COMFORT_TELEPORT', Value: '0' },
|
||||
{ Key: 'ROTATE_IN_PLACE_ENABLED', Value: '1' },
|
||||
{ Key: 'ROTATION_INCREMENT', Value: '2' },
|
||||
{ Key: 'CONTINUOUS_ROTATION_MODE', Value: '1' },
|
||||
{ Key: 'DONT_LOCK_TOOLS_TO_HAND', Value: '0' },
|
||||
{ Key: 'QualitySettings', Value: '2' },
|
||||
{ Key: 'TeleportBuffer', Value: '0' },
|
||||
{ Key: 'IgnoreBuffer', Value: '1' },
|
||||
{ Key: 'FIRST_TIME_IN_FLAGS', Value: '0' },
|
||||
{ Key: 'ShowRoomCenter', Value: '1' },
|
||||
{ Key: 'USER_TRACKING', Value: '1' },
|
||||
{ Key: 'STABILIZE_HANDS', Value: '0' },
|
||||
{ Key: 'MakerPen_SnappingMode', Value: '2' },
|
||||
{ Key: 'Recroom.ChallengeMap', Value: '17' },
|
||||
{ Key: 'VoiceFilter2', Value: '1' },
|
||||
{ Key: 'SFX_VOLUME_PERCENT_PREF', Value: '1' },
|
||||
]
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* Minimal HS256 JWT validation, mirroring the C# `JwtTokenService.ValidateAndGetAccountId`.
|
||||
*
|
||||
* Uses the same placeholder dev secret as the `auth` worker (`apps/auth/src/jwt.ts`).
|
||||
* Swap both for a shared secret binding before this is used for anything real.
|
||||
*/
|
||||
const DEV_SECRET = 'dev-insecure-signing-key-change-me'
|
||||
|
||||
function base64urlToBytes(input: string): Uint8Array {
|
||||
const padded = input.replace(/-/g, '+').replace(/_/g, '/')
|
||||
const binary = atob(padded + '='.repeat((4 - (padded.length % 4)) % 4))
|
||||
const bytes = new Uint8Array(binary.length)
|
||||
for (let i = 0; i < binary.length; i++) {
|
||||
bytes[i] = binary.charCodeAt(i)
|
||||
}
|
||||
return bytes
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an HS256 token and return its `sub` (account id) claim, or `null`
|
||||
* when the token is malformed, has a bad signature, or is expired.
|
||||
*/
|
||||
export async function validateAndGetAccountId(
|
||||
token: string,
|
||||
secret: string = DEV_SECRET
|
||||
): Promise<string | null> {
|
||||
const parts = token.split('.')
|
||||
if (parts.length !== 3) return null
|
||||
const [header, payload, signature] = parts
|
||||
|
||||
const key = await crypto.subtle.importKey(
|
||||
'raw',
|
||||
new TextEncoder().encode(secret),
|
||||
{ name: 'HMAC', hash: 'SHA-256' },
|
||||
false,
|
||||
['verify']
|
||||
)
|
||||
const valid = await crypto.subtle.verify(
|
||||
'HMAC',
|
||||
key,
|
||||
base64urlToBytes(signature),
|
||||
new TextEncoder().encode(`${header}.${payload}`)
|
||||
)
|
||||
if (!valid) return null
|
||||
|
||||
let claims: { sub?: string; exp?: number }
|
||||
try {
|
||||
claims = JSON.parse(new TextDecoder().decode(base64urlToBytes(payload)))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
|
||||
if (typeof claims.exp === 'number' && claims.exp < Math.floor(Date.now() / 1000)) {
|
||||
return null
|
||||
}
|
||||
|
||||
return claims.sub ?? null
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { Hono } from 'hono'
|
||||
import { useWorkersLogger } from 'workers-tagged-logger'
|
||||
|
||||
import { withNotFound, withOnError } from '@repo/hono-helpers'
|
||||
|
||||
import { DEFAULT_SETTINGS } from './default-settings'
|
||||
import { validateAndGetAccountId } from './jwt'
|
||||
|
||||
import type { Context } from 'hono'
|
||||
import type { App } from './context'
|
||||
|
||||
/**
|
||||
* Resolve the account id from a Bearer token (the C# action is `[Authorize]`).
|
||||
* Returns `null` when the header is missing, the token is invalid, or the `sub`
|
||||
* claim isn't an integer.
|
||||
*/
|
||||
async function authedId(c: Context<App>): Promise<number | null> {
|
||||
const authHeader = c.req.header('Authorization') ?? ''
|
||||
if (!authHeader.toLowerCase().startsWith('bearer ')) return null
|
||||
|
||||
const token = authHeader.slice('Bearer '.length)
|
||||
const accountId = await validateAndGetAccountId(token)
|
||||
if (!accountId) return null
|
||||
|
||||
const id = Number.parseInt(accountId, 10)
|
||||
return Number.isNaN(id) ? null : id
|
||||
}
|
||||
|
||||
/** Results.Unauthorized() equivalent — 401 with empty body. */
|
||||
function unauthorized(c: Context<App>) {
|
||||
return c.body(null, 401)
|
||||
}
|
||||
|
||||
/**
|
||||
* Pull `{ key, value }` pairs out of a PUT body. Mirrors the C#: a
|
||||
* form-urlencoded `key`/`value`, or a JSON body (single object or array).
|
||||
* Entries with an empty key are dropped.
|
||||
*/
|
||||
async function parseSettings(c: Context<App>): Promise<Array<{ key: string; value: string }>> {
|
||||
const contentType = c.req.header('content-type') ?? ''
|
||||
|
||||
if (contentType.includes('application/json')) {
|
||||
const body = await c.req.json<unknown>().catch(() => null)
|
||||
const list = Array.isArray(body) ? body : body == null ? [] : [body]
|
||||
return list
|
||||
.map((o) => {
|
||||
const rec = o as Record<string, unknown>
|
||||
const key = rec.key ?? rec.Key
|
||||
const value = rec.value ?? rec.Value
|
||||
return {
|
||||
key: typeof key === 'string' ? key : '',
|
||||
value:
|
||||
typeof value === 'string'
|
||||
? value
|
||||
: typeof value === 'number' || typeof value === 'boolean'
|
||||
? String(value)
|
||||
: '',
|
||||
}
|
||||
})
|
||||
.filter((s) => s.key !== '')
|
||||
}
|
||||
|
||||
// form-urlencoded / multipart
|
||||
const form = await c.req.parseBody().catch(() => ({}) as Record<string, unknown>)
|
||||
const key = typeof form.key === 'string' ? form.key : ''
|
||||
const value = typeof form.value === 'string' ? form.value : ''
|
||||
return key ? [{ key, value }] : []
|
||||
}
|
||||
|
||||
const app = new Hono<App>()
|
||||
.use(
|
||||
'*',
|
||||
// middleware
|
||||
(c, next) =>
|
||||
useWorkersLogger(c.env.NAME, {
|
||||
environment: c.env.ENVIRONMENT,
|
||||
release: c.env.SENTRY_RELEASE,
|
||||
})(c, next)
|
||||
)
|
||||
|
||||
.onError(withOnError())
|
||||
.notFound(withNotFound())
|
||||
|
||||
.get('/', (c) => c.json({ service: 'playersettings', status: 'ok' }))
|
||||
|
||||
// The authenticated player's settings as `{ PlayerId, Key, Value }`. Reads
|
||||
// the per-player KV map; seeds (and persists) the C# defaults on first read.
|
||||
.get('/playersettings', async (c) => {
|
||||
const id = await authedId(c)
|
||||
if (id === null) return unauthorized(c)
|
||||
|
||||
const kvKey = `player:${id}`
|
||||
let stored = await c.env.PLAYER_SETTINGS.get<Record<string, string>>(kvKey, 'json')
|
||||
if (!stored || Object.keys(stored).length === 0) {
|
||||
stored = Object.fromEntries(DEFAULT_SETTINGS.map((s) => [s.Key, s.Value]))
|
||||
await c.env.PLAYER_SETTINGS.put(kvKey, JSON.stringify(stored))
|
||||
}
|
||||
|
||||
return c.json(Object.entries(stored).map(([Key, Value]) => ({ PlayerId: id, Key, Value })))
|
||||
})
|
||||
|
||||
// Upsert player settings into KV, keyed by the authenticated player id.
|
||||
// The C# replaces the player's entire set; we merge so individual key PUTs
|
||||
// (e.g. `key=PlayerSessionCount&value=1`) don't wipe the rest.
|
||||
.put('/playersettings', async (c) => {
|
||||
const id = await authedId(c)
|
||||
if (id === null) return unauthorized(c)
|
||||
|
||||
const incoming = await parseSettings(c)
|
||||
if (incoming.length === 0) return c.body(null, 200)
|
||||
|
||||
const kvKey = `player:${id}`
|
||||
const existing = await c.env.PLAYER_SETTINGS.get<Record<string, string>>(kvKey, 'json')
|
||||
const merged: Record<string, string> = { ...existing }
|
||||
for (const { key, value } of incoming) merged[key] = value
|
||||
|
||||
await c.env.PLAYER_SETTINGS.put(kvKey, JSON.stringify(merged))
|
||||
return c.body(null, 200)
|
||||
})
|
||||
|
||||
export default app
|
||||
@@ -0,0 +1,113 @@
|
||||
import { env, SELF } from 'cloudflare:test'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import '../../playersettings.app'
|
||||
|
||||
import type { Env } from '../../context'
|
||||
|
||||
declare module 'cloudflare:test' {
|
||||
interface ProvidedEnv extends Env {}
|
||||
}
|
||||
|
||||
const ORIGIN = 'https://playersettings.rec.djdevin.net'
|
||||
|
||||
// Mint a token the way the `auth` worker does, using the same dev secret.
|
||||
const DEV_SECRET = 'dev-insecure-signing-key-change-me'
|
||||
|
||||
function b64url(input: ArrayBuffer | string): string {
|
||||
const bytes = typeof input === 'string' ? new TextEncoder().encode(input) : new Uint8Array(input)
|
||||
let binary = ''
|
||||
for (const byte of bytes) binary += String.fromCharCode(byte)
|
||||
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
||||
}
|
||||
|
||||
async function bearer(sub = '42'): Promise<Record<string, string>> {
|
||||
const now = Math.floor(Date.now() / 1000)
|
||||
const signingInput = `${b64url(JSON.stringify({ alg: 'HS256', typ: 'JWT' }))}.${b64url(
|
||||
JSON.stringify({ sub, exp: now + 3600 })
|
||||
)}`
|
||||
const key = await crypto.subtle.importKey(
|
||||
'raw',
|
||||
new TextEncoder().encode(DEV_SECRET),
|
||||
{ name: 'HMAC', hash: 'SHA-256' },
|
||||
false,
|
||||
['sign']
|
||||
)
|
||||
const sig = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(signingInput))
|
||||
return { Authorization: `Bearer ${signingInput}.${b64url(sig)}` }
|
||||
}
|
||||
|
||||
function putForm(fields: Record<string, string>, headers: Record<string, string> = {}): RequestInit {
|
||||
return {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded', ...headers },
|
||||
body: new URLSearchParams(fields).toString(),
|
||||
}
|
||||
}
|
||||
|
||||
describe('playersettings endpoints', () => {
|
||||
it('GET / reports service status', async () => {
|
||||
const res = await SELF.fetch(`${ORIGIN}/`)
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ service: 'playersettings', status: 'ok' })
|
||||
})
|
||||
|
||||
it('GET /playersettings 401s without a token', async () => {
|
||||
const res = await SELF.fetch(`${ORIGIN}/playersettings`)
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('GET /playersettings seeds and returns the default settings on first read', async () => {
|
||||
const res = await SELF.fetch(`${ORIGIN}/playersettings`, { headers: await bearer('100') })
|
||||
expect(res.status).toBe(200)
|
||||
const settings = (await res.json()) as Array<{ PlayerId: number; Key: string; Value: string }>
|
||||
expect(settings.length).toBeGreaterThan(0)
|
||||
expect(settings.every((s) => s.PlayerId === 100)).toBe(true)
|
||||
expect(settings.find((s) => s.Key === 'Recroom.OOBE')?.Value).toBe('77')
|
||||
expect(settings.find((s) => s.Key === 'PlayerSessionCount')?.Value).toBe('13')
|
||||
|
||||
// Defaults were persisted to KV.
|
||||
const stored = await env.PLAYER_SETTINGS.get<Record<string, string>>('player:100', 'json')
|
||||
expect(stored?.['Recroom.OOBE']).toBe('77')
|
||||
})
|
||||
|
||||
it('GET /playersettings reflects a value written by PUT', async () => {
|
||||
await SELF.fetch(
|
||||
`${ORIGIN}/playersettings`,
|
||||
putForm({ key: 'PlayerSessionCount', value: '99' }, await bearer('101'))
|
||||
)
|
||||
const res = await SELF.fetch(`${ORIGIN}/playersettings`, { headers: await bearer('101') })
|
||||
const settings = (await res.json()) as Array<{ Key: string; Value: string }>
|
||||
// PUT created the only entry, so GET returns it without seeding defaults.
|
||||
expect(settings).toEqual([{ PlayerId: 101, Key: 'PlayerSessionCount', Value: '99' }])
|
||||
})
|
||||
|
||||
it('PUT /playersettings 401s without a token', async () => {
|
||||
const res = await SELF.fetch(`${ORIGIN}/playersettings`, putForm({ key: 'X', value: '1' }))
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('PUT /playersettings persists the form key/value into KV', async () => {
|
||||
const res = await SELF.fetch(
|
||||
`${ORIGIN}/playersettings`,
|
||||
putForm({ key: 'PlayerSessionCount', value: '1' }, await bearer('7'))
|
||||
)
|
||||
expect(res.status).toBe(200)
|
||||
|
||||
const stored = await env.PLAYER_SETTINGS.get<Record<string, string>>('player:7', 'json')
|
||||
expect(stored).toEqual({ PlayerSessionCount: '1' })
|
||||
})
|
||||
|
||||
it('PUT /playersettings merges instead of replacing', async () => {
|
||||
await SELF.fetch(`${ORIGIN}/playersettings`, putForm({ key: 'A', value: '1' }, await bearer('8')))
|
||||
await SELF.fetch(`${ORIGIN}/playersettings`, putForm({ key: 'B', value: '2' }, await bearer('8')))
|
||||
|
||||
const stored = await env.PLAYER_SETTINGS.get<Record<string, string>>('player:8', 'json')
|
||||
expect(stored).toEqual({ A: '1', B: '2' })
|
||||
})
|
||||
|
||||
it('PUT /playersettings 200s with no parseable settings', async () => {
|
||||
const res = await SELF.fetch(`${ORIGIN}/playersettings`, putForm({}, await bearer('9')))
|
||||
expect(res.status).toBe(200)
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user