@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/README.md CHANGED
@@ -37,71 +37,6 @@ and runs this for you.
37
37
  npm install @kubb/studio
38
38
  ```
39
39
 
40
- ## Usage
41
-
42
- ```typescript
43
- import { Hookable, type KubbHooks } from '@kubb/core'
44
- import { connectAgent, InvalidAgentTokenError, pairAgent } from '@kubb/studio'
45
-
46
- const hooks = new Hookable<KubbHooks>()
47
- hooks.hook('studio:connected', ({ agentSlug }) => console.log(`Connected as ${agentSlug}`))
48
- hooks.hook('studio:warn', ({ message }) => console.warn(message))
49
-
50
- let token = await readStoredToken()
51
-
52
- for (;;) {
53
- token ??= (await pairAgent({ type: 'cli', name: 'my-project', hostname, machineId, onCode })).token
54
- try {
55
- // Resolves on shutdown, rejects when Studio refuses the token.
56
- await connectAgent({ token, configPath: 'kubb.config.ts', loadConfig, version: '1.0.0', hooks, signal })
57
- break
58
- } catch (error) {
59
- if (!(error instanceof InvalidAgentTokenError)) throw error
60
- token = undefined
61
- }
62
- }
63
- ```
64
-
65
- The runtime discovers nothing on its own. The host passes the token, the config loader, its own
66
- version, and a hook emitter, and keeps its own credentials. That is what lets one runtime serve a CLI
67
- running in a developer's project and a container running a fixed plugin set.
68
-
69
- ## Source layout
70
-
71
- | File | What it owns |
72
- | ---------------- | -------------------------------------------------------------------------------- |
73
- | `protocol.ts` | The wire contract Studio compiles against, published as `@kubb/studio/protocol`. |
74
- | `connect.ts` | `connectAgent`: the socket loop and the `Agent` that serves Studio's calls. |
75
- | `pair.ts` | `pairAgent`: RFC 8628 device pairing. |
76
- | `snapshot.ts` | `createSnapshot` for CI, and packing a generation into an npm tarball. |
77
- | `generations.ts` | Running a generation and keeping its files and AST for `readFiles`/`readInput`. |
78
- | `diff.ts` | The paged line diff `readDiff` serves between two kept sets. |
79
-
80
- ## Connection
81
-
82
- `connectAgent` opens `wss://<studio>/api/agent/socket` with the agent's bearer token and an
83
- `x-kubb-instance-id` header. Studio calls `connect(info)` as the first RPC call. `info` says whether
84
- the agent is a sandbox and carries its slug and Studio's version. From then on the agent pings every
85
- 30 seconds, and Studio schedules one job at a time on the socket.
86
-
87
- With `allowRead`, the connect payload includes the current `output.path` file list. Studio reads
88
- file contents from disk through `readFiles` when a user opens a file. Sandbox agents have no disk
89
- output, and output paths outside the project root are excluded.
90
-
91
- Studio ends a socket on purpose with one of these close codes:
92
-
93
- | Code | Meaning | `connectAgent` |
94
- | ------ | --------------------------------------------- | ------------------------------------- |
95
- | `4001` | The token is invalid, expired, or revoked | Rejects with `InvalidAgentTokenError` |
96
- | `4002` | Another process of the same agent took over | Resolves |
97
- | `4003` | The agent is older than Studio accepts | Rejects with `IncompatibleAgentError` |
98
- | other | An ordinary drop, `1011` for a Studio failure | Reconnects with jittered backoff |
99
-
100
- Everything the runtime has to say goes through the `hooks` emitter: `studio:connected`,
101
- `studio:disconnected`, `studio:reconnecting`, `studio:command`, `studio:warn`, and `studio:error`,
102
- next to the `kubb:*` hooks of each generation. When a request is refused for a missing permission,
103
- `studio:warn` names it as `permission`, so the host can add its own remedy.
104
-
105
40
  ## Permissions
106
41
 
107
42
  Every permission is off by default, and each covers one trust boundary:
@@ -117,45 +52,6 @@ Every permission is off by default, and each covers one trust boundary:
117
52
 
118
53
  A sandbox never writes or edits config. A sandbox the host declares with `agentType: 'sandbox'` or `'global'` always allows reads.
119
54
 
120
- ## Pairing
121
-
122
- No host starts with a token, so each one pairs over
123
- [RFC 8628](https://www.rfc-editor.org/rfc/rfc8628.html) device authorization. `pairAgent` asks Studio
124
- for a code, hands it to `onCode` to show, and polls until someone approves it in the browser.
125
-
126
- `machineId` is a secret the host keeps for the machine. Studio stores its hash, so the same machine
127
- pairing again rotates one agent's token instead of creating a second agent. Studio records the
128
- `type` with the agent. `cli` is `kubb studio`, which any member can approve. `user` and `sandbox`
129
- are the Docker image, run normally or as a sandbox. Only an admin can approve them. A denial
130
- throws `PairingDeniedError`, an expired code `PairingExpiredError`, and an aborted `signal`
131
- `PairingCanceledError`.
132
-
133
- ## CI snapshots
134
-
135
- `createSnapshot` generates the project like `kubb generate`, with the formatter, the linter, and
136
- `output.postGenerate`. It then packs the output as an npm tarball and sends one
137
- `POST /api/snapshots` with the organization CI API key as `x-api-key`.
138
-
139
- ```typescript
140
- import { createSnapshot } from '@kubb/studio'
141
-
142
- const snapshot = await createSnapshot({
143
- apiKey: process.env.KUBB_TOKEN!,
144
- configs,
145
- id: 'gh:123:pr-4',
146
- name: 'acme/api#4',
147
- packageName: '@acme/api',
148
- version: '1.0.0',
149
- commit: process.env.GITHUB_SHA,
150
- baseId: 'gh:123:refs/heads/main',
151
- })
152
- ```
153
-
154
- Snapshots that share an `id` belong to one CI agent in Studio. `changes` lists the files added,
155
- changed, and removed since that agent's previous snapshot of the package. With `baseId`,
156
- `branchChanges` compares against the latest snapshot of the CI agent with that id, such as the base
157
- branch's.
158
-
159
55
  ## Supporting Kubb
160
56
 
161
57
  Kubb is an open source project, and its development is funded entirely by sponsors. If you would like to become a sponsor, please consider:
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-CmX5XTPc.cjs");
23
+ const require_protocol = require("./protocol-D-n2Uczq.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");
@@ -50,6 +50,58 @@ node_net = __toESM(node_net, 1);
50
50
  let node_stream = require("node:stream");
51
51
  let ofetch = require("ofetch");
52
52
  let node_zlib = require("node:zlib");
53
+ // src/agentKey.ts
54
+ function signedBytes({ context, payload }) {
55
+ return Buffer.from(`${context}\n${payload}`, "utf8");
56
+ }
57
+ /**
58
+ * Creates the agent's Ed25519 key as a PKCS #8 PEM string, to store with the token.
59
+ */
60
+ function generateAgentKey() {
61
+ return (0, node_crypto.generateKeyPairSync)("ed25519").privateKey.export({
62
+ format: "pem",
63
+ type: "pkcs8"
64
+ }).toString();
65
+ }
66
+ /**
67
+ * Returns the raw 32-byte public key of `privateKey`, base64url without padding.
68
+ */
69
+ function getAgentPublicKey(privateKey) {
70
+ return (0, node_crypto.createPublicKey)(privateKey).export({ format: "jwk" }).x;
71
+ }
72
+ /**
73
+ * Signs `payload` for `context` and returns the Ed25519 signature in base64url.
74
+ */
75
+ function signAgentPayload({ privateKey, context, payload }) {
76
+ return (0, node_crypto.sign)(null, signedBytes({
77
+ context,
78
+ payload
79
+ }), privateKey).toString("base64url");
80
+ }
81
+ /**
82
+ * Checks a {@link signAgentPayload} signature. Malformed input returns `false` and never throws.
83
+ */
84
+ function verifyAgentSignature({ publicKey, context, payload, signature }) {
85
+ try {
86
+ const key = (0, node_crypto.createPublicKey)({
87
+ key: {
88
+ kty: "OKP",
89
+ crv: "Ed25519",
90
+ x: publicKey
91
+ },
92
+ format: "jwk"
93
+ });
94
+ return (0, node_crypto.verify)(null, signedBytes({
95
+ context,
96
+ payload
97
+ }), key, Buffer.from(signature, "base64url"));
98
+ } catch {
99
+ return false;
100
+ }
101
+ }
102
+ function getTokenRefreshPayload({ token, signedAt }) {
103
+ return `${signedAt}\n${(0, node_crypto.hash)("sha256", token)}`;
104
+ }
53
105
  // ../../internals/utils/src/promise.ts
54
106
  /**
55
107
  * Returns the value cached under `key` in `store`, computing and storing it on the first call.
@@ -251,7 +303,7 @@ function isPathInside(path, parent) {
251
303
  return rel !== "" && !rel.startsWith("..") && !(0, node_path.isAbsolute)(rel);
252
304
  }
253
305
  // package.json
254
- var version = "5.19.1";
306
+ var version = "5.20.0";
255
307
  // ../../internals/shared/src/constants.ts
256
308
  /**
257
309
  * Extensions `kubb` ships at its own version, so they count as installed without being a direct
@@ -2500,6 +2552,13 @@ var Agent = class extends capnweb.RpcTarget {
2500
2552
  });
2501
2553
  }
2502
2554
  this.#session.connected.resolve(info);
2555
+ const { privateKey } = this.#options;
2556
+ const { challenge } = info;
2557
+ const signature = privateKey && typeof challenge === "string" && challenge && challenge.length <= 1024 ? signAgentPayload({
2558
+ privateKey,
2559
+ context: require_protocol.AgentSignatureContext.CONNECT,
2560
+ payload: challenge
2561
+ }) : void 0;
2503
2562
  return {
2504
2563
  versions: {
2505
2564
  kubb: version,
@@ -2512,7 +2571,8 @@ var Agent = class extends capnweb.RpcTarget {
2512
2571
  extensions: [...extensions.values()],
2513
2572
  configs: entries
2514
2573
  },
2515
- permissions: this.#permissions
2574
+ permissions: this.#permissions,
2575
+ ...signature && { signature }
2516
2576
  };
2517
2577
  }
2518
2578
  async #readDiskOutput(config) {
@@ -3061,7 +3121,13 @@ const openWebSocketRpc = ({ url, token, instanceId, agent }) => {
3061
3121
  };
3062
3122
  };
3063
3123
  async function runSession({ options, openRpc, url, instanceId }) {
3064
- const { hooks, signal, heartbeatInterval, token, studioUrl, version: version$2 } = options;
3124
+ const { hooks, signal, heartbeatInterval, studioUrl, version: version$2 } = options;
3125
+ const token = typeof options.token === "function" ? await options.token() : options.token;
3126
+ if (signal?.aborted) return {
3127
+ code: 1e3,
3128
+ reason: "",
3129
+ connected: false
3130
+ };
3065
3131
  const session = {
3066
3132
  connected: Promise.withResolvers(),
3067
3133
  closed: false
@@ -3289,7 +3355,7 @@ var PairingDeniedError = class extends Error {
3289
3355
  /**
3290
3356
  * Asks Studio for a pairing code, sending the hashed machine id with it.
3291
3357
  */
3292
- async function startPairing({ studioUrl = defaultStudioUrl, type, name, hostname, machineId, signal }) {
3358
+ async function startPairing({ studioUrl = defaultStudioUrl, type, name, hostname, machineId, privateKey, signal }) {
3293
3359
  try {
3294
3360
  const pairing = await (0, ofetch.ofetch)(secureUrl({
3295
3361
  studioUrl,
@@ -3301,7 +3367,8 @@ async function startPairing({ studioUrl = defaultStudioUrl, type, name, hostname
3301
3367
  name,
3302
3368
  hostname,
3303
3369
  machine_token: (0, node_crypto.hash)("sha256", machineId),
3304
- agent_kind: type === "cli" ? void 0 : type
3370
+ agent_kind: type === "cli" ? void 0 : type,
3371
+ public_key: privateKey ? getAgentPublicKey(privateKey) : void 0
3305
3372
  },
3306
3373
  signal
3307
3374
  });
@@ -3404,6 +3471,63 @@ async function pairAgent({ onCode, onRetry, maxAttempts = 1, ...options }) {
3404
3471
  }
3405
3472
  }
3406
3473
  }
3474
+ const REFRESH_TIMEOUT_MS = 15e3;
3475
+ /**
3476
+ * Trades the agent's token for a new one. The old token stops working at once, so store the new
3477
+ * one first. Resolves `null` when there is nothing to refresh, and rejects with
3478
+ * {@link InvalidAgentTokenError} when the token is refused.
3479
+ */
3480
+ async function refreshAgentToken({ studioUrl = defaultStudioUrl, token, machineId, privateKey, signal, timeout = REFRESH_TIMEOUT_MS }) {
3481
+ const deadline = AbortSignal.timeout(timeout);
3482
+ const signedAt = Date.now();
3483
+ const proof = privateKey ? {
3484
+ signed_at: signedAt,
3485
+ signature: signAgentPayload({
3486
+ privateKey,
3487
+ context: require_protocol.AgentSignatureContext.TOKEN_REFRESH,
3488
+ payload: getTokenRefreshPayload({
3489
+ token,
3490
+ signedAt
3491
+ })
3492
+ })
3493
+ } : void 0;
3494
+ const { status, _data } = await ofetch.ofetch.raw(secureUrl({
3495
+ studioUrl,
3496
+ path: "/api/agent/token/refresh"
3497
+ }).href, {
3498
+ method: "POST",
3499
+ headers: { Authorization: `Bearer ${token}` },
3500
+ body: {
3501
+ machine_id: machineId,
3502
+ ...proof
3503
+ },
3504
+ signal: signal ? AbortSignal.any([signal, deadline]) : deadline,
3505
+ ignoreResponseError: true,
3506
+ retry: 0
3507
+ }).catch((error) => {
3508
+ if (deadline.aborted && !signal?.aborted) throw new _kubb_core.Diagnostics.Error({
3509
+ code: _kubb_core.Diagnostics.code.inputRequestFailed,
3510
+ severity: "error",
3511
+ message: `Kubb Studio did not answer the token refresh within ${timeout} ms`,
3512
+ help: "The token is unchanged. Try again later."
3513
+ });
3514
+ throw error;
3515
+ });
3516
+ if (status === 404 || status === 409) return null;
3517
+ if (status === 401) throw new InvalidAgentTokenError(studioUrl);
3518
+ if (status < 200 || status >= 300) throw new _kubb_core.Diagnostics.Error({
3519
+ code: _kubb_core.Diagnostics.code.inputRequestFailed,
3520
+ severity: "error",
3521
+ message: `Kubb Studio answered the token refresh with status ${status}`,
3522
+ help: "The token is unchanged. Try again later."
3523
+ });
3524
+ if (typeof _data?.token !== "string" || !_data.token) throw new _kubb_core.Diagnostics.Error({
3525
+ code: _kubb_core.Diagnostics.code.unknown,
3526
+ severity: "error",
3527
+ message: "Kubb Studio answered the token refresh without a token"
3528
+ });
3529
+ return _data.token;
3530
+ }
3407
3531
  // src/snapshot.ts
3408
3532
  const UPLOAD_TIMEOUT_MS = 12e4;
3409
3533
  const BUNDLED_DEPENDENCIES = ["@kubb/plugin-barrel"];
@@ -3688,6 +3812,12 @@ exports.createSnapshot = createSnapshot;
3688
3812
  exports.defaultStudioUrl = defaultStudioUrl;
3689
3813
  exports.editConfig = editConfig;
3690
3814
  exports.editConfigFile = editConfigFile;
3815
+ exports.generateAgentKey = generateAgentKey;
3816
+ exports.getAgentPublicKey = getAgentPublicKey;
3817
+ exports.getTokenRefreshPayload = getTokenRefreshPayload;
3691
3818
  exports.pairAgent = pairAgent;
3819
+ exports.refreshAgentToken = refreshAgentToken;
3820
+ exports.signAgentPayload = signAgentPayload;
3821
+ exports.verifyAgentSignature = verifyAgentSignature;
3692
3822
 
3693
3823
  //# sourceMappingURL=index.cjs.map