mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-23 05:21:15 +00:00
feat(api): OpenAPI/Swagger docs at /api/docs behind TREK_API_DOCS_ENABLED (#1412)
Swagger UI + raw spec (/api/docs-json, -yaml) over all controllers, with a bearer button that works with a plain session JWT. Off by default - the spec enumerates the whole surface incl. admin routes, so exposing it is an explicit self-hoster decision (same kill-switch pattern as TREK_PLUGINS_ENABLED). Request bodies come from the Zod schemas the routes already validate with: an enricher walks every controller, finds whole-body ZodValidationPipe params and lifts their schema into the document via zod v4's native z.toJSONSchema - nothing is annotated twice, and any route that gains a Zod pipe is documented automatically.
This commit is contained in:
Generated
+79
-5
@@ -4127,6 +4127,12 @@
|
||||
"pbf": "bin/pbf"
|
||||
}
|
||||
},
|
||||
"node_modules/@microsoft/tsdoc": {
|
||||
"version": "0.16.0",
|
||||
"resolved": "https://registry.npmjs.org/@microsoft/tsdoc/-/tsdoc-0.16.0.tgz",
|
||||
"integrity": "sha512-xgAyonlVVS+q7Vc7qLW0UrJU7rSFcETRWsqdXZtjzRU8dF+6CkozTK4V4y1LwOX7j8r/vHphjDeMeGI4tNGeGA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@modelcontextprotocol/sdk": {
|
||||
"version": "1.29.0",
|
||||
"resolved": "https://registry.npmjs.org/@modelcontextprotocol/sdk/-/sdk-1.29.0.tgz",
|
||||
@@ -4757,6 +4763,26 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@nestjs/mapped-types": {
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@nestjs/mapped-types/-/mapped-types-2.1.1.tgz",
|
||||
"integrity": "sha512-SCCoMEJ6jdeI5h/N+KCVF1+pmg/hmEkNA5nHTS8Gvww7T/LCl4o1gFLinw2iQ60w7slFkszHcGLKGdazVI4F8A==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"@nestjs/common": "^10.0.0 || ^11.0.0",
|
||||
"class-transformer": "^0.4.0 || ^0.5.0",
|
||||
"class-validator": "^0.13.0 || ^0.14.0 || ^0.15.0",
|
||||
"reflect-metadata": "^0.1.12 || ^0.2.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"class-transformer": {
|
||||
"optional": true
|
||||
},
|
||||
"class-validator": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@nestjs/platform-express": {
|
||||
"version": "11.1.27",
|
||||
"resolved": "https://registry.npmjs.org/@nestjs/platform-express/-/platform-express-11.1.27.tgz",
|
||||
@@ -5070,6 +5096,39 @@
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/@nestjs/swagger": {
|
||||
"version": "11.4.5",
|
||||
"resolved": "https://registry.npmjs.org/@nestjs/swagger/-/swagger-11.4.5.tgz",
|
||||
"integrity": "sha512-lvndlJmWBVDOUT0uEtLi6sSpW1syK2/nbAlHBhiELBORMpJGe9+EiWAT9qHtB10jW91L2Jmlwkr0/lttsYZrig==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@microsoft/tsdoc": "0.16.0",
|
||||
"@nestjs/mapped-types": "2.1.1",
|
||||
"js-yaml": "4.3.0",
|
||||
"lodash": "4.18.1",
|
||||
"path-to-regexp": "8.4.2",
|
||||
"swagger-ui-dist": "5.32.8"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@fastify/static": "^8.0.0 || ^9.0.0",
|
||||
"@nestjs/common": "^11.0.1",
|
||||
"@nestjs/core": "^11.0.1",
|
||||
"class-transformer": "*",
|
||||
"class-validator": "*",
|
||||
"reflect-metadata": "^0.1.12 || ^0.2.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@fastify/static": {
|
||||
"optional": true
|
||||
},
|
||||
"class-transformer": {
|
||||
"optional": true
|
||||
},
|
||||
"class-validator": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/@nestjs/testing": {
|
||||
"version": "11.1.27",
|
||||
"resolved": "https://registry.npmjs.org/@nestjs/testing/-/testing-11.1.27.tgz",
|
||||
@@ -6443,6 +6502,13 @@
|
||||
],
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/@scarf/scarf": {
|
||||
"version": "1.4.0",
|
||||
"resolved": "https://registry.npmjs.org/@scarf/scarf/-/scarf-1.4.0.tgz",
|
||||
"integrity": "sha512-xxeapPiUXdZAE3che6f3xogoJPeZgig6omHEy1rIY5WVsB3H2BHNnZH+gHG6x91SCWyQCzWGsuL2Hh3ClO5/qQ==",
|
||||
"hasInstallScript": true,
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/@simplewebauthn/browser": {
|
||||
"version": "13.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@simplewebauthn/browser/-/browser-13.3.0.tgz",
|
||||
@@ -8106,7 +8172,6 @@
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz",
|
||||
"integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==",
|
||||
"dev": true,
|
||||
"license": "Python-2.0"
|
||||
},
|
||||
"node_modules/aria-query": {
|
||||
@@ -12885,10 +12950,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/js-yaml": {
|
||||
"version": "4.2.0",
|
||||
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.2.0.tgz",
|
||||
"integrity": "sha512-ePWsvanv0DWuDRsW8dnt+R4jQ31SCRCQ7hhNcPXZPsoBZiemuZNYGf7adZdqX2D86j6rvKp3RpCxVTSb8WQlOw==",
|
||||
"dev": true,
|
||||
"version": "4.3.0",
|
||||
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.0.tgz",
|
||||
"integrity": "sha512-1td788aAnnZ5qs7V2QIRl1owjtYpbKt749Y3xauqQgwIIGF/xXWz1wMTEBx5O3LK3lXLVuqXPdPxj2BoFHaW9Q==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
@@ -18531,6 +18595,15 @@
|
||||
"integrity": "sha512-djbJ/vZKZO+gPoSDThGNpKDO+o+bAeA4XQKovvkNCqnIS2t+S4qnLAGQhyyrulhCFRl1WWzAp0wUDV8PpTVU3g==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/swagger-ui-dist": {
|
||||
"version": "5.32.8",
|
||||
"resolved": "https://registry.npmjs.org/swagger-ui-dist/-/swagger-ui-dist-5.32.8.tgz",
|
||||
"integrity": "sha512-dgMdWXIgnI4zX4OPhKEdWnlDODbgm8W3AX0Ivn/BBqcUh6xZsBxhZMnvk6DJyRz1BTrj8dPxtarmEGgkz30oyA==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@scarf/scarf": "=1.4.0"
|
||||
}
|
||||
},
|
||||
"node_modules/symbol-tree": {
|
||||
"version": "3.2.4",
|
||||
"resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz",
|
||||
@@ -21162,6 +21235,7 @@
|
||||
"@nestjs/common": "^11.1.24",
|
||||
"@nestjs/core": "^11.1.24",
|
||||
"@nestjs/platform-express": "^11.1.24",
|
||||
"@nestjs/swagger": "^11.4.5",
|
||||
"@simplewebauthn/server": "^13.1.2",
|
||||
"@trek/shared": "*",
|
||||
"archiver": "^6.0.1",
|
||||
|
||||
@@ -26,6 +26,7 @@
|
||||
"@nestjs/common": "^11.1.24",
|
||||
"@nestjs/core": "^11.1.24",
|
||||
"@nestjs/platform-express": "^11.1.24",
|
||||
"@nestjs/swagger": "^11.4.5",
|
||||
"@simplewebauthn/server": "^13.1.2",
|
||||
"@trek/shared": "*",
|
||||
"archiver": "^6.0.1",
|
||||
|
||||
@@ -4,6 +4,8 @@ import type { INestApplication } from '@nestjs/common';
|
||||
import { AppModule } from './nest/app.module';
|
||||
import { applyGlobalMiddleware } from './middleware/globalMiddleware';
|
||||
import { applyPlatformUploads, applyPlatformTransport, applyPlatformStatic } from './nest/platform/platform.routes';
|
||||
import { apiDocsEnabled } from './nest/common/api-docs.kill-switch';
|
||||
import { setupApiDocs } from './nest/platform/api-docs';
|
||||
|
||||
/**
|
||||
* Builds the unified TREK NestJS application that serves the ENTIRE surface — the
|
||||
@@ -27,6 +29,8 @@ import { applyPlatformUploads, applyPlatformTransport, applyPlatformStatic } fro
|
||||
* metadata, the /mcp routes, the /oauth/consent COOP header.
|
||||
* 4. applyPlatformStatic — the production built-client static assets (so a real
|
||||
* asset request returns the file before the Nest router 404s it).
|
||||
* 4b. setupApiDocs — Swagger UI/spec at /api/docs* when TREK_API_DOCS_ENABLED;
|
||||
* also Express-level, so it must precede init for the same reason.
|
||||
* 5. app.init() — registers every migrated /api domain (the Nest controllers).
|
||||
*
|
||||
* The SPA index.html fallback (unmatched GET → index.html in production) is the
|
||||
@@ -40,6 +44,7 @@ export async function buildApp(): Promise<INestApplication> {
|
||||
applyPlatformUploads(instance);
|
||||
applyPlatformTransport(instance);
|
||||
applyPlatformStatic(instance);
|
||||
if (apiDocsEnabled()) setupApiDocs(app);
|
||||
await app.init();
|
||||
return app;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
/**
|
||||
* API-docs kill switch (#1412). Deliberately NOT in src/config.ts: tests mock
|
||||
* that module with partial exports, and reading the env at call time keeps the
|
||||
* flag testable per-request (same pattern as plugins/kill-switch.ts).
|
||||
*
|
||||
* Off by default — the generated spec enumerates every route including the
|
||||
* admin surface, so exposing it is an explicit self-hoster decision.
|
||||
*/
|
||||
export function apiDocsEnabled(): boolean {
|
||||
return (process.env.TREK_API_DOCS_ENABLED || '').trim().toLowerCase() === 'true';
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
import { RequestMethod } from '@nestjs/common';
|
||||
import { ModulesContainer } from '@nestjs/core';
|
||||
import { PATH_METADATA, METHOD_METADATA, ROUTE_ARGS_METADATA } from '@nestjs/common/constants';
|
||||
import { z, type ZodType } from 'zod';
|
||||
import type { OpenAPIObject } from '@nestjs/swagger';
|
||||
import { ZodValidationPipe } from './zod-validation.pipe';
|
||||
|
||||
/**
|
||||
* Phase 2 of #1412: real request-body schemas without annotating anything
|
||||
* twice. The API validates with Zod via `@Body(new ZodValidationPipe(schema))`
|
||||
* — that pipe IS the schema source of truth, so this enricher walks every
|
||||
* controller route, finds full-body Zod pipes, and writes the converted
|
||||
* JSON schema into the generated OpenAPI document. Any route that gains a
|
||||
* ZodValidationPipe is documented automatically from then on.
|
||||
*/
|
||||
|
||||
/** Zod → OpenAPI 3.0 schema; degrades to a bare object for unrepresentable schemas. */
|
||||
export function zodToOpenApi(schema: ZodType): Record<string, unknown> {
|
||||
try {
|
||||
return z.toJSONSchema(schema, { target: 'openapi-3.0', io: 'input', unrepresentable: 'any' }) as Record<string, unknown>;
|
||||
} catch {
|
||||
return { type: 'object' };
|
||||
}
|
||||
}
|
||||
|
||||
const HTTP_METHOD: Partial<Record<RequestMethod, string>> = {
|
||||
[RequestMethod.GET]: 'get',
|
||||
[RequestMethod.POST]: 'post',
|
||||
[RequestMethod.PUT]: 'put',
|
||||
[RequestMethod.PATCH]: 'patch',
|
||||
[RequestMethod.DELETE]: 'delete',
|
||||
};
|
||||
|
||||
// RouteParamtypes.BODY — the numeric key prefix @Body() writes into
|
||||
// ROUTE_ARGS_METADATA ("<paramtype>:<index>"). The enum lives in a private
|
||||
// @nestjs/common path, so the value is pinned here with a boot-time test.
|
||||
const BODY_PARAMTYPE = '3';
|
||||
|
||||
function joinPath(base: string | undefined, sub: string | undefined): string {
|
||||
const parts = `${base ?? ''}/${sub ?? ''}`.split('/').filter(Boolean);
|
||||
// Express ":param" → OpenAPI "{param}"
|
||||
return '/' + parts.map((p) => (p.startsWith(':') ? `{${p.slice(1)}}` : p)).join('/');
|
||||
}
|
||||
|
||||
/** Find full-body Zod schemas per route and merge them into the document. */
|
||||
export function attachZodBodySchemas(app: INestApplication, document: OpenAPIObject): void {
|
||||
const modules = app.get(ModulesContainer, { strict: false });
|
||||
for (const module of modules.values()) {
|
||||
for (const wrapper of module.controllers.values()) {
|
||||
const ctor = wrapper.metatype as (abstract new (...args: never[]) => unknown) | undefined;
|
||||
if (!ctor || typeof ctor !== 'function') continue;
|
||||
const basePath = Reflect.getMetadata(PATH_METADATA, ctor) as string | undefined;
|
||||
if (basePath === undefined) continue;
|
||||
|
||||
for (const name of Object.getOwnPropertyNames(ctor.prototype)) {
|
||||
if (name === 'constructor') continue;
|
||||
const handler = (ctor.prototype as Record<string, unknown>)[name];
|
||||
if (typeof handler !== 'function') continue;
|
||||
const methodEnum = Reflect.getMetadata(METHOD_METADATA, handler) as RequestMethod | undefined;
|
||||
const verb = methodEnum !== undefined ? HTTP_METHOD[methodEnum] : undefined;
|
||||
if (!verb) continue;
|
||||
|
||||
const args = (Reflect.getMetadata(ROUTE_ARGS_METADATA, ctor, name) ?? {}) as Record<
|
||||
string,
|
||||
{ index: number; data?: unknown; pipes?: unknown[] }
|
||||
>;
|
||||
const bodyArg = Object.entries(args).find(([key, meta]) =>
|
||||
key.startsWith(`${BODY_PARAMTYPE}:`)
|
||||
// @Body('field') picks a sub-field — only whole-body pipes describe the request body
|
||||
&& meta.data === undefined
|
||||
&& (meta.pipes ?? []).some((p) => p instanceof ZodValidationPipe),
|
||||
);
|
||||
if (!bodyArg) continue;
|
||||
const zodPipe = (bodyArg[1].pipes ?? []).find((p): p is ZodValidationPipe => p instanceof ZodValidationPipe)!;
|
||||
|
||||
const route = document.paths[joinPath(basePath, Reflect.getMetadata(PATH_METADATA, handler) as string | undefined)];
|
||||
const operation = route?.[verb as 'get' | 'post' | 'put' | 'patch' | 'delete'];
|
||||
if (!operation) continue;
|
||||
operation.requestBody = {
|
||||
required: true,
|
||||
content: { 'application/json': { schema: zodToOpenApi(zodPipe.schema) } },
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,7 +11,9 @@ import type { ZodType } from 'zod';
|
||||
*/
|
||||
@Injectable()
|
||||
export class ZodValidationPipe implements PipeTransform {
|
||||
constructor(private readonly schema: ZodType) {}
|
||||
// Public so the API-docs enricher can lift the schema into the OpenAPI
|
||||
// document (#1412) — the pipe stays the single source of truth.
|
||||
constructor(readonly schema: ZodType) {}
|
||||
|
||||
transform(value: unknown, _metadata: ArgumentMetadata): unknown {
|
||||
const result = this.schema.safeParse(value);
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
|
||||
import { attachZodBodySchemas } from '../common/api-zod';
|
||||
|
||||
/**
|
||||
* Swagger UI + OpenAPI spec for the REST API (#1412), gated behind
|
||||
* TREK_API_DOCS_ENABLED. Must run BEFORE app.init() — SwaggerModule.setup
|
||||
* registers Express-level routes, and a post-init Express route is
|
||||
* unreachable behind the Nest router (see bootstrap.ts).
|
||||
*
|
||||
* /api/docs Swagger UI (all controllers, try-it-out, auth button)
|
||||
* /api/docs-json raw OpenAPI 3 document (generated clients, Postman)
|
||||
* /api/docs-yaml same, as YAML
|
||||
*
|
||||
* The bearer button works with a plain TREK session JWT: extractToken
|
||||
* accepts `Authorization: Bearer` everywhere as the cookie fallback.
|
||||
*/
|
||||
export function setupApiDocs(app: INestApplication): void {
|
||||
const version: string = process.env.APP_VERSION || (require('../../../package.json') as { version: string }).version;
|
||||
const config = new DocumentBuilder()
|
||||
.setTitle('TREK API')
|
||||
.setDescription(
|
||||
'The REST API the TREK web app itself runs on. Authenticate with a session JWT — '
|
||||
+ 'either the `trek_session` cookie (same browser) or an `Authorization: Bearer <jwt>` header.',
|
||||
)
|
||||
.setVersion(version)
|
||||
.addBearerAuth({ type: 'http', scheme: 'bearer', bearerFormat: 'JWT' }, 'session')
|
||||
.addCookieAuth('trek_session')
|
||||
.addSecurityRequirements('session')
|
||||
.build();
|
||||
const document = SwaggerModule.createDocument(app, config);
|
||||
// Lift the Zod schemas the routes already validate with into the document —
|
||||
// no double annotation, every ZodValidationPipe body is documented.
|
||||
attachZodBodySchemas(app, document);
|
||||
SwaggerModule.setup('api/docs', app, document, {
|
||||
jsonDocumentUrl: 'api/docs-json',
|
||||
yamlDocumentUrl: 'api/docs-yaml',
|
||||
swaggerOptions: { persistAuthorization: true },
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
/**
|
||||
* API-DOCS (#1412) — the flag-gated Swagger surface: /api/docs (UI),
|
||||
* /api/docs-json (raw OpenAPI 3 spec incl. the Zod-derived request bodies),
|
||||
* off-by-default behaviour, and the CSP staying intact on the docs routes.
|
||||
* Boots the real buildApp() like bootstrap.test.ts.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeAll, afterAll } from 'vitest';
|
||||
import request from 'supertest';
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
|
||||
const { testDb, dbMock } = vi.hoisted(() => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-require-imports
|
||||
const Database = require('better-sqlite3');
|
||||
const db = new Database(':memory:');
|
||||
db.exec('PRAGMA journal_mode = WAL');
|
||||
db.exec('PRAGMA foreign_keys = ON');
|
||||
db.exec('PRAGMA busy_timeout = 5000');
|
||||
const mock = {
|
||||
db,
|
||||
closeDb: () => {},
|
||||
reinitialize: () => {},
|
||||
getPlaceWithTags: () => null,
|
||||
canAccessTrip: () => undefined,
|
||||
isOwner: () => false,
|
||||
};
|
||||
return { testDb: db, dbMock: mock };
|
||||
});
|
||||
|
||||
vi.mock('../../src/db/database', () => dbMock);
|
||||
vi.mock('../../src/config', () => ({
|
||||
JWT_SECRET: 'test-jwt-secret-for-trek-testing-only',
|
||||
ENCRYPTION_KEY: 'a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2a3b4c5d6a7b8c9d0e1f2',
|
||||
updateJwtSecret: () => {},
|
||||
SESSION_DURATION: '24h',
|
||||
SESSION_DURATION_MS: 86400000,
|
||||
SESSION_DURATION_SECONDS: 86400,
|
||||
DEFAULT_LANGUAGE: 'en',
|
||||
}));
|
||||
vi.mock('../../src/websocket', () => ({ broadcast: vi.fn(), broadcastToUser: vi.fn() }));
|
||||
|
||||
import { createTables } from '../../src/db/schema';
|
||||
import { runMigrations } from '../../src/db/migrations';
|
||||
import { resetTestDb } from '../helpers/test-db';
|
||||
import { buildApp } from '../../src/bootstrap';
|
||||
import { apiDocsEnabled } from '../../src/nest/common/api-docs.kill-switch';
|
||||
|
||||
describe('API-DOCS (#1412) — flag-gated OpenAPI surface', () => {
|
||||
let app: INestApplication;
|
||||
let instance: import('express').Application;
|
||||
let prevFlag: string | undefined;
|
||||
|
||||
beforeAll(async () => {
|
||||
createTables(testDb);
|
||||
runMigrations(testDb);
|
||||
resetTestDb(testDb);
|
||||
prevFlag = process.env.TREK_API_DOCS_ENABLED;
|
||||
process.env.TREK_API_DOCS_ENABLED = 'true';
|
||||
app = await buildApp();
|
||||
instance = app.getHttpAdapter().getInstance();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
if (prevFlag === undefined) delete process.env.TREK_API_DOCS_ENABLED;
|
||||
else process.env.TREK_API_DOCS_ENABLED = prevFlag;
|
||||
await app.close();
|
||||
testDb.close();
|
||||
});
|
||||
|
||||
it('DOCS-001 — the kill switch parses the env strictly', () => {
|
||||
const prev = process.env.TREK_API_DOCS_ENABLED;
|
||||
try {
|
||||
process.env.TREK_API_DOCS_ENABLED = 'true';
|
||||
expect(apiDocsEnabled()).toBe(true);
|
||||
process.env.TREK_API_DOCS_ENABLED = ' TRUE ';
|
||||
expect(apiDocsEnabled()).toBe(true);
|
||||
process.env.TREK_API_DOCS_ENABLED = 'false';
|
||||
expect(apiDocsEnabled()).toBe(false);
|
||||
process.env.TREK_API_DOCS_ENABLED = '1';
|
||||
expect(apiDocsEnabled()).toBe(false);
|
||||
delete process.env.TREK_API_DOCS_ENABLED;
|
||||
expect(apiDocsEnabled()).toBe(false);
|
||||
} finally {
|
||||
if (prev === undefined) delete process.env.TREK_API_DOCS_ENABLED;
|
||||
else process.env.TREK_API_DOCS_ENABLED = prev;
|
||||
}
|
||||
});
|
||||
|
||||
it('DOCS-002 — /api/docs serves the Swagger UI with the CSP intact', async () => {
|
||||
const res = await request(instance).get('/api/docs').redirects(1);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.headers['content-type']).toContain('text/html');
|
||||
expect(res.headers['content-security-policy']).toBeDefined();
|
||||
});
|
||||
|
||||
it('DOCS-003 — /api/docs-json is a full OpenAPI 3 document over all controllers', async () => {
|
||||
const res = await request(instance).get('/api/docs-json');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.openapi).toMatch(/^3\./);
|
||||
// Reflection survived every controller: a few far-apart domains are present.
|
||||
expect(res.body.paths['/api/trips']).toBeDefined();
|
||||
expect(res.body.paths['/api/admin/addons/{id}']).toBeDefined();
|
||||
expect(res.body.components.securitySchemes.session).toBeDefined();
|
||||
});
|
||||
|
||||
it('DOCS-004 — Zod request bodies are lifted into the spec (no double annotation)', async () => {
|
||||
const res = await request(instance).get('/api/docs-json');
|
||||
// collections create validates with collectionCreateRequestSchema via
|
||||
// ZodValidationPipe — the enricher must surface its object schema.
|
||||
const create = res.body.paths['/api/addons/collections']?.post;
|
||||
expect(create).toBeDefined();
|
||||
const schema = create.requestBody?.content?.['application/json']?.schema;
|
||||
expect(schema?.type).toBe('object');
|
||||
expect(schema?.properties?.name).toBeDefined();
|
||||
});
|
||||
|
||||
it('DOCS-005 — without the flag the docs routes do not exist', async () => {
|
||||
const prev = process.env.TREK_API_DOCS_ENABLED;
|
||||
delete process.env.TREK_API_DOCS_ENABLED;
|
||||
let offApp: INestApplication | undefined;
|
||||
try {
|
||||
offApp = await buildApp();
|
||||
const off = offApp.getHttpAdapter().getInstance();
|
||||
expect((await request(off).get('/api/docs')).status).toBe(404);
|
||||
expect((await request(off).get('/api/docs-json')).status).toBe(404);
|
||||
} finally {
|
||||
if (offApp) await offApp.close();
|
||||
if (prev === undefined) delete process.env.TREK_API_DOCS_ENABLED;
|
||||
else process.env.TREK_API_DOCS_ENABLED = prev;
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* zodToOpenApi (#1412): Zod → OpenAPI 3.0 conversion + the degrade path.
|
||||
* The end-to-end enricher behaviour is covered by tests/integration/api-docs.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { z } from 'zod';
|
||||
import { zodToOpenApi } from '../../../src/nest/common/api-zod';
|
||||
|
||||
describe('zodToOpenApi', () => {
|
||||
it('converts an object schema with required/optional split', () => {
|
||||
const out = zodToOpenApi(z.object({ name: z.string(), count: z.number().optional() })) as {
|
||||
type: string; properties: Record<string, unknown>; required: string[];
|
||||
};
|
||||
expect(out.type).toBe('object');
|
||||
expect(out.properties.name).toEqual({ type: 'string' });
|
||||
expect(out.properties.count).toEqual({ type: 'number' });
|
||||
expect(out.required).toEqual(['name']);
|
||||
});
|
||||
|
||||
it('survives transform-heavy schemas via unrepresentable: any', () => {
|
||||
const out = zodToOpenApi(z.object({ when: z.string().transform((s) => new Date(s)) }));
|
||||
expect((out as { type: string }).type).toBe('object');
|
||||
});
|
||||
|
||||
it('degrades to a bare object instead of throwing on a broken schema', () => {
|
||||
expect(zodToOpenApi({} as never)).toEqual({ type: 'object' });
|
||||
});
|
||||
});
|
||||
@@ -190,6 +190,18 @@ For setup instructions, see [MCP-Overview](MCP-Overview).
|
||||
|
||||
---
|
||||
|
||||
## API Docs
|
||||
|
||||
| Variable | Description | Default |
|
||||
|-------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------|---------|
|
||||
| `TREK_API_DOCS_ENABLED` | Serve interactive OpenAPI/Swagger docs at `/api/docs` (raw spec at `/api/docs-json`). The spec enumerates every route including the admin surface, so it is off by default. | `false` |
|
||||
|
||||
With the flag on, `/api/docs` lists every REST endpoint with try-it-out; authorize with a session JWT
|
||||
via the Bearer button (the API accepts `Authorization: Bearer <jwt>` everywhere as the cookie fallback).
|
||||
Request bodies validated with Zod are documented automatically from the same schemas.
|
||||
|
||||
---
|
||||
|
||||
## Booking Import (KDE Itinerary)
|
||||
|
||||
| Variable | Description | Default |
|
||||
|
||||
Reference in New Issue
Block a user