mirror of
https://github.com/djdevin/recflare.git
synced 2026-09-08 22:51:30 -07:00
clean up auth, some storage improvements
This commit is contained in:
@@ -2,7 +2,6 @@ import { Hono } from 'hono'
|
||||
import { useWorkersLogger } from 'workers-tagged-logger'
|
||||
|
||||
import { withNotFound, withOnError } from '@repo/hono-helpers'
|
||||
import { validateAndGetAccountId } from '@repo/jwt'
|
||||
|
||||
import loadingScreenTipData from '../static/loading-screen-tip-data.json'
|
||||
|
||||
@@ -15,22 +14,6 @@ import type { App, Env } from './context'
|
||||
* 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, await c.env.JWT_SECRET.get())
|
||||
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
|
||||
@@ -122,27 +105,4 @@ const app = new Hono<App>()
|
||||
// load the room. Streamed from R2 under `room/`.
|
||||
.get('/room/:dataBlob', (c) => serveAsset(c, `room/${c.req.param('dataBlob')}`))
|
||||
|
||||
// Image upload. Auth-gated; 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
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { adminSecretsStore, env } from 'cloudflare:test'
|
||||
import { env } from 'cloudflare:test'
|
||||
import { exports } from 'cloudflare:workers'
|
||||
import { beforeAll, describe, expect, test } from 'vitest'
|
||||
import { describe, expect, test } from 'vitest'
|
||||
|
||||
import '../../cdn.app'
|
||||
|
||||
@@ -12,37 +12,6 @@ declare module 'cloudflare:test' {
|
||||
|
||||
const ORIGIN = 'https://example.com'
|
||||
|
||||
beforeAll(async () => {
|
||||
// Seed the shared JWT signing key into the local Secrets Store so .get() resolves.
|
||||
await adminSecretsStore(env.JWT_SECRET).create('test-signing-key')
|
||||
})
|
||||
|
||||
// Mint a token the way the `auth` worker does, signing with the shared test key seeded into the JWT_SECRET store.
|
||||
const TEST_SECRET = 'test-signing-key'
|
||||
|
||||
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(TEST_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}/`)
|
||||
@@ -95,31 +64,4 @@ describe('cdn endpoints', () => {
|
||||
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$/)
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user