@kubb/adapter-oas 5.19.0 → 5.19.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -7,10 +7,10 @@ var __name = (target, value) => __defProp(target, "name", {
7
7
  });
8
8
  let _kubb_core = require("@kubb/core");
9
9
  let _kubb_kit = require("@kubb/kit");
10
+ let node_fs_promises = require("node:fs/promises");
10
11
  let node_path = require("node:path");
11
12
  let node_url = require("node:url");
12
13
  let node_fs = require("node:fs");
13
- let node_fs_promises = require("node:fs/promises");
14
14
  let _scalar_openapi_upgrader = require("@scalar/openapi-upgrader");
15
15
  let api_ref_bundler = require("api-ref-bundler");
16
16
  let js_yaml = require("js-yaml");
@@ -21,7 +21,7 @@ var compatibility = {
21
21
  "node": ">=22.22"
22
22
  };
23
23
  // package.json
24
- var version = "5.19.0";
24
+ var version = "5.19.2";
25
25
  // src/constants.ts
26
26
  /**
27
27
  * Default parser options applied when no explicit options are provided.
@@ -405,6 +405,27 @@ async function read(path) {
405
405
  if (runtime.isBun) return Bun.file(path).text();
406
406
  return new Promise((resolvePromise, reject) => (0, node_fs.readFile)(path, { encoding: "utf8" }, (error, data) => error ? reject(error) : resolvePromise(data)));
407
407
  }
408
+ /**
409
+ * Resolves to `true` when `path` is `parent` itself or nested inside it. Both sides are resolved
410
+ * to absolute paths first, so relative and `..`-containing inputs compare correctly.
411
+ *
412
+ * Guards a destructive or an out-of-tree operation: before wiping an output directory, check that
413
+ * it does not contain the project root, and before loading a path a caller supplied, check that it
414
+ * did not escape the directory it is allowed to read from.
415
+ *
416
+ * @example
417
+ * isPathInside('./src/gen', '.') // true — nested inside the root
418
+ * isPathInside('.', '.') // true — the same directory counts as inside
419
+ * isPathInside('.', './src/gen') // false — the root is not inside its own output
420
+ * isPathInside('../other', '.') // false — escapes the root
421
+ */
422
+ function isPathInside(path, parent) {
423
+ const resolvedPath = (0, node_path.resolve)(path);
424
+ const resolvedParent = (0, node_path.resolve)(parent);
425
+ if (resolvedPath === resolvedParent) return true;
426
+ const rel = (0, node_path.relative)(resolvedParent, resolvedPath);
427
+ return rel !== "" && !rel.startsWith("..") && !(0, node_path.isAbsolute)(rel);
428
+ }
408
429
  // src/oas.ts
409
430
  /**
410
431
  * Returns `true` when a schema should be treated as nullable.
@@ -1097,6 +1118,16 @@ function getBaseUri(pathOrUrl, root) {
1097
1118
  }
1098
1119
  }
1099
1120
  /**
1121
+ * Whether `filePath` is inside one of `folders`. Links are followed first, so a link inside a
1122
+ * folder cannot point outside it.
1123
+ */
1124
+ async function isInsideFolders(filePath, folders) {
1125
+ const real = (item) => (0, node_fs_promises.realpath)((0, node_path.resolve)(item)).catch(() => (0, node_path.resolve)(item));
1126
+ const target = await real(filePath);
1127
+ const realFolders = await Promise.all(folders.map(real));
1128
+ return [...folders, ...realFolders].some((folder) => isPathInside(target, folder));
1129
+ }
1130
+ /**
1100
1131
  * Bundles a multi-file OpenAPI document into a single document via `api-ref-bundler`.
1101
1132
  *
1102
1133
  * External file schemas are hoisted into named `components.schemas` entries, so a property
@@ -1113,6 +1144,7 @@ function getBaseUri(pathOrUrl, root) {
1113
1144
  * against the OpenAPI 3.2 `$self` when the document sets one. Every other file or URL read,
1114
1145
  * including one that fails, lands in `sources`. A `$ref` that cannot be read reports
1115
1146
  * `KUBB_REF_NOT_FOUND` at the key that holds it, as a warning when it sits inside an `x-` extension.
1147
+ * So does any local file from a URL input, and a local file outside every `fileRefs` folder.
1116
1148
  *
1117
1149
  * @example Local file
1118
1150
  * `const document = await bundleDocument('./openapi.yaml')`
@@ -1120,14 +1152,20 @@ function getBaseUri(pathOrUrl, root) {
1120
1152
  * @example Remote URL
1121
1153
  * `const document = await bundleDocument('https://example.com/openapi.yaml')`
1122
1154
  */
1123
- async function bundleDocument(pathOrUrl, { document, sources = [] } = {}) {
1155
+ async function bundleDocument(pathOrUrl, { document, sources = [], fileRefs } = {}) {
1124
1156
  const cache = memo.create();
1125
1157
  const toKey = (sourcePath) => urlRegExp.test(sourcePath) ? new URL(sourcePath).href : sourcePath;
1158
+ const folders = urlRegExp.test(pathOrUrl) ? [] : fileRefs;
1159
+ const refused = /* @__PURE__ */ new Set();
1126
1160
  let entry = pathOrUrl;
1127
1161
  let entryDocument = document;
1128
- const resolver = (sourcePath) => {
1129
- if (entryDocument !== void 0 && toKey(sourcePath) === toKey(entry)) return Promise.resolve(entryDocument);
1162
+ const resolver = async (sourcePath) => {
1163
+ if (entryDocument !== void 0 && toKey(sourcePath) === toKey(entry)) return entryDocument;
1130
1164
  const key = toKey(sourcePath);
1165
+ if (key !== toKey(pathOrUrl) && !urlRegExp.test(sourcePath) && folders && !await isInsideFolders(sourcePath, folders)) {
1166
+ refused.add(sourcePath);
1167
+ throw new Error(`Refused ${sourcePath}`);
1168
+ }
1131
1169
  return memo(cache, key, () => {
1132
1170
  sources.push(key);
1133
1171
  return resolveSource(sourcePath, { remember: key === toKey(pathOrUrl) });
@@ -1143,11 +1181,12 @@ async function bundleDocument(pathOrUrl, { document, sources = [] } = {}) {
1143
1181
  entryDocument = root;
1144
1182
  return await (0, api_ref_bundler.bundle)(entry, resolver, { hooks: { onError: (message, { path, state }) => {
1145
1183
  const pointer = toKey(state.baseFile) === toKey(entry) ? `#/${path.map((token) => escapePointerToken(String(token))).join("/")}` : void 0;
1184
+ const refusedPath = [...refused].find((sourcePath) => message.includes(sourcePath));
1146
1185
  const diagnostic = {
1147
1186
  code: _kubb_kit.Diagnostics.code.refNotFound,
1148
1187
  severity: isExtensionPath(path) ? "warning" : "error",
1149
- message: `Could not bundle an external \`$ref\`. ${message}.`,
1150
- help: "Check that the file or URL the `$ref` points at exists and is readable, or fix the `$ref`.",
1188
+ message: refusedPath ? `Refused an external \`$ref\` to the local file ${refusedPath}.` : `Could not bundle an external \`$ref\`. ${message}.`,
1189
+ help: refusedPath ? folders?.length ? "This run only reads local files inside the folders its host allows, such as the project. Move the file there or inline the schema. On your own agent, `--allow-file-refs` lifts the limit." : "This input reads no local file. Inline the schema, or serve the file from a URL." : "Check that the file or URL the `$ref` points at exists and is readable, or fix the `$ref`.",
1151
1190
  ...pointer && { location: {
1152
1191
  kind: "schema",
1153
1192
  pointer
@@ -1174,7 +1213,7 @@ const inlineInputName = "<inline input>";
1174
1213
  * const document = await parseFromConfig({ type: 'data', data: '{"openapi":"3.0.0",...}' })
1175
1214
  * ```
1176
1215
  */
1177
- async function parseFromConfig(source, sources = []) {
1216
+ async function parseFromConfig(source, sources = [], { fileRefs } = {}) {
1178
1217
  const raw = await (async () => {
1179
1218
  if (source.type === "data") {
1180
1219
  const data = typeof source.data === "string" ? parseYaml(source.data, {
@@ -1184,14 +1223,18 @@ async function parseFromConfig(source, sources = []) {
1184
1223
  const isObject = Boolean(data) && typeof data === "object";
1185
1224
  if (source.root && isObject) return bundleDocument((0, node_path.join)(source.root, inlineInputName), {
1186
1225
  document: data,
1187
- sources
1226
+ sources,
1227
+ fileRefs
1188
1228
  });
1189
1229
  const scan = resolveTargets(data);
1190
1230
  if (isObject) scans.set(data, scan);
1191
1231
  return data;
1192
1232
  }
1193
1233
  await assertInputExists(source.path);
1194
- return bundleDocument(source.path, { sources });
1234
+ return bundleDocument(source.path, {
1235
+ sources,
1236
+ fileRefs
1237
+ });
1195
1238
  })();
1196
1239
  if (raw && typeof raw === "object") {
1197
1240
  const document = raw;
@@ -4045,7 +4088,7 @@ const adapterOas = (0, _kubb_core.defineExtension)({
4045
4088
  async settle() {
4046
4089
  await Promise.all(pendingValidations.splice(0));
4047
4090
  },
4048
- async parse(source, { signal } = {}) {
4091
+ async parse(source, { signal, fileRefs } = {}) {
4049
4092
  signal?.throwIfAborted();
4050
4093
  const cached = inputCache.get(source);
4051
4094
  if (cached) {
@@ -4055,7 +4098,7 @@ const adapterOas = (0, _kubb_core.defineExtension)({
4055
4098
  const read = [];
4056
4099
  sources = read;
4057
4100
  const promise = (async () => {
4058
- const document = await parseFromConfig(source, read);
4101
+ const document = await parseFromConfig(source, read, { fileRefs });
4059
4102
  signal?.throwIfAborted();
4060
4103
  assertDocument(document);
4061
4104
  if (validate) pendingValidations.push(validateDocumentInWorker(document));