Skip to content

Commit d9e5a33

Browse files
authored
feat(den): document den-api with OpenAPI (anomalyco#1371)
Generate an OpenAPI spec and Swagger UI from den-api's existing Hono and zod validators so the API stays self-describing. Add route metadata, typed responses, and hide API key creation endpoints from production docs. Co-authored-by: src-opn <[email protected]>
1 parent 4f19058 commit d9e5a33

22 files changed

Lines changed: 1800 additions & 91 deletions

‎ee/apps/den-api/package.json‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,18 +11,25 @@
1111
},
1212
"dependencies": {
1313
"@better-auth/api-key": "^1.5.6",
14-
"@openwork-ee/den-db": "workspace:*",
15-
"@openwork-ee/utils": "workspace:*",
1614
"@daytonaio/sdk": "^0.150.0",
1715
"@hono/node-server": "^1.13.8",
18-
"@hono/zod-validator": "^0.7.6",
19-
"better-call": "^1.3.2",
16+
"@hono/standard-validator": "^0.2.2",
17+
"@hono/swagger-ui": "^0.6.1",
18+
"@openwork-ee/den-db": "workspace:*",
19+
"@openwork-ee/utils": "workspace:*",
20+
"@standard-community/standard-json": "^0.3.5",
21+
"@standard-community/standard-openapi": "^0.2.9",
22+
"@standard-schema/spec": "^1.1.0",
2023
"better-auth": "^1.5.6",
24+
"better-call": "^1.3.2",
2125
"dotenv": "^16.4.5",
2226
"hono": "^4.7.2",
27+
"hono-openapi": "^1.3.0",
28+
"openapi-types": "^12.1.3",
2329
"zod": "^4.3.6"
2430
},
2531
"devDependencies": {
32+
"@types/json-schema": "^7.0.15",
2633
"@types/node": "^20.11.30",
2734
"tsx": "^4.15.7",
2835
"typescript": "^5.5.4"

‎ee/apps/den-api/src/app.ts‎

Lines changed: 137 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,16 @@
11
import "./load-env.js"
22
import { createDenTypeId } from "@openwork-ee/utils/typeid"
3+
import { swaggerUI } from "@hono/swagger-ui"
34
import { cors } from "hono/cors"
45
import { Hono } from "hono"
56
import { logger } from "hono/logger"
67
import type { RequestIdVariables } from "hono/request-id"
78
import { requestId } from "hono/request-id"
9+
import { describeRoute, openAPIRouteHandler, resolver } from "hono-openapi"
10+
import { z } from "zod"
811
import { env } from "./env.js"
912
import type { MemberTeamsContext, OrganizationContextVariables, UserOrganizationsContext } from "./middleware/index.js"
13+
import { buildOperationId, emptyResponse, htmlResponse, jsonResponse } from "./openapi.js"
1014
import { registerAdminRoutes } from "./routes/admin/index.js"
1115
import { registerAuthRoutes } from "./routes/auth/index.js"
1216
import { registerMeRoutes } from "./routes/me/index.js"
@@ -17,6 +21,21 @@ import { sessionMiddleware } from "./session.js"
1721

1822
type AppVariables = RequestIdVariables & AuthContextVariables & Partial<UserOrganizationsContext> & Partial<OrganizationContextVariables> & Partial<MemberTeamsContext>
1923

24+
const healthResponseSchema = z.object({
25+
ok: z.literal(true),
26+
service: z.literal("den-api"),
27+
}).meta({ ref: "DenApiHealthResponse" })
28+
29+
const openApiDocumentSchema = z.object({
30+
openapi: z.string(),
31+
info: z.object({
32+
title: z.string(),
33+
version: z.string(),
34+
}).passthrough(),
35+
paths: z.record(z.string(), z.unknown()),
36+
components: z.object({}).passthrough().optional(),
37+
}).passthrough().meta({ ref: "OpenApiDocument" })
38+
2039
const app = new Hono<{ Variables: AppVariables }>()
2140

2241
app.use("*", logger())
@@ -45,20 +64,132 @@ if (env.corsOrigins.length > 0) {
4564

4665
app.use("*", sessionMiddleware)
4766

48-
app.get("/", (c) => {
49-
return c.redirect("https://openworklabs.com", 302)
50-
})
67+
app.get(
68+
"/",
69+
describeRoute({
70+
tags: ["System"],
71+
summary: "Redirect API root",
72+
description: "Redirects the API root to the OpenWork marketing site instead of serving API content.",
73+
responses: {
74+
302: emptyResponse("Redirect to the OpenWork marketing site."),
75+
},
76+
}),
77+
(c) => {
78+
return c.redirect("https://openworklabs.com", 302)
79+
},
80+
)
5181

52-
app.get("/health", (c) => {
53-
return c.json({ ok: true, service: "den-api" })
54-
})
82+
app.get(
83+
"/health",
84+
describeRoute({
85+
tags: ["System"],
86+
summary: "Check den-api health",
87+
description: "Returns a lightweight health payload for den-api.",
88+
responses: {
89+
200: {
90+
description: "den-api is reachable",
91+
content: {
92+
"application/json": {
93+
schema: resolver(healthResponseSchema),
94+
},
95+
},
96+
},
97+
},
98+
}),
99+
(c) => {
100+
return c.json({ ok: true, service: "den-api" })
101+
},
102+
)
55103

56104
registerAdminRoutes(app)
57105
registerAuthRoutes(app)
58106
registerMeRoutes(app)
59107
registerOrgRoutes(app)
60108
registerWorkerRoutes(app)
61109

110+
app.get(
111+
"/openapi.json",
112+
describeRoute({
113+
tags: ["Documentation"],
114+
summary: "Get OpenAPI document",
115+
description: "Returns the machine-readable OpenAPI 3.1 document for the Den API so humans and tools can inspect the API surface.",
116+
responses: {
117+
200: jsonResponse("OpenAPI document returned successfully.", openApiDocumentSchema),
118+
},
119+
}),
120+
openAPIRouteHandler(app, {
121+
documentation: {
122+
openapi: "3.1.0",
123+
info: {
124+
title: "Den API",
125+
version: "dev",
126+
description: "OpenAPI spec for the Den control plane API.",
127+
},
128+
tags: [
129+
{ name: "System", description: "Service health and operational routes." },
130+
{ name: "Documentation", description: "OpenAPI document and Swagger UI routes." },
131+
{ name: "Organizations", description: "Organization-scoped Den API routes." },
132+
{ name: "Organization Invitations", description: "Organization invitation creation, preview, acceptance, and cancellation routes." },
133+
{ name: "Organization API Keys", description: "Organization API key management routes." },
134+
{ name: "Organization Members", description: "Organization member management routes." },
135+
{ name: "Organization Roles", description: "Organization custom role management routes." },
136+
{ name: "Organization Teams", description: "Organization team management routes." },
137+
{ name: "Organization Templates", description: "Organization shared template routes." },
138+
{ name: "Organization LLM Providers", description: "Organization LLM provider catalog, configuration, and access routes." },
139+
{ name: "Organization Skills", description: "Organization skill authoring and sharing routes." },
140+
{ name: "Organization Skill Hubs", description: "Organization skill hub management and access routes." },
141+
{ name: "Workers", description: "Worker lifecycle, billing, and runtime routes." },
142+
{ name: "Worker Billing", description: "Worker subscription and billing status routes." },
143+
{ name: "Worker Runtime", description: "Worker runtime inspection and upgrade routes." },
144+
{ name: "Worker Activity", description: "Worker heartbeat and activity reporting routes." },
145+
{ name: "Authentication", description: "Authentication and desktop sign-in handoff routes." },
146+
{ name: "Admin", description: "Administrative reporting routes." },
147+
{ name: "Users", description: "Current user and membership routes." },
148+
],
149+
components: {
150+
securitySchemes: {
151+
bearerAuth: {
152+
type: "http",
153+
scheme: "bearer",
154+
bearerFormat: "session-token",
155+
},
156+
denApiKey: {
157+
type: "apiKey",
158+
in: "header",
159+
name: "x-api-key",
160+
},
161+
},
162+
},
163+
},
164+
includeEmptyPaths: true,
165+
exclude: ["/docs", "/openapi.json"],
166+
excludeMethods: ["OPTIONS"],
167+
defaultOptions: {
168+
ALL: {
169+
operationId: (route) => buildOperationId(route.method, route.path),
170+
},
171+
},
172+
}),
173+
)
174+
175+
app.get(
176+
"/docs",
177+
describeRoute({
178+
tags: ["Documentation"],
179+
summary: "Serve Swagger UI",
180+
description: "Serves Swagger UI so developers can browse and try the Den API from a browser.",
181+
responses: {
182+
200: htmlResponse("Swagger UI page returned successfully."),
183+
},
184+
}),
185+
swaggerUI({
186+
url: "/openapi.json",
187+
persistAuthorization: true,
188+
displayOperationId: true,
189+
defaultModelsExpandDepth: 1,
190+
}),
191+
)
192+
62193
app.notFound((c) => {
63194
return c.json({ error: "not_found" }, 404)
64195
})

‎ee/apps/den-api/src/middleware/validation.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,11 @@
1-
import { zValidator } from "@hono/zod-validator"
1+
import { validator as zValidator } from "hono-openapi"
22
import type { ZodSchema } from "zod"
33

4-
function invalidRequestResponse(result: { success: false; error: { issues: unknown } }, c: { json: (body: unknown, status?: number) => Response }) {
4+
function invalidRequestResponse(result: { success: false; error: unknown }, c: { json: (body: unknown, status?: number) => Response }) {
55
return c.json(
66
{
77
error: "invalid_request",
8-
details: result.error.issues,
8+
details: result.error,
99
},
1010
400,
1111
)

‎ee/apps/den-api/src/openapi.ts‎

Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
import { resolver } from "hono-openapi"
2+
import { z } from "zod"
3+
4+
function toPascalCase(value: string) {
5+
return value
6+
.replace(/[^a-zA-Z0-9]+/g, " ")
7+
.trim()
8+
.split(/\s+/)
9+
.filter(Boolean)
10+
.map((part) => part.charAt(0).toUpperCase() + part.slice(1))
11+
.join("")
12+
}
13+
14+
export function buildOperationId(method: string, path: string) {
15+
const parts = path
16+
.split("/")
17+
.filter(Boolean)
18+
.filter((part) => part !== "v1")
19+
.map((part) => {
20+
if (part.startsWith(":")) {
21+
return `by-${part.slice(1)}`
22+
}
23+
24+
if (part === "*") {
25+
return "wildcard"
26+
}
27+
28+
return part
29+
})
30+
31+
return [method.toLowerCase(), ...parts]
32+
.map(toPascalCase)
33+
.join("")
34+
.replace(/^[A-Z]/, (char) => char.toLowerCase())
35+
}
36+
37+
const validationIssueSchema = z.object({
38+
message: z.string(),
39+
path: z.array(z.union([z.string(), z.number()])).optional(),
40+
}).passthrough()
41+
42+
export const invalidRequestSchema = z.object({
43+
error: z.literal("invalid_request"),
44+
details: z.array(validationIssueSchema),
45+
}).meta({ ref: "InvalidRequestError" })
46+
47+
export const unauthorizedSchema = z.object({
48+
error: z.literal("unauthorized"),
49+
}).meta({ ref: "UnauthorizedError" })
50+
51+
export const forbiddenSchema = z.object({
52+
error: z.literal("forbidden"),
53+
message: z.string().optional(),
54+
}).meta({ ref: "ForbiddenError" })
55+
56+
export const notFoundSchema = z.object({
57+
error: z.string(),
58+
message: z.string().optional(),
59+
}).meta({ ref: "NotFoundError" })
60+
61+
export const successSchema = z.object({
62+
success: z.literal(true),
63+
}).meta({ ref: "SuccessResponse" })
64+
65+
export const emptyObjectSchema = z.object({}).passthrough().meta({ ref: "OpaqueObject" })
66+
67+
export function jsonResponse(description: string, schema: z.ZodTypeAny) {
68+
return {
69+
description,
70+
content: {
71+
"application/json": {
72+
schema: resolver(schema),
73+
},
74+
},
75+
}
76+
}
77+
78+
export function htmlResponse(description: string) {
79+
return {
80+
description,
81+
content: {
82+
"text/html": {
83+
schema: resolver(z.string()),
84+
},
85+
},
86+
}
87+
}
88+
89+
export function textResponse(description: string) {
90+
return {
91+
description,
92+
content: {
93+
"text/plain": {
94+
schema: resolver(z.string()),
95+
},
96+
},
97+
}
98+
}
99+
100+
export function emptyResponse(description: string) {
101+
return { description }
102+
}

‎ee/apps/den-api/src/routes/admin/index.ts‎

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,12 @@
11
import { asc, desc, eq, isNotNull, sql } from "@openwork-ee/den-db/drizzle"
22
import { AuthAccountTable, AuthSessionTable, AuthUserTable, WorkerTable, AdminAllowlistTable } from "@openwork-ee/den-db/schema"
33
import type { Hono } from "hono"
4+
import { describeRoute } from "hono-openapi"
45
import { z } from "zod"
56
import { getCloudWorkerAdminBillingStatus } from "../../billing/polar.js"
67
import { db } from "../../db.js"
78
import { queryValidator, requireAdminMiddleware } from "../../middleware/index.js"
9+
import { invalidRequestSchema, jsonResponse, unauthorizedSchema } from "../../openapi.js"
810
import type { AuthContextVariables } from "../../session.js"
911

1012
type UserId = typeof AuthUserTable.$inferSelect.id
@@ -13,6 +15,18 @@ const overviewQuerySchema = z.object({
1315
includeBilling: z.string().optional(),
1416
})
1517

18+
const adminOverviewResponseSchema = z.object({
19+
viewer: z.object({
20+
id: z.string(),
21+
email: z.string(),
22+
name: z.string().nullable(),
23+
}),
24+
admins: z.array(z.object({}).passthrough()),
25+
summary: z.object({}).passthrough(),
26+
users: z.array(z.object({}).passthrough()),
27+
generatedAt: z.string().datetime(),
28+
}).meta({ ref: "AdminOverviewResponse" })
29+
1630
function normalizeEmail(value: string | null | undefined) {
1731
return value?.trim().toLowerCase() ?? ""
1832
}
@@ -84,7 +98,21 @@ async function mapWithConcurrency<T, R>(items: T[], limit: number, mapper: (item
8498
}
8599

86100
export function registerAdminRoutes<T extends { Variables: AuthContextVariables }>(app: Hono<T>) {
87-
app.get("/v1/admin/overview", requireAdminMiddleware, queryValidator(overviewQuerySchema), async (c) => {
101+
app.get(
102+
"/v1/admin/overview",
103+
describeRoute({
104+
tags: ["Admin"],
105+
summary: "Get admin overview",
106+
description: "Returns a high-level administrative overview of users, sessions, workers, admins, and optional billing data for Den operations.",
107+
responses: {
108+
200: jsonResponse("Administrative overview returned successfully.", adminOverviewResponseSchema),
109+
400: jsonResponse("The admin overview query parameters were invalid.", invalidRequestSchema),
110+
401: jsonResponse("The caller must be an authenticated admin.", unauthorizedSchema),
111+
},
112+
}),
113+
requireAdminMiddleware,
114+
queryValidator(overviewQuerySchema),
115+
async (c) => {
88116
const user = c.get("user")
89117
const query = c.req.valid("query")
90118
const includeBilling = parseBooleanQuery(query.includeBilling)
@@ -289,5 +317,6 @@ export function registerAdminRoutes<T extends { Variables: AuthContextVariables
289317
users: userRows,
290318
generatedAt: new Date().toISOString(),
291319
})
292-
})
320+
},
321+
)
293322
}

0 commit comments

Comments
 (0)