add rooms

This commit is contained in:
Devin Zuczek
2026-06-14 18:59:35 -04:00
parent 767dd47bab
commit 768ca2a0a3
64 changed files with 87267 additions and 787 deletions
+34 -7
View File
@@ -11,6 +11,20 @@ import type { App } from './context'
const TOKEN_SCOPE =
'offline_access profile rn rn.accounts rn.accounts.gc rn.api rn.chat rn.clubs rn.commerce rn.match.read rn.match.write rn.notify rn.rooms rn.storage'
/** C# `PlatformType` enum names by value, used for the token's `platform` claim. */
const PLATFORM_TYPES: Record<number, string> = {
[-1]: 'All',
0: 'Steam',
1: 'Oculus',
2: 'PlayStation',
3: 'Xbox',
4: 'RecNet',
5: 'IOS',
6: 'GooglePlay',
7: 'Standalone',
8: 'Pico',
}
const app = new Hono<App>()
.use(
'*',
@@ -46,17 +60,30 @@ const app = new Hono<App>()
// OAuth token endpoint — accepts a form-urlencoded body and issues a JWT.
.post('/connect/token', async (c) => {
let accountId = '1'
let platformId = ''
// `platform` is never populated from the body in the C# source either.
const platform = ''
// The C# reads `grant_type`, `account_id`, `platform_id` and `platform` from
// the form body.
const body = await c.req.parseBody().catch(() => ({}) as Record<string, unknown>)
console.log(body)
const grantType = typeof body.grant_type === 'string' ? body.grant_type : ''
const platformId = typeof body.platform_id === 'string' ? body.platform_id : ''
// `platform` is the PlatformType int → its enum name (e.g. 0 → "Steam").
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,
// 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'
const accessToken = await generateToken(accountId, platformId, platform)
// TODO: once a DB binding exists, remove any RoomInstance owned by accountId.
// TODO: once a DB binding exists, create the account + dorm on create_account
// and remove any RoomInstance owned by accountId on login.
return c.json({
access_token: accessToken,
+39 -3
View File
@@ -18,6 +18,27 @@ function base64url(input: ArrayBuffer | string): string {
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
}
/** Scopes the C# `JwtTokenService` stamps onto every token (as a claim array). */
const TOKEN_SCOPES = [
'profile',
'rn',
'rn.accounts',
'rn.accounts.gc',
'rn.api',
'rn.chat',
'rn.clubs',
'rn.commerce',
'rn.match.read',
'rn.match.write',
'rn.notify',
'rn.rooms',
'rn.storage',
'offline_access',
]
/** Roles the C# grants — the client needs `gameClient` to operate. */
const TOKEN_ROLES = ['gameClient', 'developer', 'moderator']
export async function generateToken(
accountId: string,
platformId: string,
@@ -26,12 +47,27 @@ export async function generateToken(
): Promise<string> {
const now = Math.floor(Date.now() / 1000)
const header = { alg: 'HS256', typ: 'JWT' }
// Mirror the claim set produced by the C# `JwtTokenService.GenerateToken`.
// The client reads `role`/`scope` (and expects a well-formed iss/aud) to
// authorize itself; a token with only `sub` is rejected before login finishes.
const payload = {
sub: accountId,
platform_id: platformId,
platform,
iss: 'https://auth.lapis.codes',
aud: 'https://auth.lapis.codes/resources',
nbf: now,
iat: now,
exp: now + TOKEN_TTL_SECONDS,
auth_time: now,
amr: 'cached_login',
client_id: 'recroom',
sub: accountId,
idp: 'local',
platform,
platform_id: platformId,
'rn.ver': '20210129',
'rn.plat': '0',
role: TOKEN_ROLES,
scope: TOKEN_SCOPES,
jti: crypto.randomUUID().replace(/-/g, '').toUpperCase(),
}
const signingInput = `${base64url(JSON.stringify(header))}.${base64url(JSON.stringify(payload))}`
+68 -6
View File
@@ -5,21 +5,41 @@ import '../../auth.app'
const ORIGIN = 'https://auth.rec.djdevin.net'
/** 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, '/')
return JSON.parse(
new TextDecoder().decode(Uint8Array.from(atob(part), (ch) => ch.charCodeAt(0)))
) as Record<string, unknown>
}
async function tokenFor(body: string): Promise<Record<string, unknown>> {
const res = await exports.default.fetch(`${ORIGIN}/connect/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body,
})
const { access_token } = (await res.json()) as { access_token: string }
return decodePayload(access_token)
}
describe('auth worker routes', () => {
test('GET /eac/challenge returns a JSON-quoted GUID', async () => {
test('GET /eac/challenge returns the EAC challenge as text/plain', async () => {
const res = await exports.default.fetch(`${ORIGIN}/eac/challenge`)
expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toContain('text/plain')
expect(await res.text()).toMatch(/^"[0-9a-f-]{36}"$/)
// Matches the C#'s JSON/eacchallenge.txt content (BOM is stripped on read).
expect(await res.text()).toBe('"AA=="')
})
test('GET /cachedlogin/forplatformid/:platform/:id returns empty list', async () => {
test('GET /cachedlogin/forplatformid/:platform/:id returns a cached login', async () => {
const res = await exports.default.fetch(`${ORIGIN}/cachedlogin/forplatformid/1/abc123`)
expect(res.status).toBe(200)
expect(await res.json()).toEqual([])
const logins = (await res.json()) as Array<{ accountId: number }>
expect(logins[0]).toMatchObject({ accountId: 1 })
})
test('POST /connect/token issues a bearer token', async () => {
test('POST /connect/token issues a bearer token with role/scope claims', async () => {
const res = await exports.default.fetch(`${ORIGIN}/connect/token`, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
@@ -34,7 +54,49 @@ describe('auth worker routes', () => {
expect(json.token_type).toBe('Bearer')
expect(json.expires_in).toBe(3600)
// header.payload.signature
expect(json.access_token.split('.')).toHaveLength(3)
const parts = json.access_token.split('.')
expect(parts).toHaveLength(3)
// The client reads these claims to authorize itself; decode and assert them.
const payload = JSON.parse(
new TextDecoder().decode(
Uint8Array.from(atob(parts[1].replace(/-/g, '+').replace(/_/g, '/')), (ch) =>
ch.charCodeAt(0)
)
)
) as Record<string, unknown>
expect(payload.sub).toBe('42') // account_id from the body is honored
expect(payload.iss).toBe('https://auth.lapis.codes')
expect(payload.aud).toBe('https://auth.lapis.codes/resources')
expect(payload.role).toContain('gameClient')
expect(payload.scope).toContain('rn.api')
})
test('POST /connect/token falls back to account 1 when no account_id is posted', async () => {
const res = await exports.default.fetch(`${ORIGIN}/connect/token`, { method: 'POST' })
expect(res.status).toBe(200)
const { access_token } = (await res.json()) as { access_token: string }
const payload = JSON.parse(
new TextDecoder().decode(
Uint8Array.from(
atob(access_token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')),
(ch) => ch.charCodeAt(0)
)
)
) as { sub: string }
expect(payload.sub).toBe('1')
})
test('POST /connect/token grant_type=create_account mints a new account id', async () => {
const payload = await tokenFor('grant_type=create_account&platform_id=steam-123')
const sub = Number.parseInt(payload.sub as string, 10)
expect(sub).toBeGreaterThanOrEqual(10000)
expect(sub).toBeLessThanOrEqual(99999)
})
test('POST /connect/token maps the platform int to its enum name', async () => {
const payload = await tokenFor('account_id=42&platform=0')
expect(payload.platform).toBe('Steam')
})
test('GET /role/developer/:id returns ok', async () => {