@kubb/studio 5.19.1 → 5.20.0

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 { 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";
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.
@@ -204,6 +237,10 @@ type StartPairingOptions = {
204
237
  * the same machine pairing again rotates one agent's token instead of creating a second agent.
205
238
  */
206
239
  machineId: string;
240
+ /**
241
+ * The agent key from `generateAgentKey`. Only its public half is sent.
242
+ */
243
+ privateKey?: string;
207
244
  /**
208
245
  * Aborting this cancels the request in flight and rejects with {@link PairingCanceledError}.
209
246
  */
@@ -224,6 +261,31 @@ type PairAgentOptions = StartPairingOptions & {
224
261
  * Pairs this machine with Studio: asks for a code, hands it to the host to show, and waits for approval.
225
262
  */
226
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>;
227
289
  type CreateSnapshotOptions = Omit<SnapshotUploadMetadata, 'hashes' | 'peerDependencies'> & {
228
290
  studioUrl?: string;
229
291
  /**
package/dist/index.d.ts CHANGED
@@ -1,5 +1,34 @@
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";
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.
@@ -204,6 +237,10 @@ type StartPairingOptions = {
204
237
  * the same machine pairing again rotates one agent's token instead of creating a second agent.
205
238
  */
206
239
  machineId: string;
240
+ /**
241
+ * The agent key from `generateAgentKey`. Only its public half is sent.
242
+ */
243
+ privateKey?: string;
207
244
  /**
208
245
  * Aborting this cancels the request in flight and rejects with {@link PairingCanceledError}.
209
246
  */
@@ -224,6 +261,31 @@ type PairAgentOptions = StartPairingOptions & {
224
261
  * Pairs this machine with Studio: asks for a code, hands it to the host to show, and waits for approval.
225
262
  */
226
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>;
227
289
  type CreateSnapshotOptions = Omit<SnapshotUploadMetadata, 'hashes' | 'peerDependencies'> & {
228
290
  studioUrl?: string;
229
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-xk8P0Zhv.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.1";
278
+ var version = "5.20.0";
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
@@ -2472,6 +2524,13 @@ var Agent = class extends RpcTarget {
2472
2524
  });
2473
2525
  }
2474
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;
2475
2534
  return {
2476
2535
  versions: {
2477
2536
  kubb: version,
@@ -2484,7 +2543,8 @@ var Agent = class extends RpcTarget {
2484
2543
  extensions: [...extensions.values()],
2485
2544
  configs: entries
2486
2545
  },
2487
- permissions: this.#permissions
2546
+ permissions: this.#permissions,
2547
+ ...signature && { signature }
2488
2548
  };
2489
2549
  }
2490
2550
  async #readDiskOutput(config) {
@@ -3033,7 +3093,13 @@ const openWebSocketRpc = ({ url, token, instanceId, agent }) => {
3033
3093
  };
3034
3094
  };
3035
3095
  async function runSession({ options, openRpc, url, instanceId }) {
3036
- 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
+ };
3037
3103
  const session = {
3038
3104
  connected: Promise.withResolvers(),
3039
3105
  closed: false
@@ -3261,7 +3327,7 @@ var PairingDeniedError = class extends Error {
3261
3327
  /**
3262
3328
  * Asks Studio for a pairing code, sending the hashed machine id with it.
3263
3329
  */
3264
- async function startPairing({ studioUrl = defaultStudioUrl, type, name, hostname, machineId, signal }) {
3330
+ async function startPairing({ studioUrl = defaultStudioUrl, type, name, hostname, machineId, privateKey, signal }) {
3265
3331
  try {
3266
3332
  const pairing = await ofetch(secureUrl({
3267
3333
  studioUrl,
@@ -3273,7 +3339,8 @@ async function startPairing({ studioUrl = defaultStudioUrl, type, name, hostname
3273
3339
  name,
3274
3340
  hostname,
3275
3341
  machine_token: hash("sha256", machineId),
3276
- agent_kind: type === "cli" ? void 0 : type
3342
+ agent_kind: type === "cli" ? void 0 : type,
3343
+ public_key: privateKey ? getAgentPublicKey(privateKey) : void 0
3277
3344
  },
3278
3345
  signal
3279
3346
  });
@@ -3376,6 +3443,63 @@ async function pairAgent({ onCode, onRetry, maxAttempts = 1, ...options }) {
3376
3443
  }
3377
3444
  }
3378
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
+ }
3379
3503
  // src/snapshot.ts
3380
3504
  const UPLOAD_TIMEOUT_MS = 12e4;
3381
3505
  const BUNDLED_DEPENDENCIES = ["@kubb/plugin-barrel"];
@@ -3650,6 +3774,6 @@ async function createSnapshot({ studioUrl = defaultStudioUrl, apiKey, configs, h
3650
3774
  });
3651
3775
  return _data.snapshot;
3652
3776
  }
3653
- 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 };
3654
3778
 
3655
3779
  //# sourceMappingURL=index.js.map