@kubb/studio 5.19.0 → 5.19.1

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/README.md CHANGED
@@ -113,8 +113,9 @@ Every permission is off by default, and each covers one trust boundary:
113
113
  | `allowConfigEdit` | Studio may change plugin options in `kubb.config.ts`. |
114
114
  | `allowRead` | Studio may read existing output files and the files a generation produced. |
115
115
  | `allowReadAst` | Studio may read back the parsed spec (the Kubb AST). |
116
+ | `allowFileRefs` | A `$ref` in the spec may read a local file outside the project. |
116
117
 
117
- A sandbox never writes or edits config, and always allows reads.
118
+ A sandbox never writes or edits config. A sandbox the host declares with `agentType: 'sandbox'` or `'global'` always allows reads.
118
119
 
119
120
  ## Pairing
120
121
 
package/dist/index.cjs CHANGED
@@ -20,7 +20,7 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
20
20
  value: mod,
21
21
  enumerable: true
22
22
  }) : target, mod));
23
- const require_protocol = require("./protocol-B4wWGPon.cjs");
23
+ const require_protocol = require("./protocol-CmX5XTPc.cjs");
24
24
  let node_crypto = require("node:crypto");
25
25
  let node_fs = require("node:fs");
26
26
  let node_fs_promises = require("node:fs/promises");
@@ -251,7 +251,7 @@ function isPathInside(path, parent) {
251
251
  return rel !== "" && !rel.startsWith("..") && !(0, node_path.isAbsolute)(rel);
252
252
  }
253
253
  // package.json
254
- var version = "5.19.0";
254
+ var version = "5.19.1";
255
255
  // ../../internals/shared/src/constants.ts
256
256
  /**
257
257
  * Extensions `kubb` ships at its own version, so they count as installed without being a direct
@@ -388,6 +388,22 @@ function isOutputValue({ key, value }) {
388
388
  function pickOutput(output) {
389
389
  return Object.fromEntries(Object.entries(output).filter(([key]) => isOutputKey(key)));
390
390
  }
391
+ /**
392
+ * Returns the first `output.path` in `value`, at any depth (`override` entries included), that is
393
+ * absolute or climbs out of the folder it resolves against.
394
+ */
395
+ function findEscapingOutputPath(value) {
396
+ if (!Array.isArray(value) && !isPlainObject(value)) return void 0;
397
+ const output = isPlainObject(value) ? value.output : void 0;
398
+ if (isPlainObject(output) && typeof output.path === "string") {
399
+ const normalized = node_path.default.posix.normalize(output.path.replaceAll("\\", "/"));
400
+ if (node_path.default.posix.isAbsolute(normalized) || /^[a-z]:/i.test(output.path) || normalized === ".." || normalized.startsWith("../")) return output.path;
401
+ }
402
+ for (const entry of Object.values(value)) {
403
+ const found = findEscapingOutputPath(entry);
404
+ if (found !== void 0) return found;
405
+ }
406
+ }
391
407
  // ../../internals/shared/src/configFile/text.ts
392
408
  /**
393
409
  * A valid JavaScript identifier, so an import name can only ever print as `import { name } from`,
@@ -483,13 +499,15 @@ function isNonEmptyString(value) {
483
499
  }
484
500
  /** Edits cross the wire, so their shape is checked before anything reads them. */
485
501
  function validateEdit(edit) {
486
- const { operation, plugin, config, path, kind, input } = typeof edit === "object" && edit !== null ? edit : {};
502
+ const { operation, plugin, config, path, kind, input, value, options } = typeof edit === "object" && edit !== null ? edit : {};
487
503
  if (typeof operation !== "string" || !OPERATIONS.has(operation)) return `unknown operation ${JSON.stringify(operation)}`;
488
504
  if (config !== void 0 && typeof config !== "string" && !Number.isSafeInteger(config)) return "config must name an entry or give its index";
489
505
  if (operation === require_protocol.ConfigEditOperation.SET_INPUT) return typeof input === "string" && input.trim() !== "" ? void 0 : "the edit names no input";
490
506
  const isOption = OPTION_OPERATIONS.has(operation);
491
507
  const isOutput = OUTPUT_OPERATIONS.has(operation);
492
508
  if (!isOutput && !isNonEmptyString(plugin)) return "the edit names no plugin";
509
+ const escaping = findEscapingOutputPath(operation === require_protocol.ConfigEditOperation.SET_OPTION && Array.isArray(path) ? path.reduceRight((inner, key) => ({ [String(key)]: inner }), value) : options);
510
+ if (escaping !== void 0) return `output.path ${JSON.stringify(escaping)} resolves outside the output folder`;
493
511
  if (kind !== void 0) {
494
512
  if (typeof kind !== "string" || !KINDS.has(kind)) return `unknown kind ${JSON.stringify(kind)}`;
495
513
  const takesKind = operation === require_protocol.ConfigEditOperation.ADD_PLUGIN || operation === require_protocol.ConfigEditOperation.REMOVE_EXTENSION;
@@ -1148,13 +1166,13 @@ function applyEdit({ source, edit, extensions }) {
1148
1166
  function editConfig({ source, edits, extensions = /* @__PURE__ */ new Map() }) {
1149
1167
  let current = source;
1150
1168
  const outcomes = edits.map((edit) => {
1151
- const invalid = validateEdit(edit);
1152
- if (invalid) return {
1153
- edit,
1154
- applied: false,
1155
- reason: invalid
1156
- };
1157
1169
  try {
1170
+ const invalid = validateEdit(edit);
1171
+ if (invalid) return {
1172
+ edit,
1173
+ applied: false,
1174
+ reason: invalid
1175
+ };
1158
1176
  const result = applyEdit({
1159
1177
  source: current,
1160
1178
  edit,
@@ -1391,7 +1409,7 @@ function generationFailure(diagnostics) {
1391
1409
  * Runs one generation and returns the files it produced. The formatter, the linter, and
1392
1410
  * `output.postGenerate` only run with `allowExec`. Throws when any plugin reports an error.
1393
1411
  */
1394
- async function generate({ config, hooks, signal, allowExec }) {
1412
+ async function generate({ config, hooks, signal, allowExec, fileRefs }) {
1395
1413
  const output = allowExec ? config.output : {
1396
1414
  ...config.output,
1397
1415
  format: false,
@@ -1403,7 +1421,8 @@ async function generate({ config, hooks, signal, allowExec }) {
1403
1421
  output
1404
1422
  }, {
1405
1423
  hooks,
1406
- signal
1424
+ signal,
1425
+ fileRefs
1407
1426
  });
1408
1427
  const result = await kubb.generate();
1409
1428
  if (!result.success) throw generationFailure(result.diagnostics);
@@ -1786,7 +1805,7 @@ const NO_BODY = /* @__PURE__ */ new Set([
1786
1805
  304
1787
1806
  ]);
1788
1807
  function notPublic(host) {
1789
- return /* @__PURE__ */ new Error(`${host} is not a public address, so a managed agent does not fetch from it`);
1808
+ return /* @__PURE__ */ new Error(`${host} is not a public address, so this agent does not fetch from it`);
1790
1809
  }
1791
1810
  function createLookup(blocked) {
1792
1811
  return (hostname, options, callback) => {
@@ -1838,8 +1857,8 @@ function request({ url, blocked, signal }) {
1838
1857
  */
1839
1858
  function createPublicFetch(blocked) {
1840
1859
  const publicFetch = async (input, init) => {
1841
- if (typeof input !== "string" && !(input instanceof URL)) throw new TypeError("A managed agent fetches by URL only");
1842
- if (init?.method && init.method.toUpperCase() !== "GET") throw new TypeError("A managed agent only sends GET requests");
1860
+ if (typeof input !== "string" && !(input instanceof URL)) throw new TypeError("This agent fetches by URL only");
1861
+ if (init?.method && init.method.toUpperCase() !== "GET") throw new TypeError("This agent only sends GET requests");
1843
1862
  let url = new URL(input);
1844
1863
  for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
1845
1864
  const response = await request({
@@ -1858,7 +1877,7 @@ function createPublicFetch(blocked) {
1858
1877
  }
1859
1878
  /**
1860
1879
  * Runs `run` with the global `fetch` limited to public addresses, then puts the original back.
1861
- * A managed agent runs one job at a time, so nothing else shares the window.
1880
+ * A sandbox or managed agent runs one job at a time, so nothing else shares the window.
1862
1881
  */
1863
1882
  async function withPublicFetch(run) {
1864
1883
  const original = globalThis.fetch;
@@ -2131,6 +2150,18 @@ function assertOutputPaths({ plugins, diskPlugins, root, outputPath }) {
2131
2150
  }
2132
2151
  }
2133
2152
  /**
2153
+ * The folders a `$ref` may read local files from on each kind of agent. Studio may have sent the
2154
+ * spec, so a shared agent gets none, and a managed agent only the git checkout it made itself. A
2155
+ * project agent gets its `root` and the folder of the file `input` in its own config. `undefined`
2156
+ * means no limit, which only `allowFileRefs` grants.
2157
+ */
2158
+ function resolveFileRefs({ agentType, allowFileRefs, root, input, checkoutDir }) {
2159
+ if (agentType === "sandbox" || agentType === "global") return [];
2160
+ if (agentType === "managed") return checkoutDir ? [checkoutDir] : [];
2161
+ if (allowFileRefs) return void 0;
2162
+ return typeof input === "string" && (0, _kubb_core.getInputKind)(input) === "file" ? [root, node_path.default.dirname(node_path.default.resolve(root, input))] : [root];
2163
+ }
2164
+ /**
2134
2165
  * Re-invokes the factory behind a disk adapter or parser with Studio's options merged over its own.
2135
2166
  * An instance carries live functions (`parse`, `print`, ...) that cannot survive JSON, so Studio's
2136
2167
  * options are a patch, not a replacement, and the factory is found from the disk instance itself: the
@@ -2222,6 +2253,7 @@ function secureUrl({ studioUrl, path, socket = false }) {
2222
2253
  }
2223
2254
  // src/connect.ts
2224
2255
  const HEARTBEAT_INTERVAL_MS = 3e4;
2256
+ const SHARED_AGENT_TYPES = /* @__PURE__ */ new Set(["sandbox", "global"]);
2225
2257
  const MAX_HEARTBEAT_INTERVAL_MS = 6e4;
2226
2258
  const PING_TIMEOUT_MS = 1e4;
2227
2259
  const OPEN_TIMEOUT_MS = 5e3;
@@ -2347,14 +2379,25 @@ var Agent = class extends capnweb.RpcTarget {
2347
2379
  this.#session = session;
2348
2380
  }
2349
2381
  get #sandbox() {
2350
- return this.#session.info?.sandbox === true;
2382
+ return SHARED_AGENT_TYPES.has(this.#options.agentType) || this.#session.info?.sandbox === true;
2351
2383
  }
2352
2384
  get #managed() {
2353
- return this.#session.info?.managed === true;
2385
+ return this.#options.agentType === "managed" || this.#session.info?.managed === true;
2386
+ }
2387
+ get #agentType() {
2388
+ if (this.#sandbox) return "sandbox";
2389
+ if (this.#managed) return "managed";
2390
+ return this.#options.agentType;
2354
2391
  }
2355
2392
  get #permissions() {
2356
- const { permissions } = this.#options;
2357
- return this.#sandbox ? {
2393
+ const { permissions, agentType } = this.#options;
2394
+ const sandbox = SHARED_AGENT_TYPES.has(agentType);
2395
+ if (this.#managed) return {
2396
+ ...permissions,
2397
+ allowFileRefs: false
2398
+ };
2399
+ if (!this.#sandbox) return permissions;
2400
+ return {
2358
2401
  ...permissions,
2359
2402
  allowWrite: false,
2360
2403
  allowConfigEdit: false,
@@ -2362,9 +2405,10 @@ var Agent = class extends capnweb.RpcTarget {
2362
2405
  allowUpdate: false,
2363
2406
  allowRemove: false,
2364
2407
  allowSaveInput: false,
2365
- allowRead: true,
2366
- allowReadAst: true
2367
- } : permissions;
2408
+ allowFileRefs: false,
2409
+ allowRead: sandbox || permissions.allowRead,
2410
+ allowReadAst: sandbox || permissions.allowReadAst
2411
+ };
2368
2412
  }
2369
2413
  get #generations() {
2370
2414
  this.#store ??= createGenerationStore({
@@ -2586,7 +2630,8 @@ var Agent = class extends capnweb.RpcTarget {
2586
2630
  });
2587
2631
  const activePlugins = plugins ?? config.plugins;
2588
2632
  if (patch?.input && !this.#sandbox && !this.#managed) await emit(this.#options.hooks, "kubb:warn", { message: "Ignored the spec from Studio: generating from a Studio spec is only available to a sandbox or managed agent" });
2589
- const checkout = this.#managed && studioInput !== void 0 && (0, _kubb_core.getInputKind)(studioInput) === "git" ? await (0, _kubb_core.checkoutGitInput)(studioInput, signal, {
2633
+ const managedInput = this.#managed ? studioInput ?? config.input : void 0;
2634
+ const checkout = typeof managedInput === "string" && (0, _kubb_core.getInputKind)(managedInput) === "git" ? await (0, _kubb_core.checkoutGitInput)(managedInput, signal, {
2590
2635
  publicOnly: true,
2591
2636
  authorization: input.gitAuth?.authorization
2592
2637
  }).catch((error) => this.#refuse({
@@ -2612,9 +2657,16 @@ var Agent = class extends capnweb.RpcTarget {
2612
2657
  },
2613
2658
  hooks: this.#options.hooks,
2614
2659
  signal,
2615
- allowExec: this.#permissions.allowWrite && this.#permissions.allowExec
2660
+ allowExec: this.#permissions.allowWrite && this.#permissions.allowExec,
2661
+ fileRefs: resolveFileRefs({
2662
+ agentType: this.#agentType,
2663
+ allowFileRefs: this.#permissions.allowFileRefs,
2664
+ root: this.#options.root,
2665
+ input: config.input,
2666
+ checkoutDir: checkout?.dir
2667
+ })
2616
2668
  });
2617
- const files = await (this.#managed ? withPublicFetch(run) : run()).catch(async (error) => {
2669
+ const files = await (this.#sandbox || this.#managed ? withPublicFetch(run) : run()).catch(async (error) => {
2618
2670
  await this.#generations.drop(jobId);
2619
2671
  await this.#logCommand("generate", getErrorMessage(error), input.requestedBy, true);
2620
2672
  throw error;
@@ -2709,7 +2761,7 @@ var Agent = class extends capnweb.RpcTarget {
2709
2761
  /**
2710
2762
  * Readies a `set-input` edit for the config file: a document is pointed at `openapi.yaml` (`openapi.json`
2711
2763
  * for JSON) in the project, one file per config entry, for `saveConfig` to write once the edit applies.
2712
- * A managed agent refuses a file path, as in a generation.
2764
+ * A managed agent refuses a file path, as in a generation. Every agent refuses a file path outside the project.
2713
2765
  */
2714
2766
  async #keepInput(edit) {
2715
2767
  if (edit?.operation !== require_protocol.ConfigEditOperation.SET_INPUT || typeof edit.input !== "string" || !edit.input.trim()) return edit;
@@ -2722,6 +2774,7 @@ var Agent = class extends capnweb.RpcTarget {
2722
2774
  }
2723
2775
  const kind = (0, _kubb_core.getInputKind)(edit.input);
2724
2776
  if (this.#managed && !MANAGED_INPUT_KINDS.has(kind)) return { reason: require_protocol.AgentMessage.MANAGED_INPUT_KIND };
2777
+ if ((kind === "file" || kind === "url" && !/^https?:/i.test(edit.input)) && !isPathInside(node_path.default.resolve(this.#options.root, edit.input), this.#options.root)) return { reason: "the input is a file outside the project" };
2725
2778
  if (kind !== "inline") return edit;
2726
2779
  const fileName = `openapi${edit.config === void 0 || edit.config === 0 ? "" : `-${String(edit.config).replace(/[^\w.-]/g, "-")}`}.${isJson(edit.input) ? "json" : "yaml"}`;
2727
2780
  return {
@@ -3132,6 +3185,7 @@ async function runAgent({ options, openRpc }) {
3132
3185
  ...options,
3133
3186
  studioUrl: options.studioUrl ?? "https://kubb.studio",
3134
3187
  root,
3188
+ agentType: options.agentType ?? "user",
3135
3189
  configFile: node_path.default.resolve(root, options.configPath),
3136
3190
  permissions: {
3137
3191
  allowWrite: false,
@@ -3140,6 +3194,7 @@ async function runAgent({ options, openRpc }) {
3140
3194
  allowUpdate: false,
3141
3195
  allowRemove: false,
3142
3196
  allowSaveInput: false,
3197
+ allowFileRefs: false,
3143
3198
  allowExec: false,
3144
3199
  allowRead: false,
3145
3200
  allowReadAst: false,