@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/README.md +2 -105
- package/dist/index.cjs +215 -30
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +71 -3
- package/dist/index.d.ts +71 -3
- package/dist/index.js +211 -32
- package/dist/index.js.map +1 -1
- package/dist/{protocol-B6oWLc7W.js → protocol-BYLMyS9H.js} +11 -2
- package/dist/{protocol-B6oWLc7W.js.map → protocol-BYLMyS9H.js.map} +1 -1
- package/dist/{protocol-f2YAAGLi.d.cts → protocol-CgearBUc.d.cts} +39 -5
- package/dist/{protocol-f2YAAGLi.d.ts → protocol-CgearBUc.d.ts} +39 -5
- package/dist/{protocol-B4wWGPon.cjs → protocol-D-n2Uczq.cjs} +22 -1
- package/dist/{protocol-B4wWGPon.cjs.map → protocol-D-n2Uczq.cjs.map} +1 -1
- package/dist/protocol.cjs +3 -1
- package/dist/protocol.d.cts +2 -2
- package/dist/protocol.d.ts +2 -2
- package/dist/protocol.js +1 -1
- package/package.json +4 -4
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:
|
|
@@ -113,47 +48,9 @@ Every permission is off by default, and each covers one trust boundary:
|
|
|
113
48
|
| `allowConfigEdit` | Studio may change plugin options in `kubb.config.ts`. |
|
|
114
49
|
| `allowRead` | Studio may read existing output files and the files a generation produced. |
|
|
115
50
|
| `allowReadAst` | Studio may read back the parsed spec (the Kubb AST). |
|
|
51
|
+
| `allowFileRefs` | A `$ref` in the spec may read a local file outside the project. |
|
|
116
52
|
|
|
117
|
-
A sandbox never writes or edits config
|
|
118
|
-
|
|
119
|
-
## Pairing
|
|
120
|
-
|
|
121
|
-
No host starts with a token, so each one pairs over
|
|
122
|
-
[RFC 8628](https://www.rfc-editor.org/rfc/rfc8628.html) device authorization. `pairAgent` asks Studio
|
|
123
|
-
for a code, hands it to `onCode` to show, and polls until someone approves it in the browser.
|
|
124
|
-
|
|
125
|
-
`machineId` is a secret the host keeps for the machine. Studio stores its hash, so the same machine
|
|
126
|
-
pairing again rotates one agent's token instead of creating a second agent. Studio records the
|
|
127
|
-
`type` with the agent. `cli` is `kubb studio`, which any member can approve. `user` and `sandbox`
|
|
128
|
-
are the Docker image, run normally or as a sandbox. Only an admin can approve them. A denial
|
|
129
|
-
throws `PairingDeniedError`, an expired code `PairingExpiredError`, and an aborted `signal`
|
|
130
|
-
`PairingCanceledError`.
|
|
131
|
-
|
|
132
|
-
## CI snapshots
|
|
133
|
-
|
|
134
|
-
`createSnapshot` generates the project like `kubb generate`, with the formatter, the linter, and
|
|
135
|
-
`output.postGenerate`. It then packs the output as an npm tarball and sends one
|
|
136
|
-
`POST /api/snapshots` with the organization CI API key as `x-api-key`.
|
|
137
|
-
|
|
138
|
-
```typescript
|
|
139
|
-
import { createSnapshot } from '@kubb/studio'
|
|
140
|
-
|
|
141
|
-
const snapshot = await createSnapshot({
|
|
142
|
-
apiKey: process.env.KUBB_TOKEN!,
|
|
143
|
-
configs,
|
|
144
|
-
id: 'gh:123:pr-4',
|
|
145
|
-
name: 'acme/api#4',
|
|
146
|
-
packageName: '@acme/api',
|
|
147
|
-
version: '1.0.0',
|
|
148
|
-
commit: process.env.GITHUB_SHA,
|
|
149
|
-
baseId: 'gh:123:refs/heads/main',
|
|
150
|
-
})
|
|
151
|
-
```
|
|
152
|
-
|
|
153
|
-
Snapshots that share an `id` belong to one CI agent in Studio. `changes` lists the files added,
|
|
154
|
-
changed, and removed since that agent's previous snapshot of the package. With `baseId`,
|
|
155
|
-
`branchChanges` compares against the latest snapshot of the CI agent with that id, such as the base
|
|
156
|
-
branch's.
|
|
53
|
+
A sandbox never writes or edits config. A sandbox the host declares with `agentType: 'sandbox'` or `'global'` always allows reads.
|
|
157
54
|
|
|
158
55
|
## Supporting Kubb
|
|
159
56
|
|
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-
|
|
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.
|
|
306
|
+
var version = "5.19.2";
|
|
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
|
|
@@ -388,6 +440,22 @@ function isOutputValue({ key, value }) {
|
|
|
388
440
|
function pickOutput(output) {
|
|
389
441
|
return Object.fromEntries(Object.entries(output).filter(([key]) => isOutputKey(key)));
|
|
390
442
|
}
|
|
443
|
+
/**
|
|
444
|
+
* Returns the first `output.path` in `value`, at any depth (`override` entries included), that is
|
|
445
|
+
* absolute or climbs out of the folder it resolves against.
|
|
446
|
+
*/
|
|
447
|
+
function findEscapingOutputPath(value) {
|
|
448
|
+
if (!Array.isArray(value) && !isPlainObject(value)) return void 0;
|
|
449
|
+
const output = isPlainObject(value) ? value.output : void 0;
|
|
450
|
+
if (isPlainObject(output) && typeof output.path === "string") {
|
|
451
|
+
const normalized = node_path.default.posix.normalize(output.path.replaceAll("\\", "/"));
|
|
452
|
+
if (node_path.default.posix.isAbsolute(normalized) || /^[a-z]:/i.test(output.path) || normalized === ".." || normalized.startsWith("../")) return output.path;
|
|
453
|
+
}
|
|
454
|
+
for (const entry of Object.values(value)) {
|
|
455
|
+
const found = findEscapingOutputPath(entry);
|
|
456
|
+
if (found !== void 0) return found;
|
|
457
|
+
}
|
|
458
|
+
}
|
|
391
459
|
// ../../internals/shared/src/configFile/text.ts
|
|
392
460
|
/**
|
|
393
461
|
* A valid JavaScript identifier, so an import name can only ever print as `import { name } from`,
|
|
@@ -483,13 +551,15 @@ function isNonEmptyString(value) {
|
|
|
483
551
|
}
|
|
484
552
|
/** Edits cross the wire, so their shape is checked before anything reads them. */
|
|
485
553
|
function validateEdit(edit) {
|
|
486
|
-
const { operation, plugin, config, path, kind, input } = typeof edit === "object" && edit !== null ? edit : {};
|
|
554
|
+
const { operation, plugin, config, path, kind, input, value, options } = typeof edit === "object" && edit !== null ? edit : {};
|
|
487
555
|
if (typeof operation !== "string" || !OPERATIONS.has(operation)) return `unknown operation ${JSON.stringify(operation)}`;
|
|
488
556
|
if (config !== void 0 && typeof config !== "string" && !Number.isSafeInteger(config)) return "config must name an entry or give its index";
|
|
489
557
|
if (operation === require_protocol.ConfigEditOperation.SET_INPUT) return typeof input === "string" && input.trim() !== "" ? void 0 : "the edit names no input";
|
|
490
558
|
const isOption = OPTION_OPERATIONS.has(operation);
|
|
491
559
|
const isOutput = OUTPUT_OPERATIONS.has(operation);
|
|
492
560
|
if (!isOutput && !isNonEmptyString(plugin)) return "the edit names no plugin";
|
|
561
|
+
const escaping = findEscapingOutputPath(operation === require_protocol.ConfigEditOperation.SET_OPTION && Array.isArray(path) ? path.reduceRight((inner, key) => ({ [String(key)]: inner }), value) : options);
|
|
562
|
+
if (escaping !== void 0) return `output.path ${JSON.stringify(escaping)} resolves outside the output folder`;
|
|
493
563
|
if (kind !== void 0) {
|
|
494
564
|
if (typeof kind !== "string" || !KINDS.has(kind)) return `unknown kind ${JSON.stringify(kind)}`;
|
|
495
565
|
const takesKind = operation === require_protocol.ConfigEditOperation.ADD_PLUGIN || operation === require_protocol.ConfigEditOperation.REMOVE_EXTENSION;
|
|
@@ -1148,13 +1218,13 @@ function applyEdit({ source, edit, extensions }) {
|
|
|
1148
1218
|
function editConfig({ source, edits, extensions = /* @__PURE__ */ new Map() }) {
|
|
1149
1219
|
let current = source;
|
|
1150
1220
|
const outcomes = edits.map((edit) => {
|
|
1151
|
-
const invalid = validateEdit(edit);
|
|
1152
|
-
if (invalid) return {
|
|
1153
|
-
edit,
|
|
1154
|
-
applied: false,
|
|
1155
|
-
reason: invalid
|
|
1156
|
-
};
|
|
1157
1221
|
try {
|
|
1222
|
+
const invalid = validateEdit(edit);
|
|
1223
|
+
if (invalid) return {
|
|
1224
|
+
edit,
|
|
1225
|
+
applied: false,
|
|
1226
|
+
reason: invalid
|
|
1227
|
+
};
|
|
1158
1228
|
const result = applyEdit({
|
|
1159
1229
|
source: current,
|
|
1160
1230
|
edit,
|
|
@@ -1391,7 +1461,7 @@ function generationFailure(diagnostics) {
|
|
|
1391
1461
|
* Runs one generation and returns the files it produced. The formatter, the linter, and
|
|
1392
1462
|
* `output.postGenerate` only run with `allowExec`. Throws when any plugin reports an error.
|
|
1393
1463
|
*/
|
|
1394
|
-
async function generate({ config, hooks, signal, allowExec }) {
|
|
1464
|
+
async function generate({ config, hooks, signal, allowExec, fileRefs }) {
|
|
1395
1465
|
const output = allowExec ? config.output : {
|
|
1396
1466
|
...config.output,
|
|
1397
1467
|
format: false,
|
|
@@ -1403,7 +1473,8 @@ async function generate({ config, hooks, signal, allowExec }) {
|
|
|
1403
1473
|
output
|
|
1404
1474
|
}, {
|
|
1405
1475
|
hooks,
|
|
1406
|
-
signal
|
|
1476
|
+
signal,
|
|
1477
|
+
fileRefs
|
|
1407
1478
|
});
|
|
1408
1479
|
const result = await kubb.generate();
|
|
1409
1480
|
if (!result.success) throw generationFailure(result.diagnostics);
|
|
@@ -1786,7 +1857,7 @@ const NO_BODY = /* @__PURE__ */ new Set([
|
|
|
1786
1857
|
304
|
|
1787
1858
|
]);
|
|
1788
1859
|
function notPublic(host) {
|
|
1789
|
-
return /* @__PURE__ */ new Error(`${host} is not a public address, so
|
|
1860
|
+
return /* @__PURE__ */ new Error(`${host} is not a public address, so this agent does not fetch from it`);
|
|
1790
1861
|
}
|
|
1791
1862
|
function createLookup(blocked) {
|
|
1792
1863
|
return (hostname, options, callback) => {
|
|
@@ -1838,8 +1909,8 @@ function request({ url, blocked, signal }) {
|
|
|
1838
1909
|
*/
|
|
1839
1910
|
function createPublicFetch(blocked) {
|
|
1840
1911
|
const publicFetch = async (input, init) => {
|
|
1841
|
-
if (typeof input !== "string" && !(input instanceof URL)) throw new TypeError("
|
|
1842
|
-
if (init?.method && init.method.toUpperCase() !== "GET") throw new TypeError("
|
|
1912
|
+
if (typeof input !== "string" && !(input instanceof URL)) throw new TypeError("This agent fetches by URL only");
|
|
1913
|
+
if (init?.method && init.method.toUpperCase() !== "GET") throw new TypeError("This agent only sends GET requests");
|
|
1843
1914
|
let url = new URL(input);
|
|
1844
1915
|
for (let hop = 0; hop <= MAX_REDIRECTS; hop++) {
|
|
1845
1916
|
const response = await request({
|
|
@@ -1858,7 +1929,7 @@ function createPublicFetch(blocked) {
|
|
|
1858
1929
|
}
|
|
1859
1930
|
/**
|
|
1860
1931
|
* 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.
|
|
1932
|
+
* A sandbox or managed agent runs one job at a time, so nothing else shares the window.
|
|
1862
1933
|
*/
|
|
1863
1934
|
async function withPublicFetch(run) {
|
|
1864
1935
|
const original = globalThis.fetch;
|
|
@@ -2131,6 +2202,18 @@ function assertOutputPaths({ plugins, diskPlugins, root, outputPath }) {
|
|
|
2131
2202
|
}
|
|
2132
2203
|
}
|
|
2133
2204
|
/**
|
|
2205
|
+
* The folders a `$ref` may read local files from on each kind of agent. Studio may have sent the
|
|
2206
|
+
* spec, so a shared agent gets none, and a managed agent only the git checkout it made itself. A
|
|
2207
|
+
* project agent gets its `root` and the folder of the file `input` in its own config. `undefined`
|
|
2208
|
+
* means no limit, which only `allowFileRefs` grants.
|
|
2209
|
+
*/
|
|
2210
|
+
function resolveFileRefs({ agentType, allowFileRefs, root, input, checkoutDir }) {
|
|
2211
|
+
if (agentType === "sandbox" || agentType === "global") return [];
|
|
2212
|
+
if (agentType === "managed") return checkoutDir ? [checkoutDir] : [];
|
|
2213
|
+
if (allowFileRefs) return void 0;
|
|
2214
|
+
return typeof input === "string" && (0, _kubb_core.getInputKind)(input) === "file" ? [root, node_path.default.dirname(node_path.default.resolve(root, input))] : [root];
|
|
2215
|
+
}
|
|
2216
|
+
/**
|
|
2134
2217
|
* Re-invokes the factory behind a disk adapter or parser with Studio's options merged over its own.
|
|
2135
2218
|
* An instance carries live functions (`parse`, `print`, ...) that cannot survive JSON, so Studio's
|
|
2136
2219
|
* options are a patch, not a replacement, and the factory is found from the disk instance itself: the
|
|
@@ -2222,6 +2305,7 @@ function secureUrl({ studioUrl, path, socket = false }) {
|
|
|
2222
2305
|
}
|
|
2223
2306
|
// src/connect.ts
|
|
2224
2307
|
const HEARTBEAT_INTERVAL_MS = 3e4;
|
|
2308
|
+
const SHARED_AGENT_TYPES = /* @__PURE__ */ new Set(["sandbox", "global"]);
|
|
2225
2309
|
const MAX_HEARTBEAT_INTERVAL_MS = 6e4;
|
|
2226
2310
|
const PING_TIMEOUT_MS = 1e4;
|
|
2227
2311
|
const OPEN_TIMEOUT_MS = 5e3;
|
|
@@ -2347,14 +2431,25 @@ var Agent = class extends capnweb.RpcTarget {
|
|
|
2347
2431
|
this.#session = session;
|
|
2348
2432
|
}
|
|
2349
2433
|
get #sandbox() {
|
|
2350
|
-
return this.#session.info?.sandbox === true;
|
|
2434
|
+
return SHARED_AGENT_TYPES.has(this.#options.agentType) || this.#session.info?.sandbox === true;
|
|
2351
2435
|
}
|
|
2352
2436
|
get #managed() {
|
|
2353
|
-
return this.#session.info?.managed === true;
|
|
2437
|
+
return this.#options.agentType === "managed" || this.#session.info?.managed === true;
|
|
2438
|
+
}
|
|
2439
|
+
get #agentType() {
|
|
2440
|
+
if (this.#sandbox) return "sandbox";
|
|
2441
|
+
if (this.#managed) return "managed";
|
|
2442
|
+
return this.#options.agentType;
|
|
2354
2443
|
}
|
|
2355
2444
|
get #permissions() {
|
|
2356
|
-
const { permissions } = this.#options;
|
|
2357
|
-
|
|
2445
|
+
const { permissions, agentType } = this.#options;
|
|
2446
|
+
const sandbox = SHARED_AGENT_TYPES.has(agentType);
|
|
2447
|
+
if (this.#managed) return {
|
|
2448
|
+
...permissions,
|
|
2449
|
+
allowFileRefs: false
|
|
2450
|
+
};
|
|
2451
|
+
if (!this.#sandbox) return permissions;
|
|
2452
|
+
return {
|
|
2358
2453
|
...permissions,
|
|
2359
2454
|
allowWrite: false,
|
|
2360
2455
|
allowConfigEdit: false,
|
|
@@ -2362,9 +2457,10 @@ var Agent = class extends capnweb.RpcTarget {
|
|
|
2362
2457
|
allowUpdate: false,
|
|
2363
2458
|
allowRemove: false,
|
|
2364
2459
|
allowSaveInput: false,
|
|
2365
|
-
|
|
2366
|
-
|
|
2367
|
-
|
|
2460
|
+
allowFileRefs: false,
|
|
2461
|
+
allowRead: sandbox || permissions.allowRead,
|
|
2462
|
+
allowReadAst: sandbox || permissions.allowReadAst
|
|
2463
|
+
};
|
|
2368
2464
|
}
|
|
2369
2465
|
get #generations() {
|
|
2370
2466
|
this.#store ??= createGenerationStore({
|
|
@@ -2456,6 +2552,13 @@ var Agent = class extends capnweb.RpcTarget {
|
|
|
2456
2552
|
});
|
|
2457
2553
|
}
|
|
2458
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;
|
|
2459
2562
|
return {
|
|
2460
2563
|
versions: {
|
|
2461
2564
|
kubb: version,
|
|
@@ -2468,7 +2571,8 @@ var Agent = class extends capnweb.RpcTarget {
|
|
|
2468
2571
|
extensions: [...extensions.values()],
|
|
2469
2572
|
configs: entries
|
|
2470
2573
|
},
|
|
2471
|
-
permissions: this.#permissions
|
|
2574
|
+
permissions: this.#permissions,
|
|
2575
|
+
...signature && { signature }
|
|
2472
2576
|
};
|
|
2473
2577
|
}
|
|
2474
2578
|
async #readDiskOutput(config) {
|
|
@@ -2586,7 +2690,8 @@ var Agent = class extends capnweb.RpcTarget {
|
|
|
2586
2690
|
});
|
|
2587
2691
|
const activePlugins = plugins ?? config.plugins;
|
|
2588
2692
|
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
|
|
2693
|
+
const managedInput = this.#managed ? studioInput ?? config.input : void 0;
|
|
2694
|
+
const checkout = typeof managedInput === "string" && (0, _kubb_core.getInputKind)(managedInput) === "git" ? await (0, _kubb_core.checkoutGitInput)(managedInput, signal, {
|
|
2590
2695
|
publicOnly: true,
|
|
2591
2696
|
authorization: input.gitAuth?.authorization
|
|
2592
2697
|
}).catch((error) => this.#refuse({
|
|
@@ -2612,9 +2717,16 @@ var Agent = class extends capnweb.RpcTarget {
|
|
|
2612
2717
|
},
|
|
2613
2718
|
hooks: this.#options.hooks,
|
|
2614
2719
|
signal,
|
|
2615
|
-
allowExec: this.#permissions.allowWrite && this.#permissions.allowExec
|
|
2720
|
+
allowExec: this.#permissions.allowWrite && this.#permissions.allowExec,
|
|
2721
|
+
fileRefs: resolveFileRefs({
|
|
2722
|
+
agentType: this.#agentType,
|
|
2723
|
+
allowFileRefs: this.#permissions.allowFileRefs,
|
|
2724
|
+
root: this.#options.root,
|
|
2725
|
+
input: config.input,
|
|
2726
|
+
checkoutDir: checkout?.dir
|
|
2727
|
+
})
|
|
2616
2728
|
});
|
|
2617
|
-
const files = await (this.#managed ? withPublicFetch(run) : run()).catch(async (error) => {
|
|
2729
|
+
const files = await (this.#sandbox || this.#managed ? withPublicFetch(run) : run()).catch(async (error) => {
|
|
2618
2730
|
await this.#generations.drop(jobId);
|
|
2619
2731
|
await this.#logCommand("generate", getErrorMessage(error), input.requestedBy, true);
|
|
2620
2732
|
throw error;
|
|
@@ -2709,7 +2821,7 @@ var Agent = class extends capnweb.RpcTarget {
|
|
|
2709
2821
|
/**
|
|
2710
2822
|
* Readies a `set-input` edit for the config file: a document is pointed at `openapi.yaml` (`openapi.json`
|
|
2711
2823
|
* 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.
|
|
2824
|
+
* A managed agent refuses a file path, as in a generation. Every agent refuses a file path outside the project.
|
|
2713
2825
|
*/
|
|
2714
2826
|
async #keepInput(edit) {
|
|
2715
2827
|
if (edit?.operation !== require_protocol.ConfigEditOperation.SET_INPUT || typeof edit.input !== "string" || !edit.input.trim()) return edit;
|
|
@@ -2722,6 +2834,7 @@ var Agent = class extends capnweb.RpcTarget {
|
|
|
2722
2834
|
}
|
|
2723
2835
|
const kind = (0, _kubb_core.getInputKind)(edit.input);
|
|
2724
2836
|
if (this.#managed && !MANAGED_INPUT_KINDS.has(kind)) return { reason: require_protocol.AgentMessage.MANAGED_INPUT_KIND };
|
|
2837
|
+
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
2838
|
if (kind !== "inline") return edit;
|
|
2726
2839
|
const fileName = `openapi${edit.config === void 0 || edit.config === 0 ? "" : `-${String(edit.config).replace(/[^\w.-]/g, "-")}`}.${isJson(edit.input) ? "json" : "yaml"}`;
|
|
2727
2840
|
return {
|
|
@@ -3008,7 +3121,13 @@ const openWebSocketRpc = ({ url, token, instanceId, agent }) => {
|
|
|
3008
3121
|
};
|
|
3009
3122
|
};
|
|
3010
3123
|
async function runSession({ options, openRpc, url, instanceId }) {
|
|
3011
|
-
const { hooks, signal, heartbeatInterval,
|
|
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
|
+
};
|
|
3012
3131
|
const session = {
|
|
3013
3132
|
connected: Promise.withResolvers(),
|
|
3014
3133
|
closed: false
|
|
@@ -3132,6 +3251,7 @@ async function runAgent({ options, openRpc }) {
|
|
|
3132
3251
|
...options,
|
|
3133
3252
|
studioUrl: options.studioUrl ?? "https://kubb.studio",
|
|
3134
3253
|
root,
|
|
3254
|
+
agentType: options.agentType ?? "user",
|
|
3135
3255
|
configFile: node_path.default.resolve(root, options.configPath),
|
|
3136
3256
|
permissions: {
|
|
3137
3257
|
allowWrite: false,
|
|
@@ -3140,6 +3260,7 @@ async function runAgent({ options, openRpc }) {
|
|
|
3140
3260
|
allowUpdate: false,
|
|
3141
3261
|
allowRemove: false,
|
|
3142
3262
|
allowSaveInput: false,
|
|
3263
|
+
allowFileRefs: false,
|
|
3143
3264
|
allowExec: false,
|
|
3144
3265
|
allowRead: false,
|
|
3145
3266
|
allowReadAst: false,
|
|
@@ -3234,7 +3355,7 @@ var PairingDeniedError = class extends Error {
|
|
|
3234
3355
|
/**
|
|
3235
3356
|
* Asks Studio for a pairing code, sending the hashed machine id with it.
|
|
3236
3357
|
*/
|
|
3237
|
-
async function startPairing({ studioUrl = defaultStudioUrl, type, name, hostname, machineId, signal }) {
|
|
3358
|
+
async function startPairing({ studioUrl = defaultStudioUrl, type, name, hostname, machineId, privateKey, signal }) {
|
|
3238
3359
|
try {
|
|
3239
3360
|
const pairing = await (0, ofetch.ofetch)(secureUrl({
|
|
3240
3361
|
studioUrl,
|
|
@@ -3246,7 +3367,8 @@ async function startPairing({ studioUrl = defaultStudioUrl, type, name, hostname
|
|
|
3246
3367
|
name,
|
|
3247
3368
|
hostname,
|
|
3248
3369
|
machine_token: (0, node_crypto.hash)("sha256", machineId),
|
|
3249
|
-
agent_kind: type === "cli" ? void 0 : type
|
|
3370
|
+
agent_kind: type === "cli" ? void 0 : type,
|
|
3371
|
+
public_key: privateKey ? getAgentPublicKey(privateKey) : void 0
|
|
3250
3372
|
},
|
|
3251
3373
|
signal
|
|
3252
3374
|
});
|
|
@@ -3349,6 +3471,63 @@ async function pairAgent({ onCode, onRetry, maxAttempts = 1, ...options }) {
|
|
|
3349
3471
|
}
|
|
3350
3472
|
}
|
|
3351
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
|
+
}
|
|
3352
3531
|
// src/snapshot.ts
|
|
3353
3532
|
const UPLOAD_TIMEOUT_MS = 12e4;
|
|
3354
3533
|
const BUNDLED_DEPENDENCIES = ["@kubb/plugin-barrel"];
|
|
@@ -3633,6 +3812,12 @@ exports.createSnapshot = createSnapshot;
|
|
|
3633
3812
|
exports.defaultStudioUrl = defaultStudioUrl;
|
|
3634
3813
|
exports.editConfig = editConfig;
|
|
3635
3814
|
exports.editConfigFile = editConfigFile;
|
|
3815
|
+
exports.generateAgentKey = generateAgentKey;
|
|
3816
|
+
exports.getAgentPublicKey = getAgentPublicKey;
|
|
3817
|
+
exports.getTokenRefreshPayload = getTokenRefreshPayload;
|
|
3636
3818
|
exports.pairAgent = pairAgent;
|
|
3819
|
+
exports.refreshAgentToken = refreshAgentToken;
|
|
3820
|
+
exports.signAgentPayload = signAgentPayload;
|
|
3821
|
+
exports.verifyAgentSignature = verifyAgentSignature;
|
|
3637
3822
|
|
|
3638
3823
|
//# sourceMappingURL=index.cjs.map
|