mirror of
https://github.com/djdevin/recflare.git
synced 2026-09-08 22:51:30 -07:00
add rooms
This commit is contained in:
@@ -3,12 +3,32 @@ import { useWorkersLogger } from 'workers-tagged-logger'
|
||||
|
||||
import { withNotFound, withOnError } from '@repo/hono-helpers'
|
||||
|
||||
import { validateAndGetAccountId } from './jwt'
|
||||
|
||||
import type { Context } from 'hono'
|
||||
import type { App } from './context'
|
||||
|
||||
/**
|
||||
* Ported from the C# `ClubsController`. The only endpoint always returned
|
||||
* `Results.NotFound()` in the source — no DB binding involved.
|
||||
* Ported from the C# `ClubsController`. The only endpoint is `[Authorize]` and
|
||||
* then returns `Results.NotFound()` unconditionally — no DB binding involved.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Resolve the account id from a Bearer token. 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
|
||||
}
|
||||
|
||||
const app = new Hono<App>()
|
||||
.use(
|
||||
'*',
|
||||
@@ -23,7 +43,22 @@ const app = new Hono<App>()
|
||||
.onError(withOnError())
|
||||
.notFound(withNotFound())
|
||||
|
||||
// No club home yet — the C# source returns NotFound here unconditionally.
|
||||
.get('/club/home/me', (c) => c.notFound())
|
||||
// [Authorize] → 401 without a valid token. The C# returns NotFound here, but
|
||||
// the client treats that 404 as an error, so we return an empty object stub.
|
||||
.get('/club/home/me', async (c) => {
|
||||
const id = await authedId(c)
|
||||
if (id === null) return c.body(null, 401)
|
||||
return c.json({})
|
||||
})
|
||||
|
||||
// Not present in CannedNet — a real Rec Room client endpoint the C# never
|
||||
// implemented. The client calls it on the clubs host at /subscription/mine/member
|
||||
// (no /club prefix) and sends no auth header, so it isn't gated. Returns an
|
||||
// empty array = no club subscription memberships (the client chokes on null).
|
||||
.get('/subscription/mine/member', (c) => c.json([]))
|
||||
|
||||
// Details for a given subscription. Also not in CannedNet; the client
|
||||
// deserializes this into an object, so it must return `{}` (not `[]`).
|
||||
.get('/subscription/details/:subscription', (c) => c.json({}))
|
||||
|
||||
export default app
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -5,10 +5,55 @@ import '../../clubs.app'
|
||||
|
||||
const ORIGIN = 'https://clubs.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)}` }
|
||||
}
|
||||
|
||||
describe('clubs endpoints', () => {
|
||||
test('GET /club/home/me returns 404', async () => {
|
||||
test('GET /club/home/me 401s without a token', async () => {
|
||||
const res = await exports.default.fetch(`${ORIGIN}/club/home/me`)
|
||||
expect(res.status).toBe(404)
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
test('GET /club/home/me returns an empty object with a valid token', async () => {
|
||||
const res = await exports.default.fetch(`${ORIGIN}/club/home/me`, { headers: await bearer() })
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({})
|
||||
})
|
||||
|
||||
test('GET /subscription/mine/member returns an empty array without a token', async () => {
|
||||
// The client calls this on the clubs host with no /club prefix and no auth.
|
||||
const res = await exports.default.fetch(`${ORIGIN}/subscription/mine/member`)
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual([])
|
||||
})
|
||||
|
||||
test('GET /subscription/details/:subscription returns an empty object', async () => {
|
||||
const res = await exports.default.fetch(`${ORIGIN}/subscription/details/rrplus`)
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({})
|
||||
})
|
||||
|
||||
test('unknown routes 404', async () => {
|
||||
|
||||
Reference in New Issue
Block a user