📖 fix: Verify Agents OpenAPI contracts and disable external reporting (#16028)

This commit is contained in:
Dustin Healy 2026-09-16 12:17:56 -07:00 • committed by GitHub
parent a26a6709ff
commit 44af4d3789
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
15 changed files with 746 additions and 21 deletions

View file

@ -39,6 +39,7 @@ concurrency:
cancel-in-progress: true
env:
SCARF_ANALYTICS: 'false'
NODE_ENV: CI
NODE_OPTIONS: '--max-old-space-size=${{ secrets.NODE_MAX_OLD_SPACE_SIZE || 6144 }}'
@ -125,7 +126,6 @@ jobs:
path: packages/api/dist
retention-days: 2
# Codegraph test selection — the GATE (stage 1: backend jest only).
#
# Paranoia policy: FULL on opened/reopened PRs and on every push to dev (see the push
@ -311,6 +311,9 @@ jobs:
- name: OpenAPI spec drift check
run: npm run -w @librechat/api openapi:check
- name: OpenAPI built documentation smoke test
run: npm run -w @librechat/api openapi:test
- name: Type check @librechat/client
run: npx tsc --noEmit -p packages/client/tsconfig.json

View file

@ -9,6 +9,8 @@ RUN apk add --no-cache python3 py3-pip uv
# Set environment variable to use jemalloc
ENV LD_PRELOAD=/usr/lib/libjemalloc.so.2
# Disable dependency installation analytics before any npm lifecycle scripts run.
ENV SCARF_ANALYTICS=false
# Add `uv` for extended MCP support
COPY --from=ghcr.io/astral-sh/uv:0.9.5-python3.12-alpine /usr/local/bin/uv /usr/local/bin/uvx /bin/

View file

@ -17,6 +17,8 @@ RUN apk upgrade --no-cache
RUN apk add --no-cache jemalloc
# Set environment variable to use jemalloc
ENV LD_PRELOAD=/usr/lib/libjemalloc.so.2
# Disable dependency installation analytics before any npm lifecycle scripts run.
ENV SCARF_ANALYTICS=false
WORKDIR /app
RUN apk --no-cache add curl

View file

@ -141,6 +141,8 @@
"devDependencies": {
"@babel/preset-env": "^7.29.5",
"@types/sanitize-html": "^2.16.1",
"ajv": "8.18.0",
"ajv-formats": "3.0.1",
"jest": "^30.2.0",
"mongodb-memory-server": "^11.0.1",
"nodemon": "^3.1.14",

View file

@ -0,0 +1,399 @@
const crypto = require('crypto');
const fs = require('fs');
const http = require('http');
const os = require('os');
const path = require('path');
const express = require('express');
const jwt = require('jsonwebtoken');
const mongoose = require('mongoose');
const request = require('supertest');
const Ajv2020 = require('ajv/dist/2020').default;
const addFormats = require('ajv-formats');
const { MongoMemoryServer } = require('mongodb-memory-server');
const { createModels, tenantStorage } = require('@librechat/data-schemas');
const {
EModelEndpoint,
EToolResources,
PermissionTypes,
Permissions,
SystemRoles,
} = require('librechat-data-provider');
const {
ErrorController,
createAgentManagementAuth,
createAgentManagementFileHandlers,
createAgentManagementUploadResponse,
createAgentUploadLock,
createSkillManagementHandlers,
handleJsonParseError,
restoreTenantContextFromReq,
} = require('@librechat/api');
const { createMulterInstance } = require('~/server/routes/files/multer');
jest.mock('~/server/services/Config', () => ({
checkCapability: jest.fn().mockResolvedValue(true),
}));
const specPath = path.resolve(__dirname, '../../../../../packages/api/openapi/agents.openapi.json');
const tenantId = 'openapi-contract-tenant';
const clientId = 'openapi-contract-client';
const subject = `${clientId}@clients`;
const audience = 'openapi-contract-audience';
let skillId;
function pointerEscape(value) {
return value.replaceAll('~', '~0').replaceAll('/', '~1');
}
function findOperation(spec, operationId) {
for (const [routePath, pathItem] of Object.entries(spec.paths)) {
for (const [method, operation] of Object.entries(pathItem)) {
if (operation.operationId === operationId) return { method, operation, routePath };
}
}
throw new Error(`Missing OpenAPI operation ${operationId}`);
}
function expectResponseToMatchSpec(spec, operationId, response) {
const { method, routePath } = findOperation(spec, operationId);
const mediaType = response.headers['content-type'].split(';', 1)[0];
const responseContract = spec.paths[routePath][method].responses[String(response.status)];
const schema = responseContract?.content?.[mediaType]?.schema;
expect(schema).toBeDefined();
const schemaPointer = [
'paths',
routePath,
method,
'responses',
String(response.status),
'content',
mediaType,
'schema',
]
.map(pointerEscape)
.join('/');
const ajv = new Ajv2020({ allErrors: true, strict: false });
addFormats(ajv);
const validate = ajv.compile({ ...spec, $ref: `#/${schemaPointer}` });
const payload = mediaType === 'application/json' ? response.body : response.text;
const valid = validate(payload);
expect({ errors: validate.errors, valid }).toEqual({ errors: null, valid: true });
}
describe('Agents OpenAPI actual HTTP contract', () => {
jest.setTimeout(120000);
let app;
let db;
let fixtureRoot;
let jwksServer;
let mongoServer;
let spec;
let token;
let wrongAudienceToken;
let user;
let agent;
let originalUploadsPath;
beforeAll(async () => {
fixtureRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'librechat-openapi-contract-'));
const uploadsPath = path.join(fixtureRoot, 'uploads');
fs.mkdirSync(uploadsPath, { recursive: true });
const configuredPaths = require('~/config/paths');
originalUploadsPath = configuredPaths.uploads;
configuredPaths.uploads = uploadsPath;
mongoServer = await MongoMemoryServer.create();
await mongoose.connect(mongoServer.getUri());
createModels(mongoose);
db = require('~/models');
user = await mongoose.models.User.create({
email: 'openapi-contract@example.test',
name: 'OpenAPI Contract Principal',
username: 'openapi-contract',
provider: 'local',
role: SystemRoles.ADMIN,
emailVerified: true,
tenantId,
});
agent = await tenantStorage.run({ tenantId }, () =>
db.createAgent({
id: crypto.randomUUID(),
name: 'OpenAPI Contract Agent',
provider: EModelEndpoint.openAI,
model: 'gpt-5',
author: user._id,
tenantId,
}),
);
const createdSkill = await tenantStorage.run({ tenantId }, () =>
db.createSkill({
name: 'openapi-contract-skill',
displayTitle: 'OpenAPI Contract Skill',
description: 'Disposable skill used to verify the public HTTP contract.',
body: '# OpenAPI Contract Skill',
author: user._id,
authorName: user.name,
tenantId,
}),
);
skillId = createdSkill.skill._id;
const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 2048 });
const keyId = 'openapi-contract-key';
const jwk = publicKey.export({ format: 'jwk' });
Object.assign(jwk, { alg: 'RS256', kid: keyId, use: 'sig' });
jwksServer = http.createServer((req, res) => {
if (req.url !== '/jwks.json') {
res.writeHead(404).end();
return;
}
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify({ keys: [jwk] }));
});
await new Promise((resolve) => jwksServer.listen(0, '127.0.0.1', resolve));
const issuer = `http://127.0.0.1:${jwksServer.address().port}`;
token = jwt.sign({ azp: clientId }, privateKey, {
algorithm: 'RS256',
audience,
expiresIn: '5m',
issuer,
keyid: keyId,
subject,
});
wrongAudienceToken = jwt.sign({ azp: clientId }, privateKey, {
algorithm: 'RS256',
audience: 'wrong-audience',
expiresIn: '5m',
issuer,
keyid: keyId,
subject,
});
const appConfig = {
fileStrategy: 'local',
paths: { uploads: uploadsPath },
fileConfig: {},
endpoints: {
agents: {
managementApi: {
auth: {
oidc: { enabled: true, issuer, audience, jwksUri: `${issuer}/jwks.json` },
clients: [
{
clientId,
subject,
userId: user._id.toString(),
tenantId,
},
],
},
},
},
},
};
const auth = createAgentManagementAuth({
findUser: (filter) => mongoose.models.User.findOne(filter),
getAppConfig: async () => appConfig,
isPrincipalActive: async () => true,
});
const getRoleByName = async () => ({
name: SystemRoles.ADMIN,
permissions: {
[PermissionTypes.AGENTS]: { [Permissions.USE]: true, [Permissions.CREATE]: true },
[PermissionTypes.SKILLS]: { [Permissions.USE]: true, [Permissions.CREATE]: true },
},
});
const { processAgentFileUpload } = require('~/server/services/Files/process');
const fileHandlers = createAgentManagementFileHandlers({
getRoleByName,
getAgentWithVersionCount: db.getAgentWithVersionCount,
getFiles: db.getFiles,
checkPermission: async () => true,
hasCapability: async () => true,
removeAgentResourceFiles: db.removeAgentResourceFiles,
processUpload: (req, res) =>
processAgentFileUpload({
req,
res: createAgentManagementUploadResponse(res, req.file, req.body.tool_resource),
metadata: { ...req.body, file_id: req.file_id },
}),
deleteTempFile: fs.promises.unlink,
getUploadConfig: async () => ({
endpoint: EModelEndpoint.openAI,
endpointType: EModelEndpoint.openAI,
disabled: false,
fileSizeLimit: 1024 * 1024,
fileLimit: 5,
totalSizeLimit: 5 * 1024 * 1024,
}),
isUploadPurposeEnabled: async () => true,
runUploadExclusive: createAgentUploadLock({ redisClient: null }),
});
const multipart = await createMulterInstance({
fileConfig: appConfig.fileConfig,
resolveEndpoint: fileHandlers.getUploadConfig,
uniqueTempPath: true,
});
const { getSkillToolDeps } = require('~/server/services/Endpoints/agents/skillDeps');
const skillHandlers = createSkillManagementHandlers({
handlers: {},
getSkillById: db.getSkillById,
getRoleByName,
checkPermission: async () => true,
hasCapability: async () => true,
saveFile: getSkillToolDeps().saveSkillFileContent,
});
app = express();
app.use(express.json({ limit: '3mb' }));
app.use(handleJsonParseError);
app.use('/api/agents/v1', auth, (req, _res, next) => {
req.config = appConfig;
next();
});
app.post(
'/api/agents/v1/agents/:id/files',
fileHandlers.authorizeUpload,
multipart.single('file'),
restoreTenantContextFromReq,
fileHandlers.upload,
);
app.put('/api/agents/v1/skills/:id/files/*relativePath', skillHandlers.updateFile);
app.get('/api/agents/v1/agents/:id', (_req, _res, next) =>
next(new Error('contract fixture escaped error')),
);
app.use(ErrorController);
spec = JSON.parse(fs.readFileSync(specPath, 'utf8'));
});
afterAll(async () => {
if (jwksServer) await new Promise((resolve) => jwksServer.close(resolve));
await mongoose.disconnect();
if (mongoServer) await mongoServer.stop();
require('~/config/paths').uploads = originalUploadsPath;
fs.rmSync(fixtureRoot, { recursive: true, force: true });
});
it('documents and validates the real OIDC authentication rejection', async () => {
const missing = await request(app).get(`/api/agents/v1/agents/${agent.id}`);
const invalid = await request(app)
.get(`/api/agents/v1/agents/${agent.id}`)
.set('Authorization', `Bearer ${wrongAudienceToken}`);
for (const response of [missing, invalid]) {
expect(response.status).toBe(401);
expect(response.body).toEqual({ error: 'Unauthorized' });
expectResponseToMatchSpec(spec, 'getAgent', response);
}
});
it('documents and validates a multipart upload persisted by the Agent upload pipeline', async () => {
const content = 'actual HTTP upload contract\n';
const response = await request(app)
.post(`/api/agents/v1/agents/${agent.id}/files`)
.set('Authorization', `Bearer ${token}`)
.field('purpose', EToolResources.context)
.attach('file', Buffer.from(content), {
filename: 'contract.txt',
contentType: 'text/plain',
});
expect(response.status).toBe(200);
expectResponseToMatchSpec(spec, 'uploadAgentFile', response);
const persisted = await mongoose.models.File.findOne({
file_id: response.body.id,
tenantId,
}).lean();
expect(persisted).toMatchObject({
bytes: Buffer.byteLength(content),
filename: 'contract.txt',
tenantId,
text: content,
type: 'text/plain',
});
const persistedAgent = await mongoose.models.Agent.findOne({ id: agent.id, tenantId }).lean();
expect(persistedAgent.tool_resources.context.file_ids).toContain(response.body.id);
});
it('documents and validates a skill-file write with Mongo and disk readback', async () => {
const initialContent = '# Contract reference\nCreated through the production skill writer.\n';
const content = '# Contract reference\nOverwritten through the production skill writer.\n';
const relativePath = 'references/contract.md';
const created = await request(app)
.put(`/api/agents/v1/skills/${skillId}/files/references/contract.md`)
.set('Authorization', `Bearer ${token}`)
.send({ content: initialContent });
const updated = await request(app)
.put(`/api/agents/v1/skills/${skillId}/files/references/contract.md`)
.set('Authorization', `Bearer ${token}`)
.send({ content });
expect(created.status).toBe(200);
expect(updated.status).toBe(200);
expectResponseToMatchSpec(spec, 'updateSkillFile', created);
expectResponseToMatchSpec(spec, 'updateSkillFile', updated);
const persisted = await mongoose.models.SkillFile.findOne({ skillId, relativePath }).lean();
expect(persisted).toMatchObject({
bytes: Buffer.byteLength(content),
mimeType: 'text/plain',
relativePath,
tenantId,
});
const diskPath = path.join(
require('~/config/paths').uploads,
user._id.toString(),
path.basename(persisted.filepath),
);
expect(fs.readFileSync(diskPath, 'utf8')).toBe(content);
});
it('validates parser and normalized management errors against their documented JSON forms', async () => {
const malformed = await request(app)
.put(`/api/agents/v1/skills/${skillId}/files/contract.md`)
.set('Authorization', `Bearer ${token}`)
.set('Content-Type', 'application/json')
.send('{');
const invalid = await request(app)
.put(`/api/agents/v1/skills/${skillId}/files/contract.md`)
.set('Authorization', `Bearer ${token}`)
.send({ content: 'valid', extra: true });
const oversizedUtf8 = await request(app)
.put(`/api/agents/v1/skills/${skillId}/files/contract.md`)
.set('Authorization', `Bearer ${token}`)
.send({ content: 'é'.repeat(512 * 1024 + 1) });
expect(malformed.status).toBe(400);
expect(invalid.status).toBe(400);
expect(oversizedUtf8.status).toBe(400);
expectResponseToMatchSpec(spec, 'updateSkillFile', malformed);
expectResponseToMatchSpec(spec, 'updateSkillFile', invalid);
expectResponseToMatchSpec(spec, 'updateSkillFile', oversizedUtf8);
});
it('records the global JSON size-limit response before authentication', async () => {
const response = await request(app)
.put(`/api/agents/v1/skills/${skillId}/files/contract.md`)
.set('Content-Type', 'application/json')
.send(JSON.stringify({ content: 'x'.repeat(3 * 1024 * 1024 + 1) }));
expect(response.status).toBe(500);
expect(response.text).toBe('An unknown error occurred.');
expectResponseToMatchSpec(spec, 'updateSkillFile', response);
});
it('documents the final error controller string response with its actual text/html type', async () => {
const response = await request(app)
.get(`/api/agents/v1/agents/${agent.id}`)
.set('Authorization', `Bearer ${token}`);
expect(response.status).toBe(500);
expect(response.text).toBe('An unknown error occurred.');
expectResponseToMatchSpec(spec, 'getAgent', response);
});
});

2
package-lock.json generated
View file

@ -159,6 +159,8 @@
"devDependencies": {
"@babel/preset-env": "^7.29.5",
"@types/sanitize-html": "^2.16.1",
"ajv": "8.18.0",
"ajv-formats": "3.0.1",
"jest": "^30.2.0",
"mongodb-memory-server": "^11.0.1",
"nodemon": "^3.1.14",

View file

@ -3,6 +3,9 @@
"version": "v0.8.8-rc3",
"description": "",
"packageManager": "npm@11.13.0",
"scarfSettings": {
"enabled": false
},
"workspaces": [
"api",
"client",

View file

@ -113,7 +113,7 @@
}
},
"500": {
"description": "Internal server error",
"description": "Internal server error. Errors normalized by the route use JSON; the final application error controller sends a text body with the text/html media type.",
"content": {
"application/json": {
"schema": {
@ -126,6 +126,15 @@
}
]
}
},
"text/html": {
"schema": {
"type": "string",
"enum": [
"An unknown error occurred.",
"Processing error in ErrorController."
]
}
}
}
}
@ -242,7 +251,7 @@
}
},
"500": {
"description": "Internal server error",
"description": "Internal server error. Errors normalized by the route use JSON; the final application error controller sends a text body with the text/html media type.",
"content": {
"application/json": {
"schema": {
@ -255,6 +264,15 @@
}
]
}
},
"text/html": {
"schema": {
"type": "string",
"enum": [
"An unknown error occurred.",
"Processing error in ErrorController."
]
}
}
}
}
@ -363,7 +381,7 @@
}
},
"500": {
"description": "Internal server error",
"description": "Internal server error. Errors normalized by the route use JSON; the final application error controller sends a text body with the text/html media type.",
"content": {
"application/json": {
"schema": {
@ -376,6 +394,15 @@
}
]
}
},
"text/html": {
"schema": {
"type": "string",
"enum": [
"An unknown error occurred.",
"Processing error in ErrorController."
]
}
}
}
}
@ -492,7 +519,7 @@
}
},
"500": {
"description": "Internal server error",
"description": "Internal server error. Errors normalized by the route use JSON; the final application error controller sends a text body with the text/html media type.",
"content": {
"application/json": {
"schema": {
@ -505,6 +532,15 @@
}
]
}
},
"text/html": {
"schema": {
"type": "string",
"enum": [
"An unknown error occurred.",
"Processing error in ErrorController."
]
}
}
}
}
@ -611,7 +647,7 @@
}
},
"500": {
"description": "Internal server error",
"description": "Internal server error. Errors normalized by the route use JSON; the final application error controller sends a text body with the text/html media type.",
"content": {
"application/json": {
"schema": {
@ -624,6 +660,15 @@
}
]
}
},
"text/html": {
"schema": {
"type": "string",
"enum": [
"An unknown error occurred.",
"Processing error in ErrorController."
]
}
}
}
}
@ -771,7 +816,7 @@
}
},
"500": {
"description": "Internal server error",
"description": "Internal server error. Errors normalized by the route use JSON; the final application error controller sends a text body with the text/html media type.",
"content": {
"application/json": {
"schema": {
@ -784,6 +829,15 @@
}
]
}
},
"text/html": {
"schema": {
"type": "string",
"enum": [
"An unknown error occurred.",
"Processing error in ErrorController."
]
}
}
}
}
@ -890,7 +944,7 @@
}
},
"500": {
"description": "Internal server error",
"description": "Internal server error. Errors normalized by the route use JSON; the final application error controller sends a text body with the text/html media type.",
"content": {
"application/json": {
"schema": {
@ -903,6 +957,15 @@
}
]
}
},
"text/html": {
"schema": {
"type": "string",
"enum": [
"An unknown error occurred.",
"Processing error in ErrorController."
]
}
}
}
}
@ -1020,7 +1083,7 @@
}
},
"500": {
"description": "Internal server error",
"description": "Internal server error. Errors normalized by the route use JSON; the final application error controller sends a text body with the text/html media type.",
"content": {
"application/json": {
"schema": {
@ -1033,6 +1096,15 @@
}
]
}
},
"text/html": {
"schema": {
"type": "string",
"enum": [
"An unknown error occurred.",
"Processing error in ErrorController."
]
}
}
}
}
@ -1151,7 +1223,7 @@
}
},
"500": {
"description": "Internal server error",
"description": "Internal server error. Errors normalized by the route use JSON; the final application error controller sends a text body with the text/html media type.",
"content": {
"application/json": {
"schema": {
@ -1164,6 +1236,15 @@
}
]
}
},
"text/html": {
"schema": {
"type": "string",
"enum": [
"An unknown error occurred.",
"Processing error in ErrorController."
]
}
}
}
}
@ -1272,7 +1353,7 @@
}
},
"500": {
"description": "Internal server error",
"description": "Internal server error. Errors normalized by the route use JSON; the final application error controller sends a text body with the text/html media type.",
"content": {
"application/json": {
"schema": {
@ -1285,6 +1366,15 @@
}
]
}
},
"text/html": {
"schema": {
"type": "string",
"enum": [
"An unknown error occurred.",
"Processing error in ErrorController."
]
}
}
}
}
@ -1408,7 +1498,7 @@
}
},
"500": {
"description": "Internal server error",
"description": "Internal server error. Errors normalized by the route use JSON; the final application error controller sends a text body with the text/html media type.",
"content": {
"application/json": {
"schema": {
@ -1421,6 +1511,15 @@
}
]
}
},
"text/html": {
"schema": {
"type": "string",
"enum": [
"An unknown error occurred.",
"Processing error in ErrorController."
]
}
}
}
}
@ -1529,7 +1628,7 @@
}
},
"500": {
"description": "Internal server error",
"description": "Internal server error. Errors normalized by the route use JSON; the final application error controller sends a text body with the text/html media type.",
"content": {
"application/json": {
"schema": {
@ -1542,6 +1641,15 @@
}
]
}
},
"text/html": {
"schema": {
"type": "string",
"enum": [
"An unknown error occurred.",
"Processing error in ErrorController."
]
}
}
}
}
@ -1659,7 +1767,7 @@
}
},
"500": {
"description": "Internal server error",
"description": "Internal server error. Errors normalized by the route use JSON; the final application error controller sends a text body with the text/html media type.",
"content": {
"application/json": {
"schema": {
@ -1672,6 +1780,15 @@
}
]
}
},
"text/html": {
"schema": {
"type": "string",
"enum": [
"An unknown error occurred.",
"Processing error in ErrorController."
]
}
}
}
}
@ -1807,7 +1924,7 @@
}
},
"500": {
"description": "Internal server error",
"description": "Internal server error. Errors normalized by the route use JSON; the final application error controller sends a text body with the text/html media type.",
"content": {
"application/json": {
"schema": {
@ -1820,6 +1937,15 @@
}
]
}
},
"text/html": {
"schema": {
"type": "string",
"enum": [
"An unknown error occurred.",
"Processing error in ErrorController."
]
}
}
}
}

View file

@ -0,0 +1,161 @@
const assert = require('node:assert/strict');
const fs = require('node:fs');
const http = require('node:http');
const path = require('node:path');
const vm = require('node:vm');
const express = require('express');
const swaggerUiDist = require('swagger-ui-dist');
const packageRoot = path.resolve(__dirname, '..');
const bundlePath = path.join(packageRoot, 'dist', 'index.cjs');
const specPath = path.join(packageRoot, 'dist', 'agents.openapi.json');
assert.ok(fs.existsSync(bundlePath), 'Build packages/api before running this smoke test');
assert.ok(fs.existsSync(specPath), 'The packages/api build must include agents.openapi.json');
const { createOpenApiRouter } = require(bundlePath);
const swaggerAssetsPath = swaggerUiDist.getAbsoluteFSPath();
const expectedSpec = fs.readFileSync(specPath);
function createApp(openapi) {
const app = express();
const getAppConfig = async (options) => {
assert.deepEqual(options, { baseOnly: true });
return openapi === undefined ? { config: {} } : { config: { openapi } };
};
for (const prefix of ['/api', '/chat/api']) {
app.use(prefix, createOpenApiRouter({ getAppConfig, swaggerAssetsPath }));
}
return app;
}
async function withServer(openapi, run) {
const server = http.createServer(createApp(openapi));
await new Promise((resolve, reject) => {
server.once('error', reject);
server.listen(0, '127.0.0.1', resolve);
});
try {
const address = server.address();
assert.ok(address && typeof address === 'object');
await run(`http://127.0.0.1:${address.port}`);
} finally {
await new Promise((resolve, reject) => {
server.close((error) => (error == null ? resolve() : reject(error)));
});
}
}
async function assertNotFound(baseUrl, pathname) {
const response = await fetch(baseUrl + pathname);
assert.equal(response.status, 404, `${pathname} should be disabled`);
assert.deepEqual(await response.json(), { message: 'Not Found' });
}
function runInitializer(html, pathname) {
const inlineScript = html.match(/<script>([\s\S]*?)<\/script>/)?.[1];
assert.ok(inlineScript, 'Docs HTML should include an inline initializer');
let onDOMContentLoaded;
let swaggerOptions;
const appended = [];
const document = {
createElement(tagName) {
return { tagName };
},
head: {
appendChild(element) {
appended.push(element);
},
},
body: {
appendChild(element) {
appended.push(element);
element.onload?.();
},
},
};
const window = {
addEventListener(eventName, listener) {
assert.equal(eventName, 'DOMContentLoaded');
onDOMContentLoaded = listener;
},
};
const SwaggerUIBundle = (options) => {
swaggerOptions = options;
return { options };
};
vm.runInNewContext(inlineScript, {
document,
location: { pathname },
SwaggerUIBundle,
window,
});
assert.equal(typeof onDOMContentLoaded, 'function');
onDOMContentLoaded();
return { appended, swaggerOptions };
}
async function assertEnabled(baseUrl, prefix) {
const specResponse = await fetch(`${baseUrl}${prefix}/openapi.json`);
assert.equal(specResponse.status, 200);
assert.match(specResponse.headers.get('content-type') ?? '', /^application\/json\b/);
assert.deepEqual(Buffer.from(await specResponse.arrayBuffer()), expectedSpec);
for (const suffix of ['/docs', '/docs/']) {
const pathname = prefix + suffix;
const docsResponse = await fetch(baseUrl + pathname);
assert.equal(docsResponse.status, 200);
assert.match(docsResponse.headers.get('content-type') ?? '', /^text\/html\b/);
const { appended, swaggerOptions } = runInitializer(await docsResponse.text(), pathname);
assert.equal(appended.length, 2);
assert.deepEqual(
{ rel: appended[0].rel, href: appended[0].href },
{ rel: 'stylesheet', href: `${prefix}/docs/assets/swagger-ui.css` },
);
assert.equal(appended[1].src, `${prefix}/docs/assets/swagger-ui-bundle.js`);
assert.deepEqual(Object.keys(swaggerOptions).sort(), ['dom_id', 'url', 'validatorUrl']);
assert.equal(swaggerOptions.url, `${prefix}/openapi.json`);
assert.equal(swaggerOptions.dom_id, '#swagger-ui');
assert.equal(swaggerOptions.validatorUrl, null);
}
for (const asset of ['swagger-ui.css', 'swagger-ui-bundle.js']) {
const assetResponse = await fetch(`${baseUrl}${prefix}/docs/assets/${asset}`);
assert.equal(assetResponse.status, 200);
assert.deepEqual(
Buffer.from(await assetResponse.arrayBuffer()),
fs.readFileSync(path.join(swaggerAssetsPath, asset)),
);
}
}
async function main() {
for (const openapi of [undefined, { enabled: false }]) {
await withServer(openapi, async (baseUrl) => {
for (const prefix of ['/api', '/chat/api']) {
await assertNotFound(baseUrl, `${prefix}/openapi.json`);
await assertNotFound(baseUrl, `${prefix}/docs`);
await assertNotFound(baseUrl, `${prefix}/docs/assets/swagger-ui.css`);
}
});
}
await withServer({ enabled: true }, async (baseUrl) => {
for (const prefix of ['/api', '/chat/api']) {
await assertEnabled(baseUrl, prefix);
}
});
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});

View file

@ -47,6 +47,7 @@
"b:build": "bun run b:clean && bun run tsdown && bun run openapi:copy",
"b:build:dev": "bun run b:clean && bun run tsdown && bun run openapi:copy",
"openapi:generate": "cross-env TS_NODE_PROJECT=tsconfig.openapi.json ts-node -r tsconfig-paths/register src/openapi/generate.ts --write",
"openapi:test": "node openapi/router.smoke.cjs",
"openapi:check": "cross-env TS_NODE_PROJECT=tsconfig.openapi.json ts-node -r tsconfig-paths/register src/openapi/generate.ts --check",
"start:everything-sse": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/examples/everything/sse.ts",
"start:everything": "node -r dotenv/config --loader ./tsconfig-paths-bootstrap.mjs --experimental-specifier-resolution=node ./src/demo/everything.ts",

View file

@ -23,6 +23,8 @@ export type ResponseContract = {
schema?: ZodTypeAny;
/** A hand-written media-type object, used when there is no Zod schema. */
content?: RawContent;
/** Hand-written media types added alongside a generated JSON schema. */
additionalContent?: RawContent;
};
export type EndpointContract = {
@ -69,7 +71,10 @@ function buildResponses(responses: ResponseContract[]): Record<string, unknown>
if (response.schema) {
result[response.status] = {
description: response.description,
content: { 'application/json': { schema: response.schema } },
content: {
'application/json': { schema: response.schema },
...response.additionalContent,
},
};
continue;
}

View file

@ -13,6 +13,7 @@ import {
import {
errorMessageResponseSchema,
accountDeletionResponseSchema,
genericServerErrorContent,
messageResponseSchema,
jsonParseErrorSchema,
} from './errors';
@ -78,7 +79,6 @@ const agentFileDeletedSchema = z.object({
id: z.string(),
deleted: z.literal(true),
});
export const agentComponentSchemas: Record<string, ZodTypeAny> = {
AgentCreateRequest: agentCreateRequestSchema,
AgentUpdateRequest: agentUpdateRequestSchema,
@ -115,8 +115,10 @@ const errorResponses = [
},
{
status: 500,
description: 'Internal server error',
description:
'Internal server error. Errors normalized by the route use JSON; the final application error controller sends a text body with the text/html media type.',
schema: z.union([agentManagementErrorSchema, errorMessageResponseSchema]),
additionalContent: genericServerErrorContent,
},
];

View file

@ -1,4 +1,15 @@
import { z } from 'zod';
import type { RawContent } from './adapter';
/** String fallbacks that Express serves as `text/html` from the final application error controller. */
export const genericServerErrorContent: RawContent = {
'text/html': {
schema: {
type: 'string',
enum: ['An unknown error occurred.', 'Processing error in ErrorController.'],
},
},
};
/**
* The flat `{ error }` envelope the auth middleware sends for 401 (`{ error: 'Unauthorized' }`)

View file

@ -38,7 +38,11 @@ const DOCS_HTML = `<!DOCTYPE html>
var script = document.createElement('script');
script.src = apiBase + '/docs/assets/swagger-ui-bundle.js';
script.onload = function () {
window.ui = SwaggerUIBundle({ url: apiBase + '/openapi.json', dom_id: '#swagger-ui' });
window.ui = SwaggerUIBundle({
url: apiBase + '/openapi.json',
dom_id: '#swagger-ui',
validatorUrl: null,
});
};
document.body.appendChild(script);
});

View file

@ -13,6 +13,7 @@ import {
import {
errorMessageResponseSchema,
accountDeletionResponseSchema,
genericServerErrorContent,
messageResponseSchema,
jsonParseErrorSchema,
} from './errors';
@ -37,7 +38,6 @@ const skillFileUpdatedSchema = z.object({
relativePath: z.string(),
bytes: z.number().int().nonnegative(),
});
export const skillComponentSchemas: Record<string, ZodTypeAny> = {
SkillFrontmatterValue: skillFrontmatterValueSchema,
Skill: skillManagementResponseSchema,
@ -74,8 +74,10 @@ const errorResponses = [
},
{
status: 500,
description: 'Internal server error',
description:
'Internal server error. Errors normalized by the route use JSON; the final application error controller sends a text body with the text/html media type.',
schema: z.union([agentManagementErrorSchema, errorMessageResponseSchema]),
additionalContent: genericServerErrorContent,
},
];