mirror of
https://github.com/djdevin/recflare.git
synced 2026-09-08 14:41:28 -07:00
updating api docs
This commit is contained in:
@@ -0,0 +1,121 @@
|
||||
import { resolver } from 'hono-openapi'
|
||||
import { z } from 'zod'
|
||||
|
||||
import type { OpenAPIV3_1 } from 'openapi-types'
|
||||
|
||||
/**
|
||||
* OpenAPI schemas for the storage worker.
|
||||
*
|
||||
* IMPORTANT: these are DESCRIPTIVE ONLY. They are passed to `describeRoute` to
|
||||
* generate the spec and are never wired into `hono-openapi`'s `validator()`. Same
|
||||
* rationale as the auth/accounts/match/econ workers: a reverse-engineered protocol,
|
||||
* lenient handlers, no runtime validation.
|
||||
*
|
||||
* Do NOT add `.meta({ id })` to these schemas — with this hono-openapi + zod v4 setup a
|
||||
* meta'd schema used in a response emits a `$ref` the framework doesn't always hoist
|
||||
* into `components.schemas`, leaving a dangling reference. Leaving meta off makes every
|
||||
* schema inline, which renders correctly in any tool.
|
||||
*/
|
||||
|
||||
/** Emit a zod schema as an `application/json` response body. */
|
||||
export function json(schema: z.ZodType, description: string) {
|
||||
return { description, content: { 'application/json': { schema: resolver(schema) } } }
|
||||
}
|
||||
|
||||
/** A `text/plain` response body. */
|
||||
export function text(description: string) {
|
||||
return { description, content: { 'text/plain': { schema: { type: 'string' as const } } } }
|
||||
}
|
||||
|
||||
function toOpenApiSchema(schema: z.ZodType): OpenAPIV3_1.SchemaObject {
|
||||
const { $schema: _$schema, additionalProperties: _extra, ...jsonSchema } = z.toJSONSchema(schema)
|
||||
return jsonSchema as OpenAPIV3_1.SchemaObject
|
||||
}
|
||||
|
||||
/** A form-urlencoded / multipart request body (the client posts both). */
|
||||
export function form(schema: z.ZodType, description: string): OpenAPIV3_1.RequestBodyObject {
|
||||
const s = toOpenApiSchema(schema)
|
||||
return {
|
||||
description,
|
||||
content: {
|
||||
'application/x-www-form-urlencoded': { schema: s },
|
||||
'multipart/form-data': { schema: s },
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/** The empty-body 401 the auth-gated routes return. */
|
||||
export const UNAUTHORIZED_RESPONSE = { description: 'Missing or invalid bearer token (empty body)' }
|
||||
|
||||
/** Bearer-JWT security requirement, for the auth-gated routes. */
|
||||
export const AUTHED = [{ bearerAuth: [] }]
|
||||
|
||||
// ---- Response schemas ------------------------------------------------------
|
||||
|
||||
/**
|
||||
* `POST /upload` success body. `filename` is the `<upload-date>/<random-name>` part of
|
||||
* the stored key — the client keeps it and later references the blob by it, and the
|
||||
* `cdn` worker reads it back from `<type-subfolder>/<filename>`. On a name-only post it
|
||||
* is the name that was sent, echoed straight back.
|
||||
*/
|
||||
export const UploadResponse = z.object({
|
||||
filename: z
|
||||
.string()
|
||||
.describe('`<YYYY-MM-DD>/<uuid>[.ext]`, or the posted name on a name-only upload'),
|
||||
})
|
||||
|
||||
/** The `{ error }` body the 400s carry. */
|
||||
export const ErrorResponse = z.object({ error: z.string() })
|
||||
|
||||
// ---- Request schemas -------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The text parts of `POST /upload`. Field names are matched case-insensitively, so the
|
||||
* client's `imageName` / `FileType` casing is only indicative. The binary part is not in
|
||||
* this schema — see `UPLOAD_REQUEST_BODY`.
|
||||
*/
|
||||
export const UploadRequest = z.object({
|
||||
FileType: z
|
||||
.string()
|
||||
.describe(
|
||||
[
|
||||
'The client’s UploadFileType enum as a string: 1 RoomSave, 2 Holotar, 3 Image,',
|
||||
'4 Video, 5 Invention, 6 RoomMetadata. 0 (Unknown) and unrecognized values have no',
|
||||
'destination folder and are rejected.',
|
||||
].join(' ')
|
||||
),
|
||||
imageName: z
|
||||
.string()
|
||||
.optional()
|
||||
.describe(
|
||||
[
|
||||
'Name-only post: with no binary part, an explicit `imageName` / `filename` / `name`',
|
||||
'is echoed straight back as `filename`.',
|
||||
].join(' ')
|
||||
),
|
||||
})
|
||||
|
||||
/**
|
||||
* The `POST /upload` request body. The binary part is detected by being a file (it has a
|
||||
* filename / content-type), not by its field name, so its key is arbitrary — the client
|
||||
* posts it as `File`. zod cannot express a binary part, so it is spliced into the
|
||||
* generated schema as `{ type: 'string', format: 'binary' }`.
|
||||
*/
|
||||
export const UPLOAD_REQUEST_BODY: OpenAPIV3_1.RequestBodyObject = (() => {
|
||||
const body = form(UploadRequest, 'The FileType and the file to store')
|
||||
for (const media of Object.values(body.content)) {
|
||||
const schema = media.schema as OpenAPIV3_1.SchemaObject
|
||||
schema.properties = {
|
||||
...schema.properties,
|
||||
File: {
|
||||
type: 'string',
|
||||
format: 'binary',
|
||||
description: [
|
||||
'The file to store. Matched by being a file part, not by this field name.',
|
||||
'Omit it to make a name-only post.',
|
||||
].join(' '),
|
||||
},
|
||||
}
|
||||
}
|
||||
return body
|
||||
})()
|
||||
+112
-33
@@ -1,9 +1,20 @@
|
||||
import { Hono } from 'hono'
|
||||
import { describeRoute, openAPIRouteHandler } from 'hono-openapi'
|
||||
import { useWorkersLogger } from 'workers-tagged-logger'
|
||||
|
||||
import { withNotFound, withOnError } from '@repo/hono-helpers'
|
||||
import { withCleanSpec, withNotFound, withOnError } from '@repo/hono-helpers'
|
||||
import { validateAndGetAccountId } from '@repo/jwt'
|
||||
|
||||
import {
|
||||
AUTHED,
|
||||
ErrorResponse,
|
||||
json,
|
||||
text,
|
||||
UNAUTHORIZED_RESPONSE,
|
||||
UPLOAD_REQUEST_BODY,
|
||||
UploadResponse,
|
||||
} from './openapi'
|
||||
|
||||
import type { App } from './context'
|
||||
|
||||
/**
|
||||
@@ -72,9 +83,18 @@ const app = new Hono<App>()
|
||||
.onError(withOnError())
|
||||
.notFound(withNotFound())
|
||||
|
||||
.get('/', async (c) => {
|
||||
return c.text('hello, world!')
|
||||
})
|
||||
.get(
|
||||
'/',
|
||||
describeRoute({
|
||||
tags: ['Meta'],
|
||||
summary: 'Health check',
|
||||
description: 'Plain-text liveness probe. No auth.',
|
||||
responses: { 200: text('Service is up (`hello, world!`)') },
|
||||
}),
|
||||
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
|
||||
@@ -83,40 +103,99 @@ const app = new Hono<App>()
|
||||
// (the `<upload-date>/<random-name>` part the `cdn` worker serves back) 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 validateAndGetAccountId(c.req.raw, await c.env.JWT_SECRET.get())
|
||||
if (id === null) return c.body(null, 401)
|
||||
.post(
|
||||
'/upload',
|
||||
describeRoute({
|
||||
tags: ['Upload'],
|
||||
summary: 'Upload a file',
|
||||
description: [
|
||||
'Stores the posted file in the shared CDN R2 bucket under',
|
||||
'`<type-subfolder>/<upload-date>/<random-name>` and returns the',
|
||||
'`<upload-date>/<random-name>` part the client references it by (the same name the',
|
||||
'`cdn` worker serves back). The subfolder comes from `FileType`; RoomSave (1) lands',
|
||||
'under `room/` so the cdn worker’s `GET /room/:dataBlob` finds it, and an Invention',
|
||||
'(5) keeps a `.inv` extension on both the key and the returned name. Auth-gated —',
|
||||
'any valid account token is allowed, no role check. A post with no binary part but',
|
||||
'an explicit `imageName` / `filename` / `name` just echoes that name back. Mirrors',
|
||||
'the reference server’s `Upload`.',
|
||||
].join(' '),
|
||||
security: AUTHED,
|
||||
requestBody: UPLOAD_REQUEST_BODY,
|
||||
responses: {
|
||||
200: json(UploadResponse, 'The stored (or echoed) file name'),
|
||||
400: json(ErrorResponse, 'Unknown/missing FileType, or neither a file nor a name'),
|
||||
401: UNAUTHORIZED_RESPONSE,
|
||||
},
|
||||
}),
|
||||
async (c) => {
|
||||
const id = await validateAndGetAccountId(c.req.raw, await c.env.JWT_SECRET.get())
|
||||
if (id === null) return c.body(null, 401)
|
||||
|
||||
const body = await c.req.parseBody().catch(() => ({}) as Record<string, unknown>)
|
||||
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)
|
||||
// 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 fileType = textField(body, 'filetype') ?? '0'
|
||||
const subfolder = subfolderForFileType(fileType)
|
||||
if (subfolder === undefined) {
|
||||
// makeUploadName == "" → no destination for an unknown/missing type.
|
||||
return c.json({ error: 'missing or unknown FileType' }, 400)
|
||||
if (file) {
|
||||
const fileType = textField(body, 'filetype') ?? '0'
|
||||
const subfolder = subfolderForFileType(fileType)
|
||||
if (subfolder === undefined) {
|
||||
// makeUploadName == "" → no destination for an unknown/missing type.
|
||||
return c.json({ error: 'missing or unknown FileType' }, 400)
|
||||
}
|
||||
// Folder each upload under its date (e.g. `room/2026-02-03/<uuid>`) so the
|
||||
// bucket stays browsable. The date is part of the returned name, so the key
|
||||
// the `cdn` worker reads back (`<subfolder>/<name>`) still round-trips — as
|
||||
// does the extension, which is why it goes on the key, not just the name.
|
||||
const datePrefix = new Date().toISOString().slice(0, 10)
|
||||
const filename = `${datePrefix}/${crypto.randomUUID()}${extensionForFileType(fileType)}`
|
||||
await c.env.CDN_ASSETS.put(`${subfolder}/${filename}`, await file.arrayBuffer(), {
|
||||
httpMetadata: { contentType: file.type || 'application/octet-stream' },
|
||||
})
|
||||
return c.json({ filename })
|
||||
}
|
||||
// Folder each upload under its date (e.g. `room/2026-02-03/<uuid>`) so the
|
||||
// bucket stays browsable. The date is part of the returned name, so the key
|
||||
// the `cdn` worker reads back (`<subfolder>/<name>`) still round-trips — as
|
||||
// does the extension, which is why it goes on the key, not just the name.
|
||||
const datePrefix = new Date().toISOString().slice(0, 10)
|
||||
const filename = `${datePrefix}/${crypto.randomUUID()}${extensionForFileType(fileType)}`
|
||||
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)
|
||||
}
|
||||
)
|
||||
|
||||
// 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)
|
||||
})
|
||||
// The generated spec. Documentation only — no request is validated against it (see
|
||||
// openapi.ts). `hide: true` keeps this route out of its own output.
|
||||
app.get(
|
||||
'/openapi.json',
|
||||
describeRoute({ hide: true }),
|
||||
withCleanSpec(
|
||||
openAPIRouteHandler(app, {
|
||||
documentation: {
|
||||
info: {
|
||||
title: 'recflare storage',
|
||||
version: '1.0.0',
|
||||
description: [
|
||||
'File uploads for recflare, a private-server reimplementation of the Rec Room',
|
||||
'backend. The client posts room saves, holotars, images, videos, inventions and',
|
||||
'room metadata here; each lands in the shared CDN R2 bucket under a folder chosen',
|
||||
'by its `FileType`, and the `cdn` worker serves them back from the same bucket.',
|
||||
].join('\n'),
|
||||
},
|
||||
servers: [{ url: 'https://storage.recflare.net', description: 'Production' }],
|
||||
components: {
|
||||
securitySchemes: {
|
||||
bearerAuth: {
|
||||
type: 'http',
|
||||
scheme: 'bearer',
|
||||
bearerFormat: 'JWT',
|
||||
description: 'An `access_token` from the auth worker’s `POST /connect/token`.',
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
)
|
||||
)
|
||||
|
||||
export default app
|
||||
|
||||
@@ -159,3 +159,35 @@ it('POST /upload 400s when there is neither a file nor a name', async () => {
|
||||
})
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('GET /openapi.json documents every route', async () => {
|
||||
const res = await SELF.fetch(`${ORIGIN}/openapi.json`)
|
||||
expect(res.status).toBe(200)
|
||||
const spec = (await res.json()) as {
|
||||
openapi: string
|
||||
paths: Record<string, Record<string, { summary?: string }>>
|
||||
}
|
||||
expect(spec.openapi).toMatch(/^3\.1/)
|
||||
|
||||
// The spec route hides itself.
|
||||
expect(spec.paths['/openapi.json']).toBeUndefined()
|
||||
|
||||
// Every route the worker serves is described. This is the drift guard: adding a
|
||||
// route without a describeRoute() block fails here rather than silently shipping
|
||||
// an incomplete spec.
|
||||
const documented = new Set(
|
||||
Object.entries(spec.paths).flatMap(([path, ops]) =>
|
||||
Object.keys(ops).map((method) => `${method.toUpperCase()} ${path}`)
|
||||
)
|
||||
)
|
||||
expect([...documented].sort()).toEqual(['GET /', 'POST /upload'])
|
||||
|
||||
// Every operation carries a summary — a path present but undescribed is not
|
||||
// documentation.
|
||||
for (const ops of Object.values(spec.paths)) {
|
||||
for (const op of Object.values(ops)) expect(op.summary).toBeTruthy()
|
||||
}
|
||||
|
||||
// Every schema inlines: a `$ref` here would be a dangling reference (see openapi.ts).
|
||||
expect(JSON.stringify(spec).includes('"$ref"')).toBe(false)
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user