@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/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { B as SnapshotUploadMetadata, G as editConfig, K as editConfigFile, O as PublishedSnapshot, a as AgentConnectInfo, c as AgentPermissions, s as AgentPermission } from "./protocol-f2YAAGLi.cjs";
1
+ import { K as editConfig, V as SnapshotUploadMetadata, a as AgentConnectInfo, c as AgentPermissions, k as PublishedSnapshot, l as AgentType, q as editConfigFile, s as AgentPermission } from "./protocol-BFIUEXLA.cjs";
2
2
  import { Config, Hookable, KubbHooks } from "@kubb/core";
3
3
  /**
4
4
  * Studio closed with {@link AgentCloseCode.UNAUTHORIZED}. Hosts forget the token and pair again.
@@ -96,6 +96,12 @@ type ConnectAgentOptions = {
96
96
  * What Studio may do in this project. Every permission is off unless granted.
97
97
  */
98
98
  permissions?: Partial<AgentPermissions>;
99
+ /**
100
+ * The kind of agent the host runs. A `'sandbox'` or `'global'` agent is shared, and lets Studio read what it generated.
101
+ * Studio's own `sandbox` and `managed` flags only take permissions away.
102
+ * @default 'user'
103
+ */
104
+ agentType?: AgentType;
99
105
  /** The CLI entry `installExtension` runs `kubb add` with. Found through the project's `kubb` or `@kubb/cli` dependency when omitted. */
100
106
  kubbBin?: string;
101
107
  /**
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { B as SnapshotUploadMetadata, G as editConfig, K as editConfigFile, O as PublishedSnapshot, a as AgentConnectInfo, c as AgentPermissions, s as AgentPermission } from "./protocol-f2YAAGLi.js";
1
+ import { K as editConfig, V as SnapshotUploadMetadata, a as AgentConnectInfo, c as AgentPermissions, k as PublishedSnapshot, l as AgentType, q as editConfigFile, s as AgentPermission } from "./protocol-BFIUEXLA.js";
2
2
  import { Config, Hookable, KubbHooks } from "@kubb/core";
3
3
  /**
4
4
  * Studio closed with {@link AgentCloseCode.UNAUTHORIZED}. Hosts forget the token and pair again.
@@ -96,6 +96,12 @@ type ConnectAgentOptions = {
96
96
  * What Studio may do in this project. Every permission is off unless granted.
97
97
  */
98
98
  permissions?: Partial<AgentPermissions>;
99
+ /**
100
+ * The kind of agent the host runs. A `'sandbox'` or `'global'` agent is shared, and lets Studio read what it generated.
101
+ * Studio's own `sandbox` and `managed` flags only take permissions away.
102
+ * @default 'user'
103
+ */
104
+ agentType?: AgentType;
99
105
  /** The CLI entry `installExtension` runs `kubb add` with. Found through the project's `kubb` or `@kubb/cli` dependency when omitted. */
100
106
  kubbBin?: string;
101
107
  /**
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import { a as AgentPermission, c as MAX_SNAPSHOT_BYTES, d as extensionKinds, i as AgentMessage, l as generationEventTypes, n as AGENT_SOCKET_PATH, r as AgentCloseCode, t as AGENT_INSTANCE_HEADER, u as ConfigEditOperation } from "./protocol-B6oWLc7W.js";
1
+ import { a as AgentPermission, c as MAX_SNAPSHOT_BYTES, d as extensionKinds, i as AgentMessage, l as generationEventTypes, n as AGENT_SOCKET_PATH, r as AgentCloseCode, t as AGENT_INSTANCE_HEADER, u as ConfigEditOperation } from "./protocol-xk8P0Zhv.js";
2
2
  import { createRequire } from "node:module";
3
3
  import { createHash, hash, randomUUID } from "node:crypto";
4
4
  import { existsSync, readFile, writeFile } from "node:fs";
@@ -223,7 +223,7 @@ function isPathInside(path, parent) {
223
223
  return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
224
224
  }
225
225
  // package.json
226
- var version = "5.19.0";
226
+ var version = "5.19.1";
227
227
  // ../../internals/shared/src/constants.ts
228
228
  /**
229
229
  * Extensions `kubb` ships at its own version, so they count as installed without being a direct
@@ -360,6 +360,22 @@ function isOutputValue({ key, value }) {
360
360
  function pickOutput(output) {
361
361
  return Object.fromEntries(Object.entries(output).filter(([key]) => isOutputKey(key)));
362
362
  }
363
+ /**
364
+ * Returns the first `output.path` in `value`, at any depth (`override` entries included), that is
365
+ * absolute or climbs out of the folder it resolves against.
366
+ */
367
+ function findEscapingOutputPath(value) {
368
+ if (!Array.isArray(value) && !isPlainObject(value)) return void 0;
369
+ const output = isPlainObject(value) ? value.output : void 0;
370
+ if (isPlainObject(output) && typeof output.path === "string") {
371
+ const normalized = path.posix.normalize(output.path.replaceAll("\\", "/"));
372
+ if (path.posix.isAbsolute(normalized) || /^[a-z]:/i.test(output.path) || normalized === ".." || normalized.startsWith("../")) return output.path;
373
+ }
374
+ for (const entry of Object.values(value)) {
375
+ const found = findEscapingOutputPath(entry);
376
+ if (found !== void 0) return found;
377
+ }
378
+ }
363
379
  // ../../internals/shared/src/configFile/text.ts
364
380
  /**
365
381
  * A valid JavaScript identifier, so an import name can only ever print as `import { name } from`,
@@ -455,13 +471,15 @@ function isNonEmptyString(value) {
455
471
  }
456
472
  /** Edits cross the wire, so their shape is checked before anything reads them. */
457
473
  function validateEdit(edit) {
458
- const { operation, plugin, config, path, kind, input } = typeof edit === "object" && edit !== null ? edit : {};
474
+ const { operation, plugin, config, path, kind, input, value, options } = typeof edit === "object" && edit !== null ? edit : {};
459
475
  if (typeof operation !== "string" || !OPERATIONS.has(operation)) return `unknown operation ${JSON.stringify(operation)}`;
460
476
  if (config !== void 0 && typeof config !== "string" && !Number.isSafeInteger(config)) return "config must name an entry or give its index";
461
477
  if (operation === ConfigEditOperation.SET_INPUT) return typeof input === "string" && input.trim() !== "" ? void 0 : "the edit names no input";
462
478
  const isOption = OPTION_OPERATIONS.has(operation);
463
479
  const isOutput = OUTPUT_OPERATIONS.has(operation);
464
480
  if (!isOutput && !isNonEmptyString(plugin)) return "the edit names no plugin";
481
+ const escaping = findEscapingOutputPath(operation === ConfigEditOperation.SET_OPTION && Array.isArray(path) ? path.reduceRight((inner, key) => ({ [String(key)]: inner }), value) : options);
482
+ if (escaping !== void 0) return `output.path ${JSON.stringify(escaping)} resolves outside the output folder`;
465
483
  if (kind !== void 0) {
466
484
  if (typeof kind !== "string" || !KINDS.has(kind)) return `unknown kind ${JSON.stringify(kind)}`;
467
485
  const takesKind = operation === ConfigEditOperation.ADD_PLUGIN || operation === ConfigEditOperation.REMOVE_EXTENSION;
@@ -1120,13 +1138,13 @@ function applyEdit({ source, edit, extensions }) {
1120
1138
  function editConfig({ source, edits, extensions = /* @__PURE__ */ new Map() }) {
1121
1139
  let current = source;
1122
1140
  const outcomes = edits.map((edit) => {
1123
- const invalid = validateEdit(edit);
1124
- if (invalid) return {
1125
- edit,
1126
- applied: false,
1127
- reason: invalid
1128
- };
1129
1141
  try {
1142
+ const invalid = validateEdit(edit);
1143
+ if (invalid) return {
1144
+ edit,
1145
+ applied: false,
1146
+ reason: invalid
1147
+ };
1130
1148
  const result = applyEdit({
1131
1149
  source: current,
1132
1150
  edit,
@@ -1363,7 +1381,7 @@ function generationFailure(diagnostics) {
1363
1381
  * Runs one generation and returns the files it produced. The formatter, the linter, and
1364
1382
  * `output.postGenerate` only run with `allowExec`. Throws when any plugin reports an error.
1365
1383
  */
1366
- async function generate({ config, hooks, signal, allowExec }) {
1384
+ async function generate({ config, hooks, signal, allowExec, fileRefs }) {
1367
1385
  const output = allowExec ? config.output : {
1368
1386
  ...config.output,
1369
1387
  format: false,
@@ -1375,7 +1393,8 @@ async function generate({ config, hooks, signal, allowExec }) {
1375
1393
  output
1376
1394
  }, {
1377
1395
  hooks,
1378
- signal
1396
+ signal,
1397
+ fileRefs
1379
1398
  });
1380
1399
  const result = await kubb.generate();
1381
1400
  if (!result.success) throw generationFailure(result.diagnostics);
@@ -1758,7 +1777,7 @@ const NO_BODY = /* @__PURE__ */ new Set([
1758
1777
  304
1759
1778
  ]);
1760
1779
  function notPublic(host) {
1761
- return /* @__PURE__ */ new Error(`${host} is not a public address, so a managed agent does not fetch from it`);
1780
+ return /* @__PURE__ */ new Error(`${host} is not a public address, so this agent does not fetch from it`);
1762
1781
  }
1763
1782
  function createLookup(blocked) {
1764
1783
  return (hostname, options, callback) => {
@@ -1810,8 +1829,8 @@ function request({ url, blocked, signal }) {
1810
1829
  */
1811
1830
  function createPublicFetch(blocked) {
1812
1831
  const publicFetch = async (input, init) => {
1813
- if (typeof input !== "string" && !(input instanceof URL)) throw new TypeError("A managed agent fetches by URL only");
1814
- if (init?.method && init.method.toUpperCase() !== "GET") throw new TypeError("A managed agent only sends GET requests");
1832
+ if (typeof input !== "string" && !(input instanceof URL)) throw new TypeError("This agent fetches by URL only");
1833
+ if (init?.method && init.method.toUpperCase() !== "GET") throw new TypeError("This agent only sends GET requests");
1815
1834
  let url = new URL(input);
1816
1835
  for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
1817
1836
  const response = await request({
@@ -1830,7 +1849,7 @@ function createPublicFetch(blocked) {
1830
1849
  }
1831
1850
  /**
1832
1851
  * Runs `run` with the global `fetch` limited to public addresses, then puts the original back.
1833
- * A managed agent runs one job at a time, so nothing else shares the window.
1852
+ * A sandbox or managed agent runs one job at a time, so nothing else shares the window.
1834
1853
  */
1835
1854
  async function withPublicFetch(run) {
1836
1855
  const original = globalThis.fetch;
@@ -2103,6 +2122,18 @@ function assertOutputPaths({ plugins, diskPlugins, root, outputPath }) {
2103
2122
  }
2104
2123
  }
2105
2124
  /**
2125
+ * The folders a `$ref` may read local files from on each kind of agent. Studio may have sent the
2126
+ * spec, so a shared agent gets none, and a managed agent only the git checkout it made itself. A
2127
+ * project agent gets its `root` and the folder of the file `input` in its own config. `undefined`
2128
+ * means no limit, which only `allowFileRefs` grants.
2129
+ */
2130
+ function resolveFileRefs({ agentType, allowFileRefs, root, input, checkoutDir }) {
2131
+ if (agentType === "sandbox" || agentType === "global") return [];
2132
+ if (agentType === "managed") return checkoutDir ? [checkoutDir] : [];
2133
+ if (allowFileRefs) return void 0;
2134
+ return typeof input === "string" && getInputKind(input) === "file" ? [root, path.dirname(path.resolve(root, input))] : [root];
2135
+ }
2136
+ /**
2106
2137
  * Re-invokes the factory behind a disk adapter or parser with Studio's options merged over its own.
2107
2138
  * An instance carries live functions (`parse`, `print`, ...) that cannot survive JSON, so Studio's
2108
2139
  * options are a patch, not a replacement, and the factory is found from the disk instance itself: the
@@ -2194,6 +2225,7 @@ function secureUrl({ studioUrl, path, socket = false }) {
2194
2225
  }
2195
2226
  // src/connect.ts
2196
2227
  const HEARTBEAT_INTERVAL_MS = 3e4;
2228
+ const SHARED_AGENT_TYPES = /* @__PURE__ */ new Set(["sandbox", "global"]);
2197
2229
  const MAX_HEARTBEAT_INTERVAL_MS = 6e4;
2198
2230
  const PING_TIMEOUT_MS = 1e4;
2199
2231
  const OPEN_TIMEOUT_MS = 5e3;
@@ -2319,14 +2351,25 @@ var Agent = class extends RpcTarget {
2319
2351
  this.#session = session;
2320
2352
  }
2321
2353
  get #sandbox() {
2322
- return this.#session.info?.sandbox === true;
2354
+ return SHARED_AGENT_TYPES.has(this.#options.agentType) || this.#session.info?.sandbox === true;
2323
2355
  }
2324
2356
  get #managed() {
2325
- return this.#session.info?.managed === true;
2357
+ return this.#options.agentType === "managed" || this.#session.info?.managed === true;
2358
+ }
2359
+ get #agentType() {
2360
+ if (this.#sandbox) return "sandbox";
2361
+ if (this.#managed) return "managed";
2362
+ return this.#options.agentType;
2326
2363
  }
2327
2364
  get #permissions() {
2328
- const { permissions } = this.#options;
2329
- return this.#sandbox ? {
2365
+ const { permissions, agentType } = this.#options;
2366
+ const sandbox = SHARED_AGENT_TYPES.has(agentType);
2367
+ if (this.#managed) return {
2368
+ ...permissions,
2369
+ allowFileRefs: false
2370
+ };
2371
+ if (!this.#sandbox) return permissions;
2372
+ return {
2330
2373
  ...permissions,
2331
2374
  allowWrite: false,
2332
2375
  allowConfigEdit: false,
@@ -2334,9 +2377,10 @@ var Agent = class extends RpcTarget {
2334
2377
  allowUpdate: false,
2335
2378
  allowRemove: false,
2336
2379
  allowSaveInput: false,
2337
- allowRead: true,
2338
- allowReadAst: true
2339
- } : permissions;
2380
+ allowFileRefs: false,
2381
+ allowRead: sandbox || permissions.allowRead,
2382
+ allowReadAst: sandbox || permissions.allowReadAst
2383
+ };
2340
2384
  }
2341
2385
  get #generations() {
2342
2386
  this.#store ??= createGenerationStore({
@@ -2558,7 +2602,8 @@ var Agent = class extends RpcTarget {
2558
2602
  });
2559
2603
  const activePlugins = plugins ?? config.plugins;
2560
2604
  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" });
2561
- const checkout = this.#managed && studioInput !== void 0 && getInputKind(studioInput) === "git" ? await checkoutGitInput(studioInput, signal, {
2605
+ const managedInput = this.#managed ? studioInput ?? config.input : void 0;
2606
+ const checkout = typeof managedInput === "string" && getInputKind(managedInput) === "git" ? await checkoutGitInput(managedInput, signal, {
2562
2607
  publicOnly: true,
2563
2608
  authorization: input.gitAuth?.authorization
2564
2609
  }).catch((error) => this.#refuse({
@@ -2584,9 +2629,16 @@ var Agent = class extends RpcTarget {
2584
2629
  },
2585
2630
  hooks: this.#options.hooks,
2586
2631
  signal,
2587
- allowExec: this.#permissions.allowWrite && this.#permissions.allowExec
2632
+ allowExec: this.#permissions.allowWrite && this.#permissions.allowExec,
2633
+ fileRefs: resolveFileRefs({
2634
+ agentType: this.#agentType,
2635
+ allowFileRefs: this.#permissions.allowFileRefs,
2636
+ root: this.#options.root,
2637
+ input: config.input,
2638
+ checkoutDir: checkout?.dir
2639
+ })
2588
2640
  });
2589
- const files = await (this.#managed ? withPublicFetch(run) : run()).catch(async (error) => {
2641
+ const files = await (this.#sandbox || this.#managed ? withPublicFetch(run) : run()).catch(async (error) => {
2590
2642
  await this.#generations.drop(jobId);
2591
2643
  await this.#logCommand("generate", getErrorMessage(error), input.requestedBy, true);
2592
2644
  throw error;
@@ -2681,7 +2733,7 @@ var Agent = class extends RpcTarget {
2681
2733
  /**
2682
2734
  * Readies a `set-input` edit for the config file: a document is pointed at `openapi.yaml` (`openapi.json`
2683
2735
  * for JSON) in the project, one file per config entry, for `saveConfig` to write once the edit applies.
2684
- * A managed agent refuses a file path, as in a generation.
2736
+ * A managed agent refuses a file path, as in a generation. Every agent refuses a file path outside the project.
2685
2737
  */
2686
2738
  async #keepInput(edit) {
2687
2739
  if (edit?.operation !== ConfigEditOperation.SET_INPUT || typeof edit.input !== "string" || !edit.input.trim()) return edit;
@@ -2694,6 +2746,7 @@ var Agent = class extends RpcTarget {
2694
2746
  }
2695
2747
  const kind = getInputKind(edit.input);
2696
2748
  if (this.#managed && !MANAGED_INPUT_KINDS.has(kind)) return { reason: AgentMessage.MANAGED_INPUT_KIND };
2749
+ if ((kind === "file" || kind === "url" && !/^https?:/i.test(edit.input)) && !isPathInside(path.resolve(this.#options.root, edit.input), this.#options.root)) return { reason: "the input is a file outside the project" };
2697
2750
  if (kind !== "inline") return edit;
2698
2751
  const fileName = `openapi${edit.config === void 0 || edit.config === 0 ? "" : `-${String(edit.config).replace(/[^\w.-]/g, "-")}`}.${isJson(edit.input) ? "json" : "yaml"}`;
2699
2752
  return {
@@ -3104,6 +3157,7 @@ async function runAgent({ options, openRpc }) {
3104
3157
  ...options,
3105
3158
  studioUrl: options.studioUrl ?? "https://kubb.studio",
3106
3159
  root,
3160
+ agentType: options.agentType ?? "user",
3107
3161
  configFile: path.resolve(root, options.configPath),
3108
3162
  permissions: {
3109
3163
  allowWrite: false,
@@ -3112,6 +3166,7 @@ async function runAgent({ options, openRpc }) {
3112
3166
  allowUpdate: false,
3113
3167
  allowRemove: false,
3114
3168
  allowSaveInput: false,
3169
+ allowFileRefs: false,
3115
3170
  allowExec: false,
3116
3171
  allowRead: false,
3117
3172
  allowReadAst: false,