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
+148
View File
@@ -0,0 +1,148 @@
import { Hono } from 'hono'
import { useWorkersLogger } from 'workers-tagged-logger'
import { withNotFound, withOnError } from '@repo/hono-helpers'
import loadingScreenTipData from '../static/loading-screen-tip-data.json'
import { validateAndGetAccountId } from './jwt'
import type { Context } from 'hono'
import type { App, Env } from './context'
/**
* Ported from the C# `CDNController`. The class `[Route("cdn")]` prefix maps to
* this worker's subdomain, so method routes are served bare. File-backed routes
* (`sigs`, `upload`) have no storage binding yet and are stubbed.
*/
/**
* 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
}
/** Parse a single-range `Range: bytes=start-end` header into an R2 range. */
function parseRange(header: string | undefined): R2Range | undefined {
if (!header) return undefined
const m = /^bytes=(\d*)-(\d*)$/.exec(header.trim())
if (!m) return undefined
const start = m[1]
const end = m[2]
if (start === '' && end !== '') return { suffix: Number(end) } // last N bytes
if (start !== '') {
return end !== '' ? { offset: Number(start), length: Number(end) - Number(start) + 1 } : { offset: Number(start) }
}
return undefined
}
/**
* Stream a binary asset from the CDN R2 bucket as application/octet-stream
* (matching the C#'s `Results.File(..., "application/octet-stream")`, which also
* honors Range requests). The C# 404s when the file is missing; so do we.
* Supports conditional GET and byte-range requests (206) — large-file
* downloaders fetch in ranges, and a 200 where a 206 is expected corrupts the
* reassembled file (e.g. EAC "Signatures don't match").
*/
async function serveAsset(c: Context<App>, key: string) {
if (key.includes('..')) return c.body(null, 400)
const ifNoneMatch = c.req.header('if-none-match')?.replace(/"/g, '')
const range = parseRange(c.req.header('range'))
const object = await (c.env as Env).CDN_ASSETS.get(key, {
...(ifNoneMatch ? { onlyIf: { etagDoesNotMatch: ifNoneMatch } } : {}),
...(range ? { range } : {}),
})
if (!object) return c.notFound()
const headers = new Headers()
object.writeHttpMetadata(headers)
headers.set('etag', object.httpEtag)
headers.set('content-type', 'application/octet-stream')
headers.set('accept-ranges', 'bytes')
headers.set('cache-control', 'public, max-age=3600')
// Precondition matched (If-None-Match) → R2 returns no body.
if (!('body' in object)) return new Response(null, { status: 304, headers })
// Range honored → 206 Partial Content with Content-Range.
if (object.range && c.req.header('range')) {
const r = object.range
let offset: number
let length: number
if ('suffix' in r) {
length = r.suffix
offset = object.size - length
} else {
offset = r.offset ?? 0
length = r.length ?? object.size - offset
}
headers.set('content-length', String(length))
headers.set('content-range', `bytes ${offset}-${offset + length - 1}/${object.size}`)
return new Response(object.body, { status: 206, headers })
}
return new Response(object.body, { headers })
}
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: 'cdn', status: 'ok' }))
// Loading-screen tips. The C# serves JSON/loadingscreentipdata.json; bundled
// here as static JSON.
.get('/config/LoadingScreenTipData', (c) => c.json(loadingScreenTipData))
// Signature blobs by name (C#: Sigs/ directory). Streamed from R2 under the
// `sigs/` key prefix; 404 when missing.
.get('/sigs/:sigName', (c) => serveAsset(c, `sigs/${c.req.param('sigName')}`))
// Room build data by name (C#: Data/DataBlobs/). The client fetches this for
// a SubRoom's DataBlob to load the room. Streamed from R2 under `room/`.
.get('/room/:dataBlob', (c) => serveAsset(c, `room/${c.req.param('dataBlob')}`))
// Image upload. [Authorize] in the C#; returns the saved filename. No storage
// binding yet, so we accept the file and return a synthesized filename without
// persisting it. TODO: write to an R2 bucket like the `img` worker.
.post('/upload', async (c) => {
const id = await authedId(c)
if (id === null) return c.body(null, 401)
const body = await c.req.parseBody().catch(() => ({}) as Record<string, unknown>)
const file = body.file
if (!(file instanceof File)) {
return c.json({ error: 'No file found in request' }, 400)
}
const validExtensions = ['.png', '.jpg', '.jpeg']
const dot = file.name.lastIndexOf('.')
const rawExt = dot >= 0 ? file.name.slice(dot).toLowerCase() : ''
const extension = validExtensions.includes(rawExt) ? rawExt : '.png'
const filename = crypto.randomUUID().replace(/-/g, '') + extension
// TODO: persist `file` to an R2 bucket under `filename`.
return c.json({ filename })
})
export default app
+17
View File
@@ -0,0 +1,17 @@
import type { HonoApp } from '@repo/hono-helpers'
import type { SharedHonoEnv, SharedHonoVariables } from '@repo/hono-helpers/src/types'
export type Env = SharedHonoEnv & {
// R2 bucket holding CDN binaries: signature blobs under `sigs/<name>` and
// room build data under `room/<name>` (mirrors the C#'s Sigs/ and
// Data/DataBlobs/ directories).
CDN_ASSETS: R2Bucket
}
/** Variables can be extended */
export type Variables = SharedHonoVariables
export interface App extends HonoApp {
Bindings: Env
Variables: Variables
}
+58
View File
@@ -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
}
+120
View File
@@ -0,0 +1,120 @@
import { env } from 'cloudflare:test'
import { exports } from 'cloudflare:workers'
import { describe, expect, test } from 'vitest'
import '../../cdn.app'
import type { Env } from '../../context'
declare module 'cloudflare:test' {
interface ProvidedEnv extends Env {}
}
const ORIGIN = 'https://cdn.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('cdn endpoints', () => {
test('GET / reports service status', async () => {
const res = await exports.default.fetch(`${ORIGIN}/`)
expect(res.status).toBe(200)
expect(await res.json()).toEqual({ service: 'cdn', status: 'ok' })
})
test('GET /config/LoadingScreenTipData returns the tip array', async () => {
const res = await exports.default.fetch(`${ORIGIN}/config/LoadingScreenTipData`)
expect(res.status).toBe(200)
const body = (await res.json()) as Array<{ Title: string }>
expect(Array.isArray(body)).toBe(true)
expect(body.length).toBeGreaterThan(0)
expect(body[0]).toHaveProperty('Title')
})
test('GET /sigs/:sigName 404s when the blob is absent', async () => {
const res = await exports.default.fetch(`${ORIGIN}/sigs/does-not-exist`)
expect(res.status).toBe(404)
})
test('GET /sigs/:sigName streams the blob from R2 as octet-stream', async () => {
await env.CDN_ASSETS.put('sigs/682c1283', new Uint8Array([1, 2, 3, 4]))
const res = await exports.default.fetch(`${ORIGIN}/sigs/682c1283`)
expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toBe('application/octet-stream')
expect(new Uint8Array(await res.arrayBuffer())).toEqual(new Uint8Array([1, 2, 3, 4]))
})
test('GET /sigs/:sigName honors a Range request with 206', async () => {
await env.CDN_ASSETS.put('sigs/ranged', new Uint8Array([10, 11, 12, 13, 14, 15]))
const res = await exports.default.fetch(`${ORIGIN}/sigs/ranged`, {
headers: { Range: 'bytes=2-4' },
})
expect(res.status).toBe(206)
expect(res.headers.get('content-range')).toBe('bytes 2-4/6')
expect(res.headers.get('accept-ranges')).toBe('bytes')
expect(new Uint8Array(await res.arrayBuffer())).toEqual(new Uint8Array([12, 13, 14]))
})
test('GET /room/:dataBlob streams the room blob from R2', async () => {
await env.CDN_ASSETS.put('room/94tp5zjtwz0gppp8xlv1j9l5b.room', new Uint8Array([9, 8, 7]))
const res = await exports.default.fetch(`${ORIGIN}/room/94tp5zjtwz0gppp8xlv1j9l5b.room`)
expect(res.status).toBe(200)
expect(res.headers.get('content-type')).toBe('application/octet-stream')
expect(new Uint8Array(await res.arrayBuffer())).toEqual(new Uint8Array([9, 8, 7]))
})
test('GET /room/:dataBlob 404s when the blob is absent', async () => {
const res = await exports.default.fetch(`${ORIGIN}/room/missing.room`)
expect(res.status).toBe(404)
})
test('POST /upload 401s without a token', async () => {
const res = await exports.default.fetch(`${ORIGIN}/upload`, { method: 'POST' })
expect(res.status).toBe(401)
})
test('POST /upload 400s when no file is supplied', async () => {
const res = await exports.default.fetch(`${ORIGIN}/upload`, {
method: 'POST',
headers: await bearer(),
})
expect(res.status).toBe(400)
expect(await res.json()).toEqual({ error: 'No file found in request' })
})
test('POST /upload returns a saved filename for a valid file', async () => {
const form = new FormData()
form.append('file', new File([new Uint8Array([1, 2, 3])], 'photo.jpg', { type: 'image/jpeg' }))
const res = await exports.default.fetch(`${ORIGIN}/upload`, {
method: 'POST',
headers: await bearer(),
body: form,
})
expect(res.status).toBe(200)
const body = (await res.json()) as { filename: string }
expect(body.filename).toMatch(/^[0-9a-f]{32}\.jpg$/)
})
})