All files / lib/prepare spec.ts

100% Statements 468/468
86.15% Branches 112/130
100% Functions 19/19
100% Lines 468/468

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 4691x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 217x 2x 2x 217x 217x 2x 2x 217x 22x 22x 217x 217x 1x 1x 1x 1x 1x 1x 191x 191x 191x 4x 4x 191x 9x 9x 191x 191x 1x 1x 1x 1x 1x 1x 1x 9x 9x 18x 6x 6x 6x 6x 18x 9x 9x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 197x 2x 2x 197x 195x 195x 195x 195x 195x 197x 1x 1x 1x 197x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 44x 44x 44x 43x 44x 1x 1x 44x 1x 44x 44x 44x 44x 43x 44x 1x 1x 44x 1x 23x 23x 23x 23x 22x 22x 22x 23x 1x 1x 23x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 116x 111x 5x 116x 111x 116x 5x 2x 3x 5x 116x 116x 1x 1x 1x 1x 1x 1x 1x 1x 24x 24x 2x 2x 24x 22x 22x 23x 23x 23x 2x 2x 23x 22x 24x 1x 1x 1x 1x 1x 1x 1x 1x 259x 259x 49x 49x 259x 126x 126x 126x 126x 126x 210x 259x 1x 1x 1x 1x 1x 1x 1284x 1284x 1284x 1x 1x 1x 1x 1x 1x 26x 26x 26x 26x 26x 26x 1x 1x 1x 1x 1x 1x 1x 1x 1x 26x 1x 1x 1x 1x 1x 1x 25x 25x 25x 1x 1x 1x 1x 1x 1x 1x 1x 25x 25x 1x 1x 1x 1x 1x 1x 24x 24x 24x 24x 24x 24x 105x 105x 24x 24x 1x 1x 1x 1x 1x 1x 1x 235x 235x 235x 171x 171x 235x 170x 170x 170x 170x 170x 170x 170x 170x 170x 170x 235x 235x 1x 1x 1x 1x 1x 1x 235x 235x 212x 212x 235x 235x 235x 235x 235x 235x 235x 235x 235x 235x 235x 235x 1x 22x 235x 235x 1x 1x 1x 1x 1x 1x 235x 235x 235x 278x 278x 235x 235x 1x 1x 1x 1x 1x 1x 235x 235x 235x 235x 235x 235x 235x 235x 235x 235x 235x 235x 235x 235x 235x 235x 235x 235x 235x 235x 235x 235x 235x 235x 1x 1x 1x 1x 1x 1x 24x 24x 24x 24x 24x 24x 192x 192x 1x 191x 192x 1536x 1536x 235x 235x 1536x 192x 24x 24x 1x 1x 1x 1x 1x 1x 24x 24x 3x 3x 24x 84x 84x 21x 24x 1x 1x 1x 1x 1x 1x 1x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x  
"use strict";
/**
 * Load an OpenAPI 3.x document and extract the operations, security schemes
 * and documentation used for indexing and for the runtime request broker.
 *
 * External `$ref`s are resolved from the local filesystem only: HTTP
 * resolution is disabled so builds never contact remote hosts.
 *
 * @module prepare/spec
 */
import SwaggerParser from "@apidevtools/swagger-parser";
import { sample } from "openapi-sampler";
 
import { OagMcpError } from "../errors.js";
import { trimTrailingSlashes } from "../util/path.js";
import type {
  ParameterInfo,
  SecurityRequirement,
  SecuritySchemeInfo,
  SpecOperation,
  SpecSummary,
} from "../types.js";
 
export const HTTP_METHODS = [
  "get",
  "put",
  "post",
  "delete",
  "options",
  "head",
  "patch",
  "trace",
] as const;
 
type Json = Record<string, unknown>;
 
/** Composite schema keywords and how their parts are joined. */
const COMPOSITES: ReadonlyArray<[string, string]> = [
  ["oneOf", " | "],
  ["anyOf", " | "],
  ["allOf", " & "],
];
 
/**
 * Convert a schema to a compact human description, e.g. "integer(int64)".
 *
 * @param {Object} schema - OpenAPI schema
 * @param {Number} [depth] - recursion depth
 * @return {String} description
 */
export function describeSchema(schema: unknown, depth = 0): string {
  if (!schema || typeof schema !== "object") {
    return "any";
  }
  const s = schema as Json;
  if (depth > 2) {
    return String(s.type ?? "object");
  }
  if (Array.isArray(s.enum)) {
    return s.enum.map((v) => JSON.stringify(v)).join(" | ");
  }
  return _describeTyped(s, depth) ?? _describeComposite(s, depth);
}
 
/**
 * Describe a schema by its `type` (and `format`), or undefined if it has none.
 *
 * @private
 */
function _describeTyped(s: Json, depth: number): string | undefined {
  const type = Array.isArray(s.type) ? s.type.join("|") : s.type;
  if (type === "array") {
    return `${describeSchema(s.items, depth + 1)}[]`;
  }
  if (!type) {
    return undefined;
  }
  return s.format ? `${type}(${s.format})` : String(type);
}
 
/**
 * Describe a schema without a `type`: its `oneOf`, `anyOf` or `allOf`
 * parts, or "object" when it has properties.
 *
 * @private
 */
function _describeComposite(s: Json, depth: number): string {
  for (const [keyword, joiner] of COMPOSITES) {
    if (Array.isArray(s[keyword])) {
      return (s[keyword] as unknown[])
        .map((x) => describeSchema(x, depth + 1))
        .join(joiner);
    }
  }
  return s.properties ? "object" : "any";
}
 
/**
 * Pick an example value for a schema, using openapi-sampler: the schema's
 * own `example`, `examples`, `default` or first `enum` value where present,
 * otherwise a value generated from its type and format (`oneOf`/`anyOf`,
 * `allOf` and recursive schemas included). Only required properties are
 * included, and `readOnly` properties are left out because the examples are
 * for requests.
 *
 * @param {Object} schema - dereferenced OpenAPI schema
 * @return {*} example value, or undefined when none can be produced
 */
export function exampleForSchema(schema: unknown): unknown {
  if (!schema || typeof schema !== "object") {
    return undefined;
  }
  try {
    return sample(schema as Parameters<typeof sample>[0], {
      skipReadOnly: true,
      skipNonRequired: true,
      quiet: true,
    });
  } catch {
    // An example is a convenience; never fail preparation over one.
    return undefined;
  }
}
 
/** Describes the parts of one security scheme type and whether it is supported. */
type SchemeDescriber = (info: SecuritySchemeInfo, scheme: Json) => void;
 
/** Security scheme types oag-mcp cannot satisfy, and why. */
const UNSUPPORTED_SCHEME_TYPES: Readonly<Record<string, string>> = {
  openIdConnect:
    "openIdConnect is not supported for upstream calls (interactive login is out of scope)",
  mutualTLS: "mutualTLS is not supported for upstream calls",
};
 
/** The describer of each supported security scheme type. */
const SCHEME_DESCRIBERS: Readonly<Record<string, SchemeDescriber>> = {
  apiKey: (info, scheme) => {
    info.in = scheme.in as SecuritySchemeInfo["in"];
    info.paramName = String(scheme.name ?? "");
    if (info.in === "header" || info.in === "query") {
      info.supported = true;
    } else {
      info.unsupportedReason = `apiKey in "${String(scheme.in)}" is not supported (header and query are)`;
    }
  },
  http: (info, scheme) => {
    info.scheme = String(scheme.scheme ?? "").toLowerCase();
    info.bearerFormat =
      typeof scheme.bearerFormat === "string" ? scheme.bearerFormat : undefined;
    if (info.scheme === "basic" || info.scheme === "bearer") {
      info.supported = true;
    } else {
      info.unsupportedReason = `HTTP "${info.scheme}" authentication is not supported (basic and bearer are)`;
    }
  },
  oauth2: (info, scheme) => {
    const flows = (scheme.flows ?? {}) as Json;
    const cc = flows.clientCredentials as Json | undefined;
    info.flows = Object.keys(flows);
    if (cc && typeof cc.tokenUrl === "string") {
      info.supported = true;
      info.tokenUrl = cc.tokenUrl;
      info.scopes = Object.keys((cc.scopes ?? {}) as Json);
    } else {
      info.unsupportedReason = `OAuth2 flows [${info.flows.join(", ")}] are not supported; only clientCredentials is (interactive login is out of scope)`;
    }
  },
};
 
/**
 * Describe a security scheme and whether oag-mcp supports it for upstream
 * calls.
 *
 * @param {String} name - scheme name
 * @param {Object} scheme - OpenAPI security scheme
 * @return {Object} scheme info
 */
export function describeSecurityScheme(
  name: string,
  scheme: Json,
): SecuritySchemeInfo {
  const type = String(scheme.type ?? "");
  const info: SecuritySchemeInfo = {
    name,
    type: type as SecuritySchemeInfo["type"],
    supported: false,
    description:
      typeof scheme.description === "string" ? scheme.description : undefined,
  };
  const describe = Object.hasOwn(SCHEME_DESCRIBERS, type)
    ? SCHEME_DESCRIBERS[type]
    : undefined;
  if (describe) {
    describe(info, scheme);
  } else {
    info.unsupportedReason = Object.hasOwn(UNSUPPORTED_SCHEME_TYPES, type)
      ? UNSUPPORTED_SCHEME_TYPES[type]
      : `Unknown security scheme type "${type}"`;
  }
  return info;
}
 
/**
 * Resolve the first server URL, substituting variable defaults.
 *
 * @param {Array} servers - OpenAPI servers
 * @return {String|undefined} URL
 * @private
 */
function _serverUrls(servers: unknown): string[] {
  if (!Array.isArray(servers)) {
    return [];
  }
  return servers
    .filter((s) => s && typeof s.url === "string")
    .map((s) => {
      let url = s.url as string;
      const vars = (s.variables ?? {}) as Record<string, { default?: string }>;
      for (const [k, v] of Object.entries(vars)) {
        url = url.split(`{${k}}`).join(String(v.default ?? ""));
      }
      return trimTrailingSlashes(url);
    });
}
 
/**
 * Normalise a security requirement list.
 *
 * @param {Array} security - OpenAPI security requirement objects
 * @return {Array} requirements
 * @private
 */
function _security(security: unknown): SecurityRequirement[] | undefined {
  if (!Array.isArray(security)) {
    return undefined;
  }
  return security.map((req) => {
    const out: SecurityRequirement = {};
    for (const [k, v] of Object.entries((req ?? {}) as Json)) {
      out[k] = Array.isArray(v) ? v.map(String) : [];
    }
    return out;
  });
}
 
/**
 * A value if it is a string, otherwise undefined.
 *
 * @private
 */
function _str(v: unknown): string | undefined {
  return typeof v === "string" ? v : undefined;
}
 
/**
 * Parse and validate the document, resolving `$ref`s from local files only.
 *
 * @private
 */
async function _parse(specPath: string): Promise<Json> {
  try {
    return (await SwaggerParser.validate(specPath, {
      resolve: { http: false },
    })) as unknown as Json;
  } catch (err) {
    throw new OagMcpError(
      "SPEC_INVALID",
      `OpenAPI document ${specPath} could not be loaded: ${(err as Error).message}`,
      {
        hint: "Check the document is valid OpenAPI 3.0/3.1. Remote $ref URLs are not fetched; vendor them as local files.",
        cause: err,
      },
    );
  }
}
 
/**
 * The document's OpenAPI version, which must be 3.0.x or 3.1.x.
 *
 * @private
 */
function _version(api: Json): string {
  const version = String(api.openapi ?? api.swagger ?? "");
  if (!/^3\.[01]\./.test(version)) {
    throw new OagMcpError(
      "SPEC_VERSION_UNSUPPORTED",
      `OpenAPI version "${version}" is not supported`,
      {
        hint: "oag-mcp supports OpenAPI 3.0.x and 3.1.x documents. Convert Swagger 2.0 documents first (e.g. with swagger2openapi).",
      },
    );
  }
  return version;
}
 
/**
 * The document's security schemes, described.
 *
 * @private
 */
function _securitySchemes(api: Json): Record<string, SecuritySchemeInfo> {
  const components = (api.components ?? {}) as Json;
  const schemes: Record<string, SecuritySchemeInfo> = {};
  for (const [name, scheme] of Object.entries(
    (components.securitySchemes ?? {}) as Json,
  )) {
    schemes[name] = describeSecurityScheme(name, scheme as Json);
  }
  return schemes;
}
 
/**
 * An operation's parameters: the path item's, overridden by the
 * operation's own with the same location and name.
 *
 * @private
 */
function _parameters(shared: Json[], op: Json): ParameterInfo[] {
  const params = new Map<string, Json>();
  for (const prm of [...shared, ...((op.parameters as Json[]) ?? [])]) {
    params.set(`${prm.in}:${prm.name}`, prm);
  }
  return [...params.values()].map((prm) => {
    const schema = (prm.schema ?? {}) as Json;
    return {
      name: String(prm.name),
      in: String(prm.in) as ParameterInfo["in"],
      required: Boolean(prm.required),
      description: _str(prm.description),
      schemaType: describeSchema(schema),
      example:
        prm.example !== undefined ? prm.example : exampleForSchema(schema),
    };
  });
}
 
/**
 * An operation's request body, described by its first media type.
 *
 * @private
 */
function _requestBody(op: Json): SpecOperation["requestBody"] {
  if (!op.requestBody || typeof op.requestBody !== "object") {
    return undefined;
  }
  const rb = op.requestBody as Json;
  const content = (rb.content ?? {}) as Json;
  const contentTypes = Object.keys(content);
  const firstType = contentTypes[0];
  const media = (firstType ? content[firstType] : {}) as Json;
  return {
    required: Boolean(rb.required),
    contentTypes,
    description: _str(rb.description),
    schemaType: describeSchema(media.schema),
    example:
      media.example !== undefined
        ? media.example
        : exampleForSchema(media.schema),
  };
}
 
/**
 * An operation's response descriptions by status code.
 *
 * @private
 */
function _responses(op: Json): Record<string, string> {
  const responses: Record<string, string> = {};
  for (const [code, r] of Object.entries((op.responses ?? {}) as Json)) {
    responses[code] = _str((r as Json)?.description) ?? "";
  }
  return responses;
}
 
/**
 * Summarise one operation.
 *
 * @private
 */
function _operation(
  method: string,
  path: string,
  op: Json,
  shared: Json[],
  globalSecurity: SecurityRequirement[],
): SpecOperation {
  const explicit = _security(op.security);
  return {
    key: `${method.toUpperCase()} ${path}`,
    method: method.toUpperCase(),
    path,
    operationId: _str(op.operationId),
    tags: Array.isArray(op.tags) ? op.tags.map(String) : [],
    summary: _str(op.summary),
    description: _str(op.description),
    deprecated: Boolean(op.deprecated),
    parameters: _parameters(shared, op),
    requestBody: _requestBody(op),
    responses: _responses(op),
    security: explicit ?? globalSecurity,
    securityIsOverride: explicit !== undefined,
  };
}
 
/**
 * Every operation of every path, in document order.
 *
 * @private
 */
function _operations(
  api: Json,
  globalSecurity: SecurityRequirement[],
): SpecOperation[] {
  const operations: SpecOperation[] = [];
  for (const [path, item] of Object.entries((api.paths ?? {}) as Json)) {
    const pathItem = (item ?? {}) as Json;
    const shared = Array.isArray(pathItem.parameters)
      ? (pathItem.parameters as Json[])
      : [];
    for (const method of HTTP_METHODS) {
      const op = pathItem[method] as Json | undefined;
      if (op) {
        operations.push(_operation(method, path, op, shared, globalSecurity));
      }
    }
  }
  return operations;
}
 
/**
 * The document's tags.
 *
 * @private
 */
function _tags(api: Json): SpecSummary["tags"] {
  if (!Array.isArray(api.tags)) {
    return [];
  }
  return (api.tags as Json[]).map((t) => ({
    name: String(t.name),
    description: _str(t.description),
  }));
}
 
/**
 * Load, validate and summarise an OpenAPI document.
 *
 * @param {String} specPath - path to the OpenAPI YAML/JSON document
 * @return {Promise} spec summary
 */
export async function loadSpec(specPath: string): Promise<SpecSummary> {
  const api = await _parse(specPath);
  const version = _version(api);
  const info = (api.info ?? {}) as Json;
  const globalSecurity = _security(api.security) ?? [];
  return {
    openapiVersion: version,
    title: String(info.title ?? "API"),
    apiVersion: String(info.version ?? ""),
    description: _str(info.description),
    servers: _serverUrls(api.servers),
    tags: _tags(api),
    securitySchemes: _securitySchemes(api),
    globalSecurity,
    operations: _operations(api, globalSecurity),
  };
}