⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
fix(api): correct generated API documentation (#277)
I'm Groot 🌳5501ceeabf66
diff --git a/apps/api/src/__tests__/integration/openapi.test.ts b/apps/api/src/__tests__/integration/openapi.test.tsnew file mode 100644index 00000000..01dd1293--- /dev/null+++ b/apps/api/src/__tests__/integration/openapi.test.ts@@ -0,0 +1,121 @@+import { describe, expect, it } from 'bun:test';+import pkg from '../../../../../package.json';+import { app } from '../helpers/app';++type Operation = {+ description?: string;+ security?: Array<Record<string, string[]>>;+ tags?: string[];+ requestBody?: { content?: Record<string, unknown> };+ responses?: Record<string, { content?: Record<string, unknown> }>;+};++type Document = {+ info: { version: string; description?: string };+ servers?: Array<{ url: string }>;+ paths: Record<string, Record<string, Operation>>;+};++async function document(): Promise<Document> {+ const response = await app.handle(new Request('http://localhost/docs/json'));+ expect(response.status).toBe(200);+ return (await response.json()) as Document;+}++describe('OpenAPI document', () => {+ it('uses the configured public origin and current product version', async () => {+ const doc = await document();++ expect(doc.servers?.[0]?.url).toBe(process.env.API_URL);+ expect(doc.info.version).toBe(pkg.version);+ expect(doc.info.description).toContain('/account/api-keys');+ expect(doc.info.description).toContain('/mcp');+ });++ it('documents each authentication surface accurately', async () => {+ const doc = await document();++ expect(doc.paths['/projects']!.get!.security).toBeUndefined();+ expect(doc.paths['/']!.get!.security).toEqual([]);+ expect(doc.paths['/me']!.get!.security).toEqual([{}, { apiKey: [] }]);+ expect(doc.paths['/share/issue/{token}']!.get!.security).toEqual([]);+ expect(doc.paths['/internal/agent-runs/execute']!.post!.security).toEqual([+ { workerToken: [] },+ ]);+ expect(doc.paths['/scim/v2/Users']!.post!.security).toEqual([{ scimBearer: [] }]);+ expect(doc.paths['/webhooks/git/{webhookId}']!.post!.security).toContainEqual({+ gitLabToken: [],+ });+ });++ it('documents only the media types each surface accepts', async () => {+ const doc = await document();+ const genericMediaTypes = ['application/json', 'multipart/form-data', 'text/plain'];++ expect(Object.keys(doc.paths['/projects']!.post!.requestBody!.content!)).toEqual([+ 'application/json',+ ]);+ expect(+ Object.keys(doc.paths['/issues/{issueId}/attachments']!.post!.requestBody!.content!),+ ).toEqual(['multipart/form-data']);+ expect(+ Object.keys(doc.paths['/webhooks/git/{webhookId}']!.post!.requestBody!.content!),+ ).toEqual(['application/json']);+ expect(Object.keys(doc.paths['/scim/v2/Users']!.post!.requestBody!.content!)).toEqual([+ 'application/scim+json',+ ]);+ expect(Object.keys(doc.paths['/scim/v2/Users']!.post!.responses!['201']!.content!)).toEqual([+ 'application/scim+json',+ ]);++ for (const path of Object.values(doc.paths)) {+ for (const operation of Object.values(path)) {+ if (!operation || typeof operation !== 'object' || !('responses' in operation)) continue;+ const requestTypes = Object.keys(operation.requestBody?.content ?? {}).filter((mediaType) =>+ genericMediaTypes.includes(mediaType),+ );+ expect(requestTypes.length).toBeLessThanOrEqual(1);+ for (const response of Object.values(operation.responses ?? {})) {+ const responseTypes = Object.keys(response.content ?? {}).filter((mediaType) =>+ genericMediaTypes.includes(mediaType),+ );+ expect(responseTypes.length).toBeLessThanOrEqual(1);+ }+ }+ }+ });++ it('groups SCIM and gives every operation a description', async () => {+ const doc = await document();+ const operations = Object.values(doc.paths).flatMap((path) =>+ Object.values(path).filter((operation): operation is Operation =>+ Boolean(operation && typeof operation === 'object' && 'responses' in operation),+ ),+ );++ expect(doc.paths['/scim/v2/Users']!.post!.tags).toEqual(['SCIM']);+ expect(operations.length).toBeGreaterThan(300);+ expect(operations.every((operation) => Boolean(operation.description))).toBe(true);+ });+});++describe('API CORS', () => {+ it('allows personal API keys from the web app', async () => {+ const origin = process.env.APP_URL?.split(',')[0]?.trim();+ if (!origin) throw new Error('APP_URL is required for the CORS test');+ const response = await app.handle(+ new Request('http://localhost/projects', {+ method: 'OPTIONS',+ headers: {+ origin,+ 'access-control-request-method': 'GET',+ 'access-control-request-headers': 'x-api-key',+ },+ }),+ );++ expect(response.status).toBe(204);+ const allowed = response.headers.get('access-control-allow-headers')?.toLowerCase();+ expect(allowed).toContain('x-api-key');+ });+});diff --git a/apps/api/src/app.ts b/apps/api/src/app.tsindex 2302f634..54cdd45e 100644--- a/apps/api/src/app.ts+++ b/apps/api/src/app.ts@@ -19,6 +19,30 @@ import { internalTelegramRoutes } from './modules/telegram/internal-routes';import { gitWebhookRoutes } from './modules/git/webhook';import { scimRoutes } from './modules/scim';import { syncOidcGroupsAfterCallback } from './modules/scim/oidc-sync';+import { normalizeOpenApiResponse } from './openapi';+import pkg from '../../../package.json';++const apiUrl = (process.env.API_URL ?? 'http://localhost:3000').replace(/\/+$/, '');+const appUrl = (process.env.APP_URL?.split(',')[0]?.trim() || 'http://localhost:3001').replace(+ /\/+$/,+ '',+);+const apiDescription = `REST API for projects, work items, AI agents, Git integrations, analytics, and instance administration.++## Quick start++1. Create a personal API key in [Account settings](${appUrl}/account/api-keys). The key is shown once and carries the same permissions as its owner.+2. Send it in the \`x-api-key\` header. Never put a key in a URL, issue, comment, or source file.+3. Use the project key from the URL in routes containing \`{projectKey}\`. This page is opened from a project, but the API document is instance-wide.++\`\`\`sh+curl "${apiUrl}/projects" \\+ --header "x-api-key: YOUR_PERSONAL_API_KEY"+\`\`\`++JSON errors use \`{ "error": "message" }\` and may also include a stable \`code\`. Pagination parameters and response envelopes are documented per operation.++For agent clients, use the MCP endpoint at [${apiUrl}/mcp](${apiUrl}/mcp). SCIM, worker-internal routes, and repository webhooks use the separate credentials shown on their operations.`;// The assembled Elysia app, without `.listen()`. `index.ts` imports this and// binds the port; tests import it and pass it to Eden Treaty to drive routes in@@ -29,9 +53,12 @@ export const app = new Elysia()origin: trustedOrigins,credentials: true,methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],- allowedHeaders: ['Content-Type', 'Authorization'],+ allowedHeaders: ['Content-Type', 'Authorization', 'x-api-key'],}),)+ .onAfterHandle({ as: 'global' }, ({ request, response }) =>+ normalizeOpenApiResponse(request, response),+ )// OpenAPI docs. Mounted on the main app (outside the planner's session guard)// so the UI at /docs and the spec at /docs/json are reachable without a// session. The spec is generated from the `t` schemas on every route.@@ -49,9 +76,10 @@ export const app = new Elysia()documentation: {info: {title: "It's a Plan API",- version: '1.0.0',- description: 'REST API for projects, issues, and their dependent entities.\n\n',+ version: pkg.version,+ description: apiDescription,},+ servers: [{ url: apiUrl, description: 'Configured public API origin' }],tags: [{ name: 'Projects', description: 'Projects and the full work items view' },{ name: 'Members', description: 'Project membership and roles' },@@ -147,6 +175,48 @@ export const app = new Elysia()components: {securitySchemes: {apiKey: { type: 'apiKey', in: 'header', name: 'x-api-key' },+ scimBearer: {+ type: 'http',+ scheme: 'bearer',+ bearerFormat: 'opaque',+ description: 'Instance SCIM token generated in God mode.',+ },+ workerToken: {+ type: 'apiKey',+ in: 'header',+ name: 'x-worker-token',+ description: 'Shared token used only by the worker and bot services.',+ },+ gitHubSignature: {+ type: 'apiKey',+ in: 'header',+ name: 'x-hub-signature-256',+ description: 'GitHub HMAC signature generated from the raw request body.',+ },+ gitLabToken: {+ type: 'apiKey',+ in: 'header',+ name: 'x-gitlab-token',+ description: 'GitLab secret token configured on the project webhook.',+ },+ giteaSignature: {+ type: 'apiKey',+ in: 'header',+ name: 'x-gitea-signature',+ description: 'Gitea HMAC signature generated from the raw request body.',+ },+ forgejoSignature: {+ type: 'apiKey',+ in: 'header',+ name: 'x-forgejo-signature',+ description: 'Forgejo HMAC signature generated from the raw request body.',+ },+ bitbucketSignature: {+ type: 'apiKey',+ in: 'header',+ name: 'x-hub-signature',+ description: 'Bitbucket HMAC signature generated from the raw request body.',+ },},},security: [{ apiKey: [] }],diff --git a/apps/api/src/modules/git/index.ts b/apps/api/src/modules/git/index.tsindex 0b7001bc..9e2d8b29 100644--- a/apps/api/src/modules/git/index.ts+++ b/apps/api/src/modules/git/index.ts@@ -43,7 +43,11 @@ export const gitSettingsRoutes = new Elysia({{permission: ['integrations', 'read'],response: { 200: GitSettingsResponse, ...accessErrors },- detail: { summary: "Get a project's repository integration settings" },+ detail: {+ summary: "Get a project's repository integration settings",+ description:+ 'Return the webhook endpoint, enabled events, merge automation, and the secret only when the caller may edit integrations.',+ },},).patch(@@ -53,7 +57,11 @@ export const gitSettingsRoutes = new Elysia({permission: ['integrations', 'edit'],body: updateGitSettingsBody,response: { 200: GitSettingsResponse, ...commonErrors },- detail: { summary: "Update a project's repository integration settings" },+ detail: {+ summary: "Update a project's repository integration settings",+ description:+ 'Enable repository events and configure the issue state change applied after a merge.',+ },},).post(@@ -66,7 +74,11 @@ export const gitSettingsRoutes = new Elysia({{permission: ['integrations', 'edit'],response: { 200: GitSettingsResponse, ...accessErrors },- detail: { summary: "Regenerate a project's repository webhook secret" },+ detail: {+ summary: "Regenerate a project's repository webhook secret",+ description:+ 'Replace the shared webhook secret and update every webhook managed through a provider connection.',+ },},).get(@@ -75,7 +87,11 @@ export const gitSettingsRoutes = new Elysia({{permission: ['integrations', 'read'],response: { 200: GitProviderConnectionListResponse, ...accessErrors },- detail: { summary: "List a project's Git provider connections" },+ detail: {+ summary: "List a project's Git provider connections",+ description:+ 'List the GitHub and GitLab accounts authorized for this project and their connected repositories.',+ },},).post(@@ -89,7 +105,11 @@ export const gitSettingsRoutes = new Elysia({permission: ['integrations', 'edit'],body: createGitProviderConnectionBody,response: { 201: GitProviderConnectionResponse, ...commonErrors, ...errors(502) },- detail: { summary: 'Connect a Git provider account' },+ detail: {+ summary: 'Connect a Git provider account',+ description:+ 'Validate a GitHub or GitLab access token, encrypt it, and save the provider account for repository selection.',+ },},).delete(@@ -102,7 +122,11 @@ export const gitSettingsRoutes = new Elysia({permission: ['integrations', 'edit'],params: gitProviderConnectionParams,response: { 204: t.Void(), ...commonErrors, ...errors(502) },- detail: { summary: 'Disconnect a Git provider account' },+ detail: {+ summary: 'Disconnect a Git provider account',+ description:+ 'Remove every managed repository webhook for the connection, then delete the encrypted provider credential.',+ },},).get(@@ -119,7 +143,11 @@ export const gitSettingsRoutes = new Elysia({params: gitProviderConnectionParams,query: availableRepositoriesQuery,response: { 200: AvailableGitRepositoryPageResponse, ...commonErrors, ...errors(502) },- detail: { summary: 'List repositories available through a Git provider connection' },+ detail: {+ summary: 'List repositories available through a Git provider connection',+ description:+ 'Search repositories visible to the connected provider account and report which ones are already connected.',+ },},).post(@@ -131,7 +159,11 @@ export const gitSettingsRoutes = new Elysia({params: gitProviderConnectionParams,body: connectRepositoriesBody,response: { 200: GitProviderConnectionResponse, ...commonErrors, ...errors(502) },- detail: { summary: 'Connect repositories and install their webhooks' },+ detail: {+ summary: 'Connect repositories and install their webhooks',+ description:+ 'Add the selected repositories to the project and create or reconcile provider webhooks for pull request and CI events.',+ },},).delete(@@ -144,6 +176,10 @@ export const gitSettingsRoutes = new Elysia({permission: ['integrations', 'edit'],params: gitManagedRepositoryParams,response: { 204: t.Void(), ...commonErrors, ...errors(502) },- detail: { summary: 'Disconnect a repository and remove its managed webhook' },+ detail: {+ summary: 'Disconnect a repository and remove its managed webhook',+ description:+ 'Delete the repository connection and remove the webhook that Plan installed at the provider.',+ },},);diff --git a/apps/api/src/modules/scim/index.ts b/apps/api/src/modules/scim/index.tsindex 2eafd4aa..c955f6a9 100644--- a/apps/api/src/modules/scim/index.ts+++ b/apps/api/src/modules/scim/index.ts@@ -81,7 +81,11 @@ function requestedPage(query: { startIndex?: number; count?: number }) {};}-const scimHandlers = new Elysia({ name: 'scim-handlers', prefix: SCIM_PREFIX })+const scimHandlers = new Elysia({+ name: 'scim-handlers',+ prefix: SCIM_PREFIX,+ detail: { tags: ['SCIM'] },+})// RFC 7644 §3.1 allows a SCIM client to send `application/scim+json`, and real// identity providers (Okta, Entra, Authentik) do. Elysia's default body parser// matches `Content-Type` exactly against `application/json`, so a request sentdiff --git a/apps/api/src/openapi.ts b/apps/api/src/openapi.tsnew file mode 100644index 00000000..f33b8bcc--- /dev/null+++ b/apps/api/src/openapi.ts@@ -0,0 +1,145 @@+import type { ElysiaSwaggerConfig } from '@elysiajs/swagger';++type OpenApiDocument = NonNullable<ElysiaSwaggerConfig['documentation']>;+type Paths = NonNullable<OpenApiDocument['paths']>;+type PathItem = NonNullable<Paths[string]>;+type Operation = NonNullable<PathItem['get']>;++const METHODS = ['get', 'post', 'put', 'patch', 'delete'] as const;+const GENERIC_CONTENT_TYPES = ['application/json', 'multipart/form-data', 'text/plain'];++const MULTIPART_OPERATIONS = new Set([+ 'POST /issues/{issueId}/attachments',+ 'PUT /attachments/{publicId}',+ 'POST /me/avatar',+ 'POST /projects/{projectKey}/agent-skills/{skillId}/references',+]);++const PUBLIC_GET_PATHS = [+ /^\/$/,+ /^\/auth-config$/,+ /^\/attachments\/\{publicId\}\/raw$/,+ /^\/chat-attachments\/\{publicId\}\/raw$/,+ /^\/avatars\/\{id\}\/raw$/,+ /^\/invites\/\{token\}$/,+ /^\/share\//,+];++const GIT_WEBHOOK_SECURITY: NonNullable<Operation['security']> = [+ { gitHubSignature: [] },+ { gitLabToken: [] },+ { giteaSignature: [] },+ { forgejoSignature: [] },+ { bitbucketSignature: [] },+];++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function isOpenApiDocument(value: unknown): value is OpenApiDocument & { paths: Paths } {+ return isRecord(value) && isRecord(value.paths);+}++function operationAt(pathItem: PathItem, method: (typeof METHODS)[number]): Operation | undefined {+ return pathItem[method] as Operation | undefined;+}++function mediaTypeFor(path: string, method: string): string {+ if (path.startsWith('/scim/v2/')) return 'application/scim+json';+ if (MULTIPART_OPERATIONS.has(`${method.toUpperCase()} ${path}`)) return 'multipart/form-data';+ return 'application/json';+}++function normalizeContent(+ content: Record<string, unknown> | undefined,+ mediaType: string,+): Record<string, unknown> | undefined {+ if (!content) return undefined;+ const keys = Object.keys(content);+ if (!keys.some((key) => GENERIC_CONTENT_TYPES.includes(key))) return content;+ const schema = content[mediaType] ?? content['application/json'] ?? content[keys[0]!];+ return schema === undefined ? content : { [mediaType]: schema };+}++function normalizeOperationContent(operation: Operation, path: string, method: string): void {+ const requestBody = operation.requestBody;+ if (requestBody && 'content' in requestBody && requestBody.content) {+ if (path === '/webhooks/git/{webhookId}' || path === '/webhooks/github/{webhookId}') {+ requestBody.content = {+ 'application/json': {+ schema: {+ type: 'object',+ additionalProperties: true,+ description: 'The provider webhook payload. The exact shape depends on the event.',+ },+ },+ };+ } else {+ requestBody.content = normalizeContent(+ requestBody.content as Record<string, unknown>,+ mediaTypeFor(path, method),+ ) as typeof requestBody.content;+ }+ }++ const responseMediaType = path.startsWith('/scim/v2/')+ ? 'application/scim+json'+ : 'application/json';+ for (const response of Object.values(operation.responses ?? {})) {+ if (!response || !('content' in response) || !response.content) continue;+ response.content = normalizeContent(+ response.content as Record<string, unknown>,+ responseMediaType,+ ) as typeof response.content;+ }+}++function normalizeOperationSecurity(operation: Operation, path: string, method: string): void {+ if (path.startsWith('/scim/v2/')) {+ operation.tags = ['SCIM'];+ operation.security = [{ scimBearer: [] }];+ return;+ }+ if (path.startsWith('/internal/')) {+ operation.security = [{ workerToken: [] }];+ return;+ }+ if (path === '/webhooks/git/{webhookId}' || path === '/webhooks/github/{webhookId}') {+ operation.security = GIT_WEBHOOK_SECURITY;+ return;+ }+ if (path === '/me' && method === 'get') {+ operation.security = [{}, { apiKey: [] }];+ return;+ }+ if (method === 'get' && PUBLIC_GET_PATHS.some((pattern) => pattern.test(path))) {+ operation.security = [];+ }+}++function ensureDescription(operation: Operation): void {+ if (operation.description || !operation.summary) return;+ operation.description =+ `${operation.summary}. ` ++ 'The request and response schemas below are generated from the validation used by the API.';+}++export function normalizeOpenApiDocument(document: OpenApiDocument & { paths: Paths }) {+ for (const [path, pathItem] of Object.entries(document.paths)) {+ if (!pathItem) continue;+ for (const method of METHODS) {+ const operation = operationAt(pathItem, method);+ if (!operation) continue;+ normalizeOperationSecurity(operation, path, method);+ normalizeOperationContent(operation, path, method);+ ensureDescription(operation);+ }+ }+ return document;+}++export function normalizeOpenApiResponse(request: Request, response: unknown): unknown {+ if (new URL(request.url).pathname !== '/docs/json' || !isOpenApiDocument(response)) return;+ return normalizeOpenApiDocument(response);+}