@kubb/studio 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.d.cts CHANGED
@@ -1,5 +1,34 @@
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 { U as SnapshotUploadMetadata, X as editConfigFile, Y as editConfig, a as AgentConnectInfo, c as AgentPermissions, j as PublishedSnapshot, l as AgentSignatureContext, s as AgentPermission, u as AgentType } from "./protocol-CgearBUc.cjs";
2
2
  import { Config, Hookable, KubbHooks } from "@kubb/core";
3
+ /**
4
+ * Creates the agent's Ed25519 key as a PKCS #8 PEM string, to store with the token.
5
+ */
6
+ export declare function generateAgentKey(): string;
7
+ /**
8
+ * Returns the raw 32-byte public key of `privateKey`, base64url without padding.
9
+ */
10
+ export declare function getAgentPublicKey(privateKey: string): string;
11
+ /**
12
+ * Signs `payload` for `context` and returns the Ed25519 signature in base64url.
13
+ */
14
+ export declare function signAgentPayload({ privateKey, context, payload }: {
15
+ privateKey: string;
16
+ context: AgentSignatureContext;
17
+ payload: string;
18
+ }): string;
19
+ /**
20
+ * Checks a {@link signAgentPayload} signature. Malformed input returns `false` and never throws.
21
+ */
22
+ export declare function verifyAgentSignature({ publicKey, context, payload, signature }: {
23
+ publicKey: string;
24
+ context: AgentSignatureContext;
25
+ payload: string;
26
+ signature: string;
27
+ }): boolean;
28
+ export declare function getTokenRefreshPayload({ token, signedAt }: {
29
+ token: string;
30
+ signedAt: number;
31
+ }): string;
3
32
  /**
4
33
  * Studio closed with {@link AgentCloseCode.UNAUTHORIZED}. Hosts forget the token and pair again.
5
34
  */
@@ -70,9 +99,13 @@ declare global {
70
99
  }
71
100
  type ConnectAgentOptions = {
72
101
  /**
73
- * The agent's bearer token, from {@link pairAgent}.
102
+ * The agent's bearer token, from {@link pairAgent}. A function is read before every socket opens.
74
103
  */
75
- token: string;
104
+ token: string | (() => string | Promise<string>);
105
+ /**
106
+ * The agent key from `generateAgentKey`, which signs the connect challenge.
107
+ */
108
+ privateKey?: string;
76
109
  studioUrl?: string;
77
110
  /**
78
111
  * The config path shown in Studio, relative to `root` unless absolute.
@@ -96,6 +129,12 @@ type ConnectAgentOptions = {
96
129
  * What Studio may do in this project. Every permission is off unless granted.
97
130
  */
98
131
  permissions?: Partial<AgentPermissions>;
132
+ /**
133
+ * The kind of agent the host runs. A `'sandbox'` or `'global'` agent is shared, and lets Studio read what it generated.
134
+ * Studio's own `sandbox` and `managed` flags only take permissions away.
135
+ * @default 'user'
136
+ */
137
+ agentType?: AgentType;
99
138
  /** The CLI entry `installExtension` runs `kubb add` with. Found through the project's `kubb` or `@kubb/cli` dependency when omitted. */
100
139
  kubbBin?: string;
101
140
  /**
@@ -198,6 +237,10 @@ type StartPairingOptions = {
198
237
  * the same machine pairing again rotates one agent's token instead of creating a second agent.
199
238
  */
200
239
  machineId: string;
240
+ /**
241
+ * The agent key from `generateAgentKey`. Only its public half is sent.
242
+ */
243
+ privateKey?: string;
201
244
  /**
202
245
  * Aborting this cancels the request in flight and rejects with {@link PairingCanceledError}.
203
246
  */
@@ -218,6 +261,31 @@ type PairAgentOptions = StartPairingOptions & {
218
261
  * Pairs this machine with Studio: asks for a code, hands it to the host to show, and waits for approval.
219
262
  */
220
263
  export declare function pairAgent({ onCode, onRetry, maxAttempts, ...options }: PairAgentOptions): Promise<PairingResult>;
264
+ type RefreshAgentTokenOptions = {
265
+ studioUrl?: string;
266
+ token: string;
267
+ /**
268
+ * The secret the machine paired with.
269
+ */
270
+ machineId: string;
271
+ /**
272
+ * The stored agent key, which signs the request.
273
+ */
274
+ privateKey?: string;
275
+ signal?: AbortSignal;
276
+ /**
277
+ * How long to wait for an answer, in milliseconds.
278
+ *
279
+ * @default 15000
280
+ */
281
+ timeout?: number;
282
+ };
283
+ /**
284
+ * Trades the agent's token for a new one. The old token stops working at once, so store the new
285
+ * one first. Resolves `null` when there is nothing to refresh, and rejects with
286
+ * {@link InvalidAgentTokenError} when the token is refused.
287
+ */
288
+ export declare function refreshAgentToken({ studioUrl, token, machineId, privateKey, signal, timeout }: RefreshAgentTokenOptions): Promise<string | null>;
221
289
  type CreateSnapshotOptions = Omit<SnapshotUploadMetadata, 'hashes' | 'peerDependencies'> & {
222
290
  studioUrl?: string;
223
291
  /**
package/dist/index.d.ts CHANGED
@@ -1,5 +1,34 @@
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 { U as SnapshotUploadMetadata, X as editConfigFile, Y as editConfig, a as AgentConnectInfo, c as AgentPermissions, j as PublishedSnapshot, l as AgentSignatureContext, s as AgentPermission, u as AgentType } from "./protocol-CgearBUc.js";
2
2
  import { Config, Hookable, KubbHooks } from "@kubb/core";
3
+ /**
4
+ * Creates the agent's Ed25519 key as a PKCS #8 PEM string, to store with the token.
5
+ */
6
+ export declare function generateAgentKey(): string;
7
+ /**
8
+ * Returns the raw 32-byte public key of `privateKey`, base64url without padding.
9
+ */
10
+ export declare function getAgentPublicKey(privateKey: string): string;
11
+ /**
12
+ * Signs `payload` for `context` and returns the Ed25519 signature in base64url.
13
+ */
14
+ export declare function signAgentPayload({ privateKey, context, payload }: {
15
+ privateKey: string;
16
+ context: AgentSignatureContext;
17
+ payload: string;
18
+ }): string;
19
+ /**
20
+ * Checks a {@link signAgentPayload} signature. Malformed input returns `false` and never throws.
21
+ */
22
+ export declare function verifyAgentSignature({ publicKey, context, payload, signature }: {
23
+ publicKey: string;
24
+ context: AgentSignatureContext;
25
+ payload: string;
26
+ signature: string;
27
+ }): boolean;
28
+ export declare function getTokenRefreshPayload({ token, signedAt }: {
29
+ token: string;
30
+ signedAt: number;
31
+ }): string;
3
32
  /**
4
33
  * Studio closed with {@link AgentCloseCode.UNAUTHORIZED}. Hosts forget the token and pair again.
5
34
  */
@@ -70,9 +99,13 @@ declare global {
70
99
  }
71
100
  type ConnectAgentOptions = {
72
101
  /**
73
- * The agent's bearer token, from {@link pairAgent}.
102
+ * The agent's bearer token, from {@link pairAgent}. A function is read before every socket opens.
74
103
  */
75
- token: string;
104
+ token: string | (() => string | Promise<string>);
105
+ /**
106
+ * The agent key from `generateAgentKey`, which signs the connect challenge.
107
+ */
108
+ privateKey?: string;
76
109
  studioUrl?: string;
77
110
  /**
78
111
  * The config path shown in Studio, relative to `root` unless absolute.
@@ -96,6 +129,12 @@ type ConnectAgentOptions = {
96
129
  * What Studio may do in this project. Every permission is off unless granted.
97
130
  */
98
131
  permissions?: Partial<AgentPermissions>;
132
+ /**
133
+ * The kind of agent the host runs. A `'sandbox'` or `'global'` agent is shared, and lets Studio read what it generated.
134
+ * Studio's own `sandbox` and `managed` flags only take permissions away.
135
+ * @default 'user'
136
+ */
137
+ agentType?: AgentType;
99
138
  /** The CLI entry `installExtension` runs `kubb add` with. Found through the project's `kubb` or `@kubb/cli` dependency when omitted. */
100
139
  kubbBin?: string;
101
140
  /**
@@ -198,6 +237,10 @@ type StartPairingOptions = {
198
237
  * the same machine pairing again rotates one agent's token instead of creating a second agent.
199
238
  */
200
239
  machineId: string;
240
+ /**
241
+ * The agent key from `generateAgentKey`. Only its public half is sent.
242
+ */
243
+ privateKey?: string;
201
244
  /**
202
245
  * Aborting this cancels the request in flight and rejects with {@link PairingCanceledError}.
203
246
  */
@@ -218,6 +261,31 @@ type PairAgentOptions = StartPairingOptions & {
218
261
  * Pairs this machine with Studio: asks for a code, hands it to the host to show, and waits for approval.
219
262
  */
220
263
  export declare function pairAgent({ onCode, onRetry, maxAttempts, ...options }: PairAgentOptions): Promise<PairingResult>;
264
+ type RefreshAgentTokenOptions = {
265
+ studioUrl?: string;
266
+ token: string;
267
+ /**
268
+ * The secret the machine paired with.
269
+ */
270
+ machineId: string;
271
+ /**
272
+ * The stored agent key, which signs the request.
273
+ */
274
+ privateKey?: string;
275
+ signal?: AbortSignal;
276
+ /**
277
+ * How long to wait for an answer, in milliseconds.
278
+ *
279
+ * @default 15000
280
+ */
281
+ timeout?: number;
282
+ };
283
+ /**
284
+ * Trades the agent's token for a new one. The old token stops working at once, so store the new
285
+ * one first. Resolves `null` when there is nothing to refresh, and rejects with
286
+ * {@link InvalidAgentTokenError} when the token is refused.
287
+ */
288
+ export declare function refreshAgentToken({ studioUrl, token, machineId, privateKey, signal, timeout }: RefreshAgentTokenOptions): Promise<string | null>;
221
289
  type CreateSnapshotOptions = Omit<SnapshotUploadMetadata, 'hashes' | 'peerDependencies'> & {
222
290
  studioUrl?: string;
223
291
  /**
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
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, d as generationEventTypes, f as ConfigEditOperation, i as AgentMessage, n as AGENT_SOCKET_PATH, o as AgentSignatureContext, p as extensionKinds, r as AgentCloseCode, t as AGENT_INSTANCE_HEADER, u as MAX_SNAPSHOT_BYTES } from "./protocol-BYLMyS9H.js";
2
2
  import { createRequire } from "node:module";
3
- import { createHash, hash, randomUUID } from "node:crypto";
3
+ import { createHash, createPublicKey, generateKeyPairSync, hash, randomUUID, sign, verify } from "node:crypto";
4
4
  import { existsSync, readFile, writeFile } from "node:fs";
5
5
  import { mkdir, mkdir as mkdir$1, mkdtemp, rm, writeFile as writeFile$1 } from "node:fs/promises";
6
6
  import { tmpdir } from "node:os";
@@ -22,6 +22,58 @@ import net from "node:net";
22
22
  import { Readable, Transform } from "node:stream";
23
23
  import { ofetch } from "ofetch";
24
24
  import { gzipSync } from "node:zlib";
25
+ // src/agentKey.ts
26
+ function signedBytes({ context, payload }) {
27
+ return Buffer.from(`${context}\n${payload}`, "utf8");
28
+ }
29
+ /**
30
+ * Creates the agent's Ed25519 key as a PKCS #8 PEM string, to store with the token.
31
+ */
32
+ function generateAgentKey() {
33
+ return generateKeyPairSync("ed25519").privateKey.export({
34
+ format: "pem",
35
+ type: "pkcs8"
36
+ }).toString();
37
+ }
38
+ /**
39
+ * Returns the raw 32-byte public key of `privateKey`, base64url without padding.
40
+ */
41
+ function getAgentPublicKey(privateKey) {
42
+ return createPublicKey(privateKey).export({ format: "jwk" }).x;
43
+ }
44
+ /**
45
+ * Signs `payload` for `context` and returns the Ed25519 signature in base64url.
46
+ */
47
+ function signAgentPayload({ privateKey, context, payload }) {
48
+ return sign(null, signedBytes({
49
+ context,
50
+ payload
51
+ }), privateKey).toString("base64url");
52
+ }
53
+ /**
54
+ * Checks a {@link signAgentPayload} signature. Malformed input returns `false` and never throws.
55
+ */
56
+ function verifyAgentSignature({ publicKey, context, payload, signature }) {
57
+ try {
58
+ const key = createPublicKey({
59
+ key: {
60
+ kty: "OKP",
61
+ crv: "Ed25519",
62
+ x: publicKey
63
+ },
64
+ format: "jwk"
65
+ });
66
+ return verify(null, signedBytes({
67
+ context,
68
+ payload
69
+ }), key, Buffer.from(signature, "base64url"));
70
+ } catch {
71
+ return false;
72
+ }
73
+ }
74
+ function getTokenRefreshPayload({ token, signedAt }) {
75
+ return `${signedAt}\n${hash("sha256", token)}`;
76
+ }
25
77
  // ../../internals/utils/src/promise.ts
26
78
  /**
27
79
  * Returns the value cached under `key` in `store`, computing and storing it on the first call.
@@ -223,7 +275,7 @@ function isPathInside(path, parent) {
223
275
  return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
224
276
  }
225
277
  // package.json
226
- var version = "5.19.0";
278
+ var version = "5.19.2";
227
279
  // ../../internals/shared/src/constants.ts
228
280
  /**
229
281
  * Extensions `kubb` ships at its own version, so they count as installed without being a direct
@@ -360,6 +412,22 @@ function isOutputValue({ key, value }) {
360
412
  function pickOutput(output) {
361
413
  return Object.fromEntries(Object.entries(output).filter(([key]) => isOutputKey(key)));
362
414
  }
415
+ /**
416
+ * Returns the first `output.path` in `value`, at any depth (`override` entries included), that is
417
+ * absolute or climbs out of the folder it resolves against.
418
+ */
419
+ function findEscapingOutputPath(value) {
420
+ if (!Array.isArray(value) && !isPlainObject(value)) return void 0;
421
+ const output = isPlainObject(value) ? value.output : void 0;
422
+ if (isPlainObject(output) && typeof output.path === "string") {
423
+ const normalized = path.posix.normalize(output.path.replaceAll("\\", "/"));
424
+ if (path.posix.isAbsolute(normalized) || /^[a-z]:/i.test(output.path) || normalized === ".." || normalized.startsWith("../")) return output.path;
425
+ }
426
+ for (const entry of Object.values(value)) {
427
+ const found = findEscapingOutputPath(entry);
428
+ if (found !== void 0) return found;
429
+ }
430
+ }
363
431
  // ../../internals/shared/src/configFile/text.ts
364
432
  /**
365
433
  * A valid JavaScript identifier, so an import name can only ever print as `import { name } from`,
@@ -455,13 +523,15 @@ function isNonEmptyString(value) {
455
523
  }
456
524
  /** Edits cross the wire, so their shape is checked before anything reads them. */
457
525
  function validateEdit(edit) {
458
- const { operation, plugin, config, path, kind, input } = typeof edit === "object" && edit !== null ? edit : {};
526
+ const { operation, plugin, config, path, kind, input, value, options } = typeof edit === "object" && edit !== null ? edit : {};
459
527
  if (typeof operation !== "string" || !OPERATIONS.has(operation)) return `unknown operation ${JSON.stringify(operation)}`;
460
528
  if (config !== void 0 && typeof config !== "string" && !Number.isSafeInteger(config)) return "config must name an entry or give its index";
461
529
  if (operation === ConfigEditOperation.SET_INPUT) return typeof input === "string" && input.trim() !== "" ? void 0 : "the edit names no input";
462
530
  const isOption = OPTION_OPERATIONS.has(operation);
463
531
  const isOutput = OUTPUT_OPERATIONS.has(operation);
464
532
  if (!isOutput && !isNonEmptyString(plugin)) return "the edit names no plugin";
533
+ const escaping = findEscapingOutputPath(operation === ConfigEditOperation.SET_OPTION && Array.isArray(path) ? path.reduceRight((inner, key) => ({ [String(key)]: inner }), value) : options);
534
+ if (escaping !== void 0) return `output.path ${JSON.stringify(escaping)} resolves outside the output folder`;
465
535
  if (kind !== void 0) {
466
536
  if (typeof kind !== "string" || !KINDS.has(kind)) return `unknown kind ${JSON.stringify(kind)}`;
467
537
  const takesKind = operation === ConfigEditOperation.ADD_PLUGIN || operation === ConfigEditOperation.REMOVE_EXTENSION;
@@ -1120,13 +1190,13 @@ function applyEdit({ source, edit, extensions }) {
1120
1190
  function editConfig({ source, edits, extensions = /* @__PURE__ */ new Map() }) {
1121
1191
  let current = source;
1122
1192
  const outcomes = edits.map((edit) => {
1123
- const invalid = validateEdit(edit);
1124
- if (invalid) return {
1125
- edit,
1126
- applied: false,
1127
- reason: invalid
1128
- };
1129
1193
  try {
1194
+ const invalid = validateEdit(edit);
1195
+ if (invalid) return {
1196
+ edit,
1197
+ applied: false,
1198
+ reason: invalid
1199
+ };
1130
1200
  const result = applyEdit({
1131
1201
  source: current,
1132
1202
  edit,
@@ -1363,7 +1433,7 @@ function generationFailure(diagnostics) {
1363
1433
  * Runs one generation and returns the files it produced. The formatter, the linter, and
1364
1434
  * `output.postGenerate` only run with `allowExec`. Throws when any plugin reports an error.
1365
1435
  */
1366
- async function generate({ config, hooks, signal, allowExec }) {
1436
+ async function generate({ config, hooks, signal, allowExec, fileRefs }) {
1367
1437
  const output = allowExec ? config.output : {
1368
1438
  ...config.output,
1369
1439
  format: false,
@@ -1375,7 +1445,8 @@ async function generate({ config, hooks, signal, allowExec }) {
1375
1445
  output
1376
1446
  }, {
1377
1447
  hooks,
1378
- signal
1448
+ signal,
1449
+ fileRefs
1379
1450
  });
1380
1451
  const result = await kubb.generate();
1381
1452
  if (!result.success) throw generationFailure(result.diagnostics);
@@ -1758,7 +1829,7 @@ const NO_BODY = /* @__PURE__ */ new Set([
1758
1829
  304
1759
1830
  ]);
1760
1831
  function notPublic(host) {
1761
- return /* @__PURE__ */ new Error(`${host} is not a public address, so a managed agent does not fetch from it`);
1832
+ return /* @__PURE__ */ new Error(`${host} is not a public address, so this agent does not fetch from it`);
1762
1833
  }
1763
1834
  function createLookup(blocked) {
1764
1835
  return (hostname, options, callback) => {
@@ -1810,8 +1881,8 @@ function request({ url, blocked, signal }) {
1810
1881
  */
1811
1882
  function createPublicFetch(blocked) {
1812
1883
  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");
1884
+ if (typeof input !== "string" && !(input instanceof URL)) throw new TypeError("This agent fetches by URL only");
1885
+ if (init?.method && init.method.toUpperCase() !== "GET") throw new TypeError("This agent only sends GET requests");
1815
1886
  let url = new URL(input);
1816
1887
  for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
1817
1888
  const response = await request({
@@ -1830,7 +1901,7 @@ function createPublicFetch(blocked) {
1830
1901
  }
1831
1902
  /**
1832
1903
  * 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.
1904
+ * A sandbox or managed agent runs one job at a time, so nothing else shares the window.
1834
1905
  */
1835
1906
  async function withPublicFetch(run) {
1836
1907
  const original = globalThis.fetch;
@@ -2103,6 +2174,18 @@ function assertOutputPaths({ plugins, diskPlugins, root, outputPath }) {
2103
2174
  }
2104
2175
  }
2105
2176
  /**
2177
+ * The folders a `$ref` may read local files from on each kind of agent. Studio may have sent the
2178
+ * spec, so a shared agent gets none, and a managed agent only the git checkout it made itself. A
2179
+ * project agent gets its `root` and the folder of the file `input` in its own config. `undefined`
2180
+ * means no limit, which only `allowFileRefs` grants.
2181
+ */
2182
+ function resolveFileRefs({ agentType, allowFileRefs, root, input, checkoutDir }) {
2183
+ if (agentType === "sandbox" || agentType === "global") return [];
2184
+ if (agentType === "managed") return checkoutDir ? [checkoutDir] : [];
2185
+ if (allowFileRefs) return void 0;
2186
+ return typeof input === "string" && getInputKind(input) === "file" ? [root, path.dirname(path.resolve(root, input))] : [root];
2187
+ }
2188
+ /**
2106
2189
  * Re-invokes the factory behind a disk adapter or parser with Studio's options merged over its own.
2107
2190
  * An instance carries live functions (`parse`, `print`, ...) that cannot survive JSON, so Studio's
2108
2191
  * options are a patch, not a replacement, and the factory is found from the disk instance itself: the
@@ -2194,6 +2277,7 @@ function secureUrl({ studioUrl, path, socket = false }) {
2194
2277
  }
2195
2278
  // src/connect.ts
2196
2279
  const HEARTBEAT_INTERVAL_MS = 3e4;
2280
+ const SHARED_AGENT_TYPES = /* @__PURE__ */ new Set(["sandbox", "global"]);
2197
2281
  const MAX_HEARTBEAT_INTERVAL_MS = 6e4;
2198
2282
  const PING_TIMEOUT_MS = 1e4;
2199
2283
  const OPEN_TIMEOUT_MS = 5e3;
@@ -2319,14 +2403,25 @@ var Agent = class extends RpcTarget {
2319
2403
  this.#session = session;
2320
2404
  }
2321
2405
  get #sandbox() {
2322
- return this.#session.info?.sandbox === true;
2406
+ return SHARED_AGENT_TYPES.has(this.#options.agentType) || this.#session.info?.sandbox === true;
2323
2407
  }
2324
2408
  get #managed() {
2325
- return this.#session.info?.managed === true;
2409
+ return this.#options.agentType === "managed" || this.#session.info?.managed === true;
2410
+ }
2411
+ get #agentType() {
2412
+ if (this.#sandbox) return "sandbox";
2413
+ if (this.#managed) return "managed";
2414
+ return this.#options.agentType;
2326
2415
  }
2327
2416
  get #permissions() {
2328
- const { permissions } = this.#options;
2329
- return this.#sandbox ? {
2417
+ const { permissions, agentType } = this.#options;
2418
+ const sandbox = SHARED_AGENT_TYPES.has(agentType);
2419
+ if (this.#managed) return {
2420
+ ...permissions,
2421
+ allowFileRefs: false
2422
+ };
2423
+ if (!this.#sandbox) return permissions;
2424
+ return {
2330
2425
  ...permissions,
2331
2426
  allowWrite: false,
2332
2427
  allowConfigEdit: false,
@@ -2334,9 +2429,10 @@ var Agent = class extends RpcTarget {
2334
2429
  allowUpdate: false,
2335
2430
  allowRemove: false,
2336
2431
  allowSaveInput: false,
2337
- allowRead: true,
2338
- allowReadAst: true
2339
- } : permissions;
2432
+ allowFileRefs: false,
2433
+ allowRead: sandbox || permissions.allowRead,
2434
+ allowReadAst: sandbox || permissions.allowReadAst
2435
+ };
2340
2436
  }
2341
2437
  get #generations() {
2342
2438
  this.#store ??= createGenerationStore({
@@ -2428,6 +2524,13 @@ var Agent = class extends RpcTarget {
2428
2524
  });
2429
2525
  }
2430
2526
  this.#session.connected.resolve(info);
2527
+ const { privateKey } = this.#options;
2528
+ const { challenge } = info;
2529
+ const signature = privateKey && typeof challenge === "string" && challenge && challenge.length <= 1024 ? signAgentPayload({
2530
+ privateKey,
2531
+ context: AgentSignatureContext.CONNECT,
2532
+ payload: challenge
2533
+ }) : void 0;
2431
2534
  return {
2432
2535
  versions: {
2433
2536
  kubb: version,
@@ -2440,7 +2543,8 @@ var Agent = class extends RpcTarget {
2440
2543
  extensions: [...extensions.values()],
2441
2544
  configs: entries
2442
2545
  },
2443
- permissions: this.#permissions
2546
+ permissions: this.#permissions,
2547
+ ...signature && { signature }
2444
2548
  };
2445
2549
  }
2446
2550
  async #readDiskOutput(config) {
@@ -2558,7 +2662,8 @@ var Agent = class extends RpcTarget {
2558
2662
  });
2559
2663
  const activePlugins = plugins ?? config.plugins;
2560
2664
  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, {
2665
+ const managedInput = this.#managed ? studioInput ?? config.input : void 0;
2666
+ const checkout = typeof managedInput === "string" && getInputKind(managedInput) === "git" ? await checkoutGitInput(managedInput, signal, {
2562
2667
  publicOnly: true,
2563
2668
  authorization: input.gitAuth?.authorization
2564
2669
  }).catch((error) => this.#refuse({
@@ -2584,9 +2689,16 @@ var Agent = class extends RpcTarget {
2584
2689
  },
2585
2690
  hooks: this.#options.hooks,
2586
2691
  signal,
2587
- allowExec: this.#permissions.allowWrite && this.#permissions.allowExec
2692
+ allowExec: this.#permissions.allowWrite && this.#permissions.allowExec,
2693
+ fileRefs: resolveFileRefs({
2694
+ agentType: this.#agentType,
2695
+ allowFileRefs: this.#permissions.allowFileRefs,
2696
+ root: this.#options.root,
2697
+ input: config.input,
2698
+ checkoutDir: checkout?.dir
2699
+ })
2588
2700
  });
2589
- const files = await (this.#managed ? withPublicFetch(run) : run()).catch(async (error) => {
2701
+ const files = await (this.#sandbox || this.#managed ? withPublicFetch(run) : run()).catch(async (error) => {
2590
2702
  await this.#generations.drop(jobId);
2591
2703
  await this.#logCommand("generate", getErrorMessage(error), input.requestedBy, true);
2592
2704
  throw error;
@@ -2681,7 +2793,7 @@ var Agent = class extends RpcTarget {
2681
2793
  /**
2682
2794
  * Readies a `set-input` edit for the config file: a document is pointed at `openapi.yaml` (`openapi.json`
2683
2795
  * 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.
2796
+ * A managed agent refuses a file path, as in a generation. Every agent refuses a file path outside the project.
2685
2797
  */
2686
2798
  async #keepInput(edit) {
2687
2799
  if (edit?.operation !== ConfigEditOperation.SET_INPUT || typeof edit.input !== "string" || !edit.input.trim()) return edit;
@@ -2694,6 +2806,7 @@ var Agent = class extends RpcTarget {
2694
2806
  }
2695
2807
  const kind = getInputKind(edit.input);
2696
2808
  if (this.#managed && !MANAGED_INPUT_KINDS.has(kind)) return { reason: AgentMessage.MANAGED_INPUT_KIND };
2809
+ 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
2810
  if (kind !== "inline") return edit;
2698
2811
  const fileName = `openapi${edit.config === void 0 || edit.config === 0 ? "" : `-${String(edit.config).replace(/[^\w.-]/g, "-")}`}.${isJson(edit.input) ? "json" : "yaml"}`;
2699
2812
  return {
@@ -2980,7 +3093,13 @@ const openWebSocketRpc = ({ url, token, instanceId, agent }) => {
2980
3093
  };
2981
3094
  };
2982
3095
  async function runSession({ options, openRpc, url, instanceId }) {
2983
- const { hooks, signal, heartbeatInterval, token, studioUrl, version: version$2 } = options;
3096
+ const { hooks, signal, heartbeatInterval, studioUrl, version: version$2 } = options;
3097
+ const token = typeof options.token === "function" ? await options.token() : options.token;
3098
+ if (signal?.aborted) return {
3099
+ code: 1e3,
3100
+ reason: "",
3101
+ connected: false
3102
+ };
2984
3103
  const session = {
2985
3104
  connected: Promise.withResolvers(),
2986
3105
  closed: false
@@ -3104,6 +3223,7 @@ async function runAgent({ options, openRpc }) {
3104
3223
  ...options,
3105
3224
  studioUrl: options.studioUrl ?? "https://kubb.studio",
3106
3225
  root,
3226
+ agentType: options.agentType ?? "user",
3107
3227
  configFile: path.resolve(root, options.configPath),
3108
3228
  permissions: {
3109
3229
  allowWrite: false,
@@ -3112,6 +3232,7 @@ async function runAgent({ options, openRpc }) {
3112
3232
  allowUpdate: false,
3113
3233
  allowRemove: false,
3114
3234
  allowSaveInput: false,
3235
+ allowFileRefs: false,
3115
3236
  allowExec: false,
3116
3237
  allowRead: false,
3117
3238
  allowReadAst: false,
@@ -3206,7 +3327,7 @@ var PairingDeniedError = class extends Error {
3206
3327
  /**
3207
3328
  * Asks Studio for a pairing code, sending the hashed machine id with it.
3208
3329
  */
3209
- async function startPairing({ studioUrl = defaultStudioUrl, type, name, hostname, machineId, signal }) {
3330
+ async function startPairing({ studioUrl = defaultStudioUrl, type, name, hostname, machineId, privateKey, signal }) {
3210
3331
  try {
3211
3332
  const pairing = await ofetch(secureUrl({
3212
3333
  studioUrl,
@@ -3218,7 +3339,8 @@ async function startPairing({ studioUrl = defaultStudioUrl, type, name, hostname
3218
3339
  name,
3219
3340
  hostname,
3220
3341
  machine_token: hash("sha256", machineId),
3221
- agent_kind: type === "cli" ? void 0 : type
3342
+ agent_kind: type === "cli" ? void 0 : type,
3343
+ public_key: privateKey ? getAgentPublicKey(privateKey) : void 0
3222
3344
  },
3223
3345
  signal
3224
3346
  });
@@ -3321,6 +3443,63 @@ async function pairAgent({ onCode, onRetry, maxAttempts = 1, ...options }) {
3321
3443
  }
3322
3444
  }
3323
3445
  }
3446
+ const REFRESH_TIMEOUT_MS = 15e3;
3447
+ /**
3448
+ * Trades the agent's token for a new one. The old token stops working at once, so store the new
3449
+ * one first. Resolves `null` when there is nothing to refresh, and rejects with
3450
+ * {@link InvalidAgentTokenError} when the token is refused.
3451
+ */
3452
+ async function refreshAgentToken({ studioUrl = defaultStudioUrl, token, machineId, privateKey, signal, timeout = REFRESH_TIMEOUT_MS }) {
3453
+ const deadline = AbortSignal.timeout(timeout);
3454
+ const signedAt = Date.now();
3455
+ const proof = privateKey ? {
3456
+ signed_at: signedAt,
3457
+ signature: signAgentPayload({
3458
+ privateKey,
3459
+ context: AgentSignatureContext.TOKEN_REFRESH,
3460
+ payload: getTokenRefreshPayload({
3461
+ token,
3462
+ signedAt
3463
+ })
3464
+ })
3465
+ } : void 0;
3466
+ const { status, _data } = await ofetch.raw(secureUrl({
3467
+ studioUrl,
3468
+ path: "/api/agent/token/refresh"
3469
+ }).href, {
3470
+ method: "POST",
3471
+ headers: { Authorization: `Bearer ${token}` },
3472
+ body: {
3473
+ machine_id: machineId,
3474
+ ...proof
3475
+ },
3476
+ signal: signal ? AbortSignal.any([signal, deadline]) : deadline,
3477
+ ignoreResponseError: true,
3478
+ retry: 0
3479
+ }).catch((error) => {
3480
+ if (deadline.aborted && !signal?.aborted) throw new Diagnostics.Error({
3481
+ code: Diagnostics.code.inputRequestFailed,
3482
+ severity: "error",
3483
+ message: `Kubb Studio did not answer the token refresh within ${timeout} ms`,
3484
+ help: "The token is unchanged. Try again later."
3485
+ });
3486
+ throw error;
3487
+ });
3488
+ if (status === 404 || status === 409) return null;
3489
+ if (status === 401) throw new InvalidAgentTokenError(studioUrl);
3490
+ if (status < 200 || status >= 300) throw new Diagnostics.Error({
3491
+ code: Diagnostics.code.inputRequestFailed,
3492
+ severity: "error",
3493
+ message: `Kubb Studio answered the token refresh with status ${status}`,
3494
+ help: "The token is unchanged. Try again later."
3495
+ });
3496
+ if (typeof _data?.token !== "string" || !_data.token) throw new Diagnostics.Error({
3497
+ code: Diagnostics.code.unknown,
3498
+ severity: "error",
3499
+ message: "Kubb Studio answered the token refresh without a token"
3500
+ });
3501
+ return _data.token;
3502
+ }
3324
3503
  // src/snapshot.ts
3325
3504
  const UPLOAD_TIMEOUT_MS = 12e4;
3326
3505
  const BUNDLED_DEPENDENCIES = ["@kubb/plugin-barrel"];
@@ -3595,6 +3774,6 @@ async function createSnapshot({ studioUrl = defaultStudioUrl, apiKey, configs, h
3595
3774
  });
3596
3775
  return _data.snapshot;
3597
3776
  }
3598
- export { IncompatibleAgentError, InvalidAgentTokenError, PairingCanceledError, PairingDeniedError, PairingExpiredError, connectAgent, createSnapshot, defaultStudioUrl, editConfig, editConfigFile, pairAgent };
3777
+ export { IncompatibleAgentError, InvalidAgentTokenError, PairingCanceledError, PairingDeniedError, PairingExpiredError, connectAgent, createSnapshot, defaultStudioUrl, editConfig, editConfigFile, generateAgentKey, getAgentPublicKey, getTokenRefreshPayload, pairAgent, refreshAgentToken, signAgentPayload, verifyAgentSignature };
3599
3778
 
3600
3779
  //# sourceMappingURL=index.js.map