mirror of
https://github.com/djdevin/recflare.git
synced 2026-09-09 07:01:27 -07:00
almost into a room
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
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
|
||||
}
|
||||
|
||||
/** Variables can be extended */
|
||||
export type Variables = SharedHonoVariables
|
||||
|
||||
export interface App extends HonoApp {
|
||||
Bindings: Env
|
||||
Variables: Variables
|
||||
}
|
||||
@@ -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,159 @@
|
||||
import { Hono } from 'hono'
|
||||
import { useWorkersLogger } from 'workers-tagged-logger'
|
||||
|
||||
import { withNotFound, withOnError } from '@repo/hono-helpers'
|
||||
|
||||
import type { App } from './context'
|
||||
import type { Context } from 'hono'
|
||||
import { validateAndGetAccountId } from './jwt'
|
||||
|
||||
/**
|
||||
* Ported from the C# `MatchmakingController`. Endpoints the C# backs with EF Core
|
||||
* (`AppDbContext`) are stubbed here — there's no DB binding yet, so room/player
|
||||
* lookups fall back to the same defaults the C# uses when nothing is found.
|
||||
*
|
||||
* Auth-gated routes still validate the Bearer JWT issued by the `auth` worker.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Default `/player` payload. The C# serves this from `JSON/getplayer.json`
|
||||
* whenever the `id` is missing/invalid or the account isn't found; Workers have
|
||||
* no filesystem so it's inlined here.
|
||||
*/
|
||||
const DEFAULT_GET_PLAYER = [
|
||||
{
|
||||
playerId: 1,
|
||||
statusVisibility: 0,
|
||||
deviceClass: 0,
|
||||
vrMovementMode: 1,
|
||||
roomInstance: null,
|
||||
isOnline: true,
|
||||
appVersion: '20210129',
|
||||
platform: 0,
|
||||
},
|
||||
]
|
||||
|
||||
/** Heartbeat body posted by the client (all fields optional). */
|
||||
interface HeartbeatRequest {
|
||||
playerId?: number
|
||||
statusVisibility?: number
|
||||
deviceClass?: number
|
||||
vrMovementMode?: number
|
||||
appVersion?: string | null
|
||||
platform?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the account id from a Bearer token, mirroring the repeated
|
||||
* auth-header check in the C#. 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)
|
||||
}
|
||||
|
||||
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())
|
||||
|
||||
// ---- Player presence -----------------------------------------------------
|
||||
.post('/player/login', (c) => c.body(null, 200))
|
||||
|
||||
.get('/player', (c) => {
|
||||
// C# loads the account + its active RoomInstance; without a DB binding it
|
||||
// always falls through to the JSON/getplayer.json default.
|
||||
// TODO: build the per-account payload once a DB binding exists.
|
||||
return c.json(DEFAULT_GET_PLAYER)
|
||||
})
|
||||
|
||||
.post('/player/heartbeat', async (c) => {
|
||||
const id = await authedId(c)
|
||||
if (id === null) return unauthorized(c)
|
||||
|
||||
// Body may be a JSON HeartbeatRequest or a form post; only JSON is read.
|
||||
const raw = await c.req.text().catch(() => '')
|
||||
let hb: HeartbeatRequest = {}
|
||||
if (raw.trimStart().startsWith('{')) {
|
||||
try {
|
||||
hb = JSON.parse(raw) as HeartbeatRequest
|
||||
} catch {
|
||||
hb = {}
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: look up the player's active RoomInstance once a DB binding exists.
|
||||
return c.json({
|
||||
playerId: hb.playerId ? hb.playerId : id,
|
||||
statusVisibility: hb.statusVisibility ?? 0,
|
||||
deviceClass: hb.deviceClass ?? 0,
|
||||
vrMovementMode: hb.vrMovementMode ? hb.vrMovementMode : 1,
|
||||
roomInstance: null,
|
||||
isOnline: false,
|
||||
appVersion: hb.appVersion ?? '',
|
||||
platform: hb.platform ?? 0,
|
||||
})
|
||||
})
|
||||
|
||||
.put('/player/statusvisibility', (c) => c.body(null, 200)) // TODO: add functionality
|
||||
|
||||
// ---- Room navigation -----------------------------------------------------
|
||||
.post('/goto/room/:room', async (c) => {
|
||||
const id = await authedId(c)
|
||||
if (id === null) return unauthorized(c)
|
||||
// No Rooms binding → the room can never be found (C# returns NotFound here).
|
||||
// TODO: resolve the Room, upsert a RoomInstance, and return it.
|
||||
return c.text('Room not found', 404)
|
||||
})
|
||||
|
||||
.post('/goto/none', (c) =>
|
||||
// Offline dorm — fully static in the C# source.
|
||||
c.json({
|
||||
errorCode: 0,
|
||||
roomInstance: {
|
||||
roomInstanceId: 1,
|
||||
roomId: 1,
|
||||
subRoomId: 1,
|
||||
roomInstanceType: 2,
|
||||
location: '76d98498-60a1-430c-ab76-b54a29b7a163',
|
||||
dataBlob: '',
|
||||
eventId: 0,
|
||||
clubId: 0,
|
||||
photonRegionId: 'us',
|
||||
photonRoomId: crypto.randomUUID(),
|
||||
name: 'DormRoom',
|
||||
maxCapacity: 4,
|
||||
isFull: false,
|
||||
isPrivate: true,
|
||||
isInProgress: false,
|
||||
EncryptVoiceChat: false,
|
||||
},
|
||||
})
|
||||
)
|
||||
|
||||
// ---- Room instance -------------------------------------------------------
|
||||
.post('/roominstance/:id/reportjoinresult', (c) => c.body(null, 200))
|
||||
|
||||
export default app
|
||||
@@ -0,0 +1,114 @@
|
||||
import { exports } from 'cloudflare:workers'
|
||||
import { describe, expect, test } from 'vitest'
|
||||
|
||||
import '../../match.app'
|
||||
|
||||
const ORIGIN = 'https://match.rec.djdevin.net'
|
||||
|
||||
// Mint a token the way the `auth` worker does, using the same dev secret, so the
|
||||
// match worker's validation accepts it. Kept inline to avoid a cross-package
|
||||
// import.
|
||||
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)}` }
|
||||
}
|
||||
|
||||
describe('public endpoints', () => {
|
||||
test('POST /player/login returns 200', async () => {
|
||||
const res = await exports.default.fetch(`${ORIGIN}/player/login`, { method: 'POST' })
|
||||
expect(res.status).toBe(200)
|
||||
})
|
||||
|
||||
test('GET /player returns the default payload', async () => {
|
||||
const res = await exports.default.fetch(`${ORIGIN}/player?id=99`)
|
||||
expect(res.status).toBe(200)
|
||||
const players = (await res.json()) as Array<{ playerId: number; isOnline: boolean }>
|
||||
expect(players[0]).toMatchObject({ playerId: 1, isOnline: true, appVersion: '20210129' })
|
||||
})
|
||||
|
||||
test('POST /goto/none returns the offline dorm', async () => {
|
||||
const res = await exports.default.fetch(`${ORIGIN}/goto/none`, { method: 'POST' })
|
||||
expect(res.status).toBe(200)
|
||||
const body = (await res.json()) as {
|
||||
errorCode: number
|
||||
roomInstance: { name: string; location: string; photonRoomId: string }
|
||||
}
|
||||
expect(body.errorCode).toBe(0)
|
||||
expect(body.roomInstance).toMatchObject({
|
||||
name: 'DormRoom',
|
||||
location: '76d98498-60a1-430c-ab76-b54a29b7a163',
|
||||
isPrivate: true,
|
||||
})
|
||||
expect(body.roomInstance.photonRoomId).toMatch(/^[0-9a-f-]{36}$/)
|
||||
})
|
||||
|
||||
test('PUT /player/statusvisibility returns 200', async () => {
|
||||
const res = await exports.default.fetch(`${ORIGIN}/player/statusvisibility`, { method: 'PUT' })
|
||||
expect(res.status).toBe(200)
|
||||
})
|
||||
|
||||
test('POST /roominstance/:id/reportjoinresult returns 200', async () => {
|
||||
const res = await exports.default.fetch(`${ORIGIN}/roominstance/5/reportjoinresult`, {
|
||||
method: 'POST',
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
})
|
||||
})
|
||||
|
||||
describe('auth-gated endpoints', () => {
|
||||
test('POST /goto/room/:room 401s without a token', async () => {
|
||||
const res = await exports.default.fetch(`${ORIGIN}/goto/room/dormroom`, { method: 'POST' })
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
test('POST /goto/room/:room 404s with a valid token (no DB)', async () => {
|
||||
const res = await exports.default.fetch(`${ORIGIN}/goto/room/dormroom`, {
|
||||
method: 'POST',
|
||||
headers: await bearer(),
|
||||
})
|
||||
expect(res.status).toBe(404)
|
||||
})
|
||||
|
||||
test('POST /player/heartbeat 401s without a token', async () => {
|
||||
const res = await exports.default.fetch(`${ORIGIN}/player/heartbeat`, { method: 'POST' })
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
test('POST /player/heartbeat echoes the body and defaults playerId to the token id', async () => {
|
||||
const res = await exports.default.fetch(`${ORIGIN}/player/heartbeat`, {
|
||||
method: 'POST',
|
||||
headers: { ...(await bearer()), 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ statusVisibility: 2, platform: 5, appVersion: '20210129' }),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toMatchObject({
|
||||
playerId: 42,
|
||||
statusVisibility: 2,
|
||||
vrMovementMode: 1,
|
||||
roomInstance: null,
|
||||
isOnline: false,
|
||||
appVersion: '20210129',
|
||||
platform: 5,
|
||||
})
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user