mirror of
https://github.com/djdevin/recflare.git
synced 2026-09-08 14:41:28 -07:00
custom rooms
This commit is contained in:
@@ -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 & {
|
||||
// Shared CDN R2 bucket (`recflare-cdn`, owned by the `cdn` worker). Client
|
||||
// uploads are written here under a per-FileType subfolder; the `cdn` worker
|
||||
// serves them back.
|
||||
CDN_ASSETS: R2Bucket
|
||||
}
|
||||
|
||||
/** 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.
|
||||
*
|
||||
* 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,115 @@
|
||||
import { Hono } from 'hono'
|
||||
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'
|
||||
|
||||
/**
|
||||
* Storage worker. Handles client file uploads (`POST /upload`) into the shared
|
||||
* CDN R2 bucket, foldered by the posted `FileType` so the `cdn` worker can serve
|
||||
* them back.
|
||||
*/
|
||||
|
||||
/**
|
||||
* The client's `UploadFileType` enum → the R2 subfolder uploads of that type are
|
||||
* stored under. `Unknown` (0) is intentionally absent: like the reference
|
||||
* server's `makeUploadName`, an unrecognized type has no destination and is
|
||||
* rejected rather than stored.
|
||||
*/
|
||||
const UPLOAD_SUBFOLDER: Record<number, string> = {
|
||||
1: 'roomsave',
|
||||
2: 'holotar',
|
||||
3: 'image',
|
||||
4: 'video',
|
||||
5: 'invention',
|
||||
6: 'roommetadata',
|
||||
}
|
||||
|
||||
/** Resolve the storage subfolder for a posted FileType, or `undefined` when unknown. */
|
||||
function subfolderForFileType(fileType: string): string | undefined {
|
||||
return UPLOAD_SUBFOLDER[Number.parseInt(fileType, 10)]
|
||||
}
|
||||
|
||||
/** Read a text form field by any of its accepted names, matched case-insensitively. */
|
||||
function textField(body: Record<string, unknown>, ...names: string[]): string | undefined {
|
||||
for (const [key, value] of Object.entries(body)) {
|
||||
if (typeof value === 'string' && names.includes(key.toLowerCase())) return value
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
|
||||
/**
|
||||
* 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(
|
||||
'*',
|
||||
// middleware
|
||||
(c, next) =>
|
||||
useWorkersLogger(c.env.NAME, {
|
||||
environment: c.env.ENVIRONMENT,
|
||||
release: c.env.SENTRY_RELEASE,
|
||||
})(c, next)
|
||||
)
|
||||
|
||||
.onError(withOnError())
|
||||
.notFound(withNotFound())
|
||||
|
||||
.get('/', async (c) => {
|
||||
return c.text('hello, world!')
|
||||
})
|
||||
|
||||
// File upload. Auth-gated — any valid account token is allowed (no role check).
|
||||
// Multipart form with `FileType` (the client's UploadFileType enum) and a binary
|
||||
// part. Stores the file in the shared CDN R2 bucket under
|
||||
// `<type-subfolder>/<random-name>` and returns the generated filename the client
|
||||
// references it by. Also accepts a name-only post (no binary) that just echoes
|
||||
// back an explicit `name`/`filename`/`imagename`. Mirrors the reference `Upload`.
|
||||
.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>)
|
||||
|
||||
// The binary part is identified by being a file (filename/content-type),
|
||||
// not by its field name — matching the reference's part detection.
|
||||
const file = Object.values(body).find((v): v is File => v instanceof File)
|
||||
|
||||
if (file) {
|
||||
const subfolder = subfolderForFileType(textField(body, 'filetype') ?? '0')
|
||||
if (subfolder === undefined) {
|
||||
// makeUploadName == "" → no destination for an unknown/missing type.
|
||||
return c.json({ error: 'missing or unknown FileType' }, 400)
|
||||
}
|
||||
const filename = crypto.randomUUID().replace(/-/g, '')
|
||||
await c.env.CDN_ASSETS.put(`${subfolder}/${filename}`, await file.arrayBuffer(), {
|
||||
httpMetadata: { contentType: file.type || 'application/octet-stream' },
|
||||
})
|
||||
return c.json({ filename })
|
||||
}
|
||||
|
||||
// No binary — accept an explicit name and echo it straight back.
|
||||
const explicitName = textField(body, 'imagename', 'filename', 'name')
|
||||
if (explicitName) return c.json({ filename: explicitName })
|
||||
|
||||
return c.json({ error: 'missing filename or valid upload data' }, 400)
|
||||
})
|
||||
|
||||
export default app
|
||||
@@ -0,0 +1,134 @@
|
||||
import { env, SELF } from 'cloudflare:test'
|
||||
import { expect, it } from 'vitest'
|
||||
|
||||
import type { Env } from '../../context'
|
||||
|
||||
declare module 'cloudflare:test' {
|
||||
interface ProvidedEnv extends Env {}
|
||||
}
|
||||
|
||||
const ORIGIN = 'https://example.com'
|
||||
|
||||
// Mint a token the way the `auth` worker does, using the same dev secret, so the
|
||||
// storage worker's validation accepts it.
|
||||
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)}` }
|
||||
}
|
||||
|
||||
/** Build the client's multipart upload body: FileType + File. */
|
||||
function uploadForm(fileType: string, bytes: Uint8Array): FormData {
|
||||
const form = new FormData()
|
||||
form.set('FileType', fileType)
|
||||
form.set('File', new File([bytes], 'file.bin', { type: 'application/octet-stream' }))
|
||||
return form
|
||||
}
|
||||
|
||||
it('response with hello world', async () => {
|
||||
const res = await SELF.fetch(ORIGIN)
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.text()).toMatchInlineSnapshot(`"hello, world!"`)
|
||||
})
|
||||
|
||||
it('POST /upload 401s without a token', async () => {
|
||||
const res = await SELF.fetch(`${ORIGIN}/upload`, {
|
||||
method: 'POST',
|
||||
body: uploadForm('6', new Uint8Array([1])),
|
||||
})
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('POST /upload stores a RoomMetadata (FileType 6) file under roommetadata/ and returns its name', async () => {
|
||||
// Mirrors the client's multipart upload: FileType=6, File=<binary>.
|
||||
const bytes = new Uint8Array([0x10, 0x02, 0x1a, 0x00])
|
||||
const res = await SELF.fetch(`${ORIGIN}/upload`, {
|
||||
method: 'POST',
|
||||
headers: await bearer(),
|
||||
body: uploadForm('6', bytes),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
const { filename } = (await res.json()) as { filename: string }
|
||||
expect(filename).toMatch(/^[0-9a-f]{32}$/)
|
||||
|
||||
// The bytes are persisted in the shared CDN bucket under the type subfolder.
|
||||
const stored = await env.CDN_ASSETS.get(`roommetadata/${filename}`)
|
||||
expect(stored).not.toBeNull()
|
||||
expect(new Uint8Array(await stored!.arrayBuffer())).toEqual(bytes)
|
||||
})
|
||||
|
||||
it('POST /upload folders each FileType under its own subfolder', async () => {
|
||||
const headers = await bearer()
|
||||
const cases: Array<[string, string]> = [
|
||||
['1', 'roomsave'],
|
||||
['3', 'image'],
|
||||
['5', 'invention'],
|
||||
]
|
||||
for (const [fileType, subfolder] of cases) {
|
||||
const res = await SELF.fetch(`${ORIGIN}/upload`, {
|
||||
method: 'POST',
|
||||
headers,
|
||||
body: uploadForm(fileType, new Uint8Array([1, 2, 3])),
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
const { filename } = (await res.json()) as { filename: string }
|
||||
expect(await env.CDN_ASSETS.get(`${subfolder}/${filename}`)).not.toBeNull()
|
||||
}
|
||||
})
|
||||
|
||||
it('POST /upload 400s for a binary with an unknown/missing FileType', async () => {
|
||||
// Unknown type (999) and the Unknown enum value (0) have no destination → 400.
|
||||
for (const fileType of ['999', '0']) {
|
||||
const res = await SELF.fetch(`${ORIGIN}/upload`, {
|
||||
method: 'POST',
|
||||
headers: await bearer(),
|
||||
body: uploadForm(fileType, new Uint8Array([9])),
|
||||
})
|
||||
expect(res.status).toBe(400)
|
||||
}
|
||||
})
|
||||
|
||||
it('POST /upload echoes an explicit name when no binary is posted', async () => {
|
||||
const form = new FormData()
|
||||
form.set('FileType', '3')
|
||||
form.set('imageName', 'existing-image-key.png')
|
||||
const res = await SELF.fetch(`${ORIGIN}/upload`, {
|
||||
method: 'POST',
|
||||
headers: await bearer(),
|
||||
body: form,
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
expect((await res.json()) as { filename: string }).toEqual({
|
||||
filename: 'existing-image-key.png',
|
||||
})
|
||||
})
|
||||
|
||||
it('POST /upload 400s when there is neither a file nor a name', async () => {
|
||||
const form = new FormData()
|
||||
form.set('FileType', '6')
|
||||
const res = await SELF.fetch(`${ORIGIN}/upload`, {
|
||||
method: 'POST',
|
||||
headers: await bearer(),
|
||||
body: form,
|
||||
})
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
Reference in New Issue
Block a user