@nexum-hub/agent 0.0.0-stage → 0.0.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +129 -2
- package/contracts/v2/common.schema.json +262 -0
- package/contracts/v2/fixtures/inputs.json +244 -0
- package/contracts/v2/fixtures/wire.json +6493 -0
- package/contracts/v2/model/agent.close.input.schema.json +14 -0
- package/contracts/v2/model/agent.close.output.schema.json +101 -0
- package/contracts/v2/model/agent.list.input.schema.json +57 -0
- package/contracts/v2/model/agent.list.output.schema.json +220 -0
- package/contracts/v2/model/agent.open.input.schema.json +35 -0
- package/contracts/v2/model/agent.open.output.schema.json +41 -0
- package/contracts/v2/model/agent.run.cancel.input.schema.json +18 -0
- package/contracts/v2/model/agent.run.cancel.output.schema.json +100 -0
- package/contracts/v2/model/agent.run.get.input.schema.json +41 -0
- package/contracts/v2/model/agent.run.get.output.schema.json +100 -0
- package/contracts/v2/model/agent.run.input.input.schema.json +30 -0
- package/contracts/v2/model/agent.run.input.output.schema.json +100 -0
- package/contracts/v2/model/agent.run.list.input.schema.json +47 -0
- package/contracts/v2/model/agent.run.list.output.schema.json +41 -0
- package/contracts/v2/model/agent.run.start.input.schema.json +73 -0
- package/contracts/v2/model/agent.run.start.output.schema.json +100 -0
- package/contracts/v2/wire/bodies.schema.json +383 -0
- package/contracts/v2/wire/envelope.schema.json +2280 -0
- package/contracts/v2/wire/events.schema.json +242 -0
- package/contracts/v2/wire/maintenance.schema.json +308 -0
- package/contracts/v2/wire/operations.schema.json +1791 -0
- package/contracts/v2/wire/stream.schema.json +74 -0
- package/contracts/v2/wire/types.schema.json +2616 -0
- package/dist/adapters/mcp-http.d.ts +22 -0
- package/dist/adapters/mcp-http.js +472 -0
- package/dist/adapters/mcp-http.js.map +1 -0
- package/dist/adapters/mcp-oauth.d.ts +29 -0
- package/dist/adapters/mcp-oauth.js +653 -0
- package/dist/adapters/mcp-oauth.js.map +1 -0
- package/dist/adapters/mcp-wire.d.ts +21 -0
- package/dist/adapters/mcp-wire.js +307 -0
- package/dist/adapters/mcp-wire.js.map +1 -0
- package/dist/adapters/mcp.d.ts +56 -0
- package/dist/adapters/mcp.js +1989 -0
- package/dist/adapters/mcp.js.map +1 -0
- package/dist/adapters/openapi-http.d.ts +29 -0
- package/dist/adapters/openapi-http.js +504 -0
- package/dist/adapters/openapi-http.js.map +1 -0
- package/dist/adapters/openapi-request.d.ts +26 -0
- package/dist/adapters/openapi-request.js +597 -0
- package/dist/adapters/openapi-request.js.map +1 -0
- package/dist/adapters/openapi-schema.d.ts +22 -0
- package/dist/adapters/openapi-schema.js +471 -0
- package/dist/adapters/openapi-schema.js.map +1 -0
- package/dist/adapters/openapi-typegen.d.ts +11 -0
- package/dist/adapters/openapi-typegen.js +185 -0
- package/dist/adapters/openapi-typegen.js.map +1 -0
- package/dist/adapters/openapi-types.d.ts +99 -0
- package/dist/adapters/openapi-types.js +2 -0
- package/dist/adapters/openapi-types.js.map +1 -0
- package/dist/adapters/openapi.d.ts +7 -0
- package/dist/adapters/openapi.js +768 -0
- package/dist/adapters/openapi.js.map +1 -0
- package/dist/application/activation.d.ts +28 -0
- package/dist/application/activation.js +289 -0
- package/dist/application/activation.js.map +1 -0
- package/dist/application/attachments.d.ts +24 -0
- package/dist/application/attachments.js +87 -0
- package/dist/application/attachments.js.map +1 -0
- package/dist/application/authority.d.ts +32 -0
- package/dist/application/authority.js +213 -0
- package/dist/application/authority.js.map +1 -0
- package/dist/application/catalog.d.ts +11 -0
- package/dist/application/catalog.js +177 -0
- package/dist/application/catalog.js.map +1 -0
- package/dist/application/config.d.ts +24 -0
- package/dist/application/config.js +140 -0
- package/dist/application/config.js.map +1 -0
- package/dist/application/connection.d.ts +35 -0
- package/dist/application/connection.js +465 -0
- package/dist/application/connection.js.map +1 -0
- package/dist/application/data-plane.d.ts +35 -0
- package/dist/application/data-plane.js +437 -0
- package/dist/application/data-plane.js.map +1 -0
- package/dist/application/diagnostics.d.ts +4 -0
- package/dist/application/diagnostics.js +65 -0
- package/dist/application/diagnostics.js.map +1 -0
- package/dist/application/dispatcher.d.ts +4 -0
- package/dist/application/dispatcher.js +16 -0
- package/dist/application/dispatcher.js.map +1 -0
- package/dist/application/main.d.ts +12 -0
- package/dist/application/main.js +167 -0
- package/dist/application/main.js.map +1 -0
- package/dist/application/maintenance.d.ts +27 -0
- package/dist/application/maintenance.js +244 -0
- package/dist/application/maintenance.js.map +1 -0
- package/dist/application/packages.d.ts +25 -0
- package/dist/application/packages.js +208 -0
- package/dist/application/packages.js.map +1 -0
- package/dist/application/processes.d.ts +49 -0
- package/dist/application/processes.js +180 -0
- package/dist/application/processes.js.map +1 -0
- package/dist/application/run-view.d.ts +17 -0
- package/dist/application/run-view.js +286 -0
- package/dist/application/run-view.js.map +1 -0
- package/dist/application/runtime.d.ts +78 -0
- package/dist/application/runtime.js +1747 -0
- package/dist/application/runtime.js.map +1 -0
- package/dist/application/tasks.d.ts +38 -0
- package/dist/application/tasks.js +23 -0
- package/dist/application/tasks.js.map +1 -0
- package/dist/application/user-state.d.ts +20 -0
- package/dist/application/user-state.js +52 -0
- package/dist/application/user-state.js.map +1 -0
- package/dist/application/work-git.d.ts +14 -0
- package/dist/application/work-git.js +67 -0
- package/dist/application/work-git.js.map +1 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +40 -0
- package/dist/cli.js.map +1 -0
- package/dist/contracts/caller.d.ts +51 -0
- package/dist/contracts/caller.js +95 -0
- package/dist/contracts/caller.js.map +1 -0
- package/dist/contracts/error-data.d.ts +6 -0
- package/dist/contracts/error-data.js +51 -0
- package/dist/contracts/error-data.js.map +1 -0
- package/dist/contracts/errors.d.ts +10 -0
- package/dist/contracts/errors.js +28 -0
- package/dist/contracts/errors.js.map +1 -0
- package/dist/contracts/json.d.ts +9 -0
- package/dist/contracts/json.js +104 -0
- package/dist/contracts/json.js.map +1 -0
- package/dist/contracts/types.d.ts +122 -0
- package/dist/contracts/types.js +19 -0
- package/dist/contracts/types.js.map +1 -0
- package/dist/contracts/validation.d.ts +4 -0
- package/dist/contracts/validation.js +157 -0
- package/dist/contracts/validation.js.map +1 -0
- package/dist/contracts/wire-validation.d.ts +9 -0
- package/dist/contracts/wire-validation.js +399 -0
- package/dist/contracts/wire-validation.js.map +1 -0
- package/dist/contracts/wire.d.ts +1083 -0
- package/dist/contracts/wire.js +62 -0
- package/dist/contracts/wire.js.map +1 -0
- package/dist/extension-api.d.ts +12 -0
- package/dist/extension-api.js +2 -0
- package/dist/extension-api.js.map +1 -0
- package/dist/extensions/api.d.ts +72 -0
- package/dist/extensions/api.js +2 -0
- package/dist/extensions/api.js.map +1 -0
- package/dist/extensions/host-requests.d.ts +23 -0
- package/dist/extensions/host-requests.js +60 -0
- package/dist/extensions/host-requests.js.map +1 -0
- package/dist/extensions/materials.d.ts +37 -0
- package/dist/extensions/materials.js +691 -0
- package/dist/extensions/materials.js.map +1 -0
- package/dist/extensions/package-loader.d.ts +28 -0
- package/dist/extensions/package-loader.js +177 -0
- package/dist/extensions/package-loader.js.map +1 -0
- package/dist/extensions/packages.d.ts +73 -0
- package/dist/extensions/packages.js +441 -0
- package/dist/extensions/packages.js.map +1 -0
- package/dist/extensions/registry.d.ts +92 -0
- package/dist/extensions/registry.js +1540 -0
- package/dist/extensions/registry.js.map +1 -0
- package/dist/extensions/resources.d.ts +105 -0
- package/dist/extensions/resources.js +595 -0
- package/dist/extensions/resources.js.map +1 -0
- package/dist/extensions/state.d.ts +25 -0
- package/dist/extensions/state.js +10 -0
- package/dist/extensions/state.js.map +1 -0
- package/dist/extensions/transfer.d.ts +81 -0
- package/dist/extensions/transfer.js +16 -0
- package/dist/extensions/transfer.js.map +1 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +25 -0
- package/dist/index.js.map +1 -0
- package/dist/maintenance/configuration.d.ts +79 -0
- package/dist/maintenance/configuration.js +1503 -0
- package/dist/maintenance/configuration.js.map +1 -0
- package/dist/maintenance/credentials.d.ts +23 -0
- package/dist/maintenance/credentials.js +177 -0
- package/dist/maintenance/credentials.js.map +1 -0
- package/dist/maintenance/files.d.ts +2 -0
- package/dist/maintenance/files.js +40 -0
- package/dist/maintenance/files.js.map +1 -0
- package/dist/maintenance/npm.d.ts +71 -0
- package/dist/maintenance/npm.js +1013 -0
- package/dist/maintenance/npm.js.map +1 -0
- package/dist/maintenance/oauth.d.ts +45 -0
- package/dist/maintenance/oauth.js +686 -0
- package/dist/maintenance/oauth.js.map +1 -0
- package/dist/maintenance/requests.d.ts +347 -0
- package/dist/maintenance/requests.js +959 -0
- package/dist/maintenance/requests.js.map +1 -0
- package/dist/maintenance/work-git.d.ts +29 -0
- package/dist/maintenance/work-git.js +776 -0
- package/dist/maintenance/work-git.js.map +1 -0
- package/dist/process/backend.d.ts +54 -0
- package/dist/process/backend.js +39 -0
- package/dist/process/backend.js.map +1 -0
- package/dist/process/environment-windows.d.ts +15 -0
- package/dist/process/environment-windows.js +151 -0
- package/dist/process/environment-windows.js.map +1 -0
- package/dist/process/environment.d.ts +28 -0
- package/dist/process/environment.js +410 -0
- package/dist/process/environment.js.map +1 -0
- package/dist/process/launch.d.ts +31 -0
- package/dist/process/launch.js +281 -0
- package/dist/process/launch.js.map +1 -0
- package/dist/process/managed.d.ts +36 -0
- package/dist/process/managed.js +459 -0
- package/dist/process/managed.js.map +1 -0
- package/dist/process/output-log.d.ts +50 -0
- package/dist/process/output-log.js +552 -0
- package/dist/process/output-log.js.map +1 -0
- package/dist/process/pipes.d.ts +16 -0
- package/dist/process/pipes.js +588 -0
- package/dist/process/pipes.js.map +1 -0
- package/dist/process/pty.d.ts +22 -0
- package/dist/process/pty.js +512 -0
- package/dist/process/pty.js.map +1 -0
- package/dist/process/windows-conout-worker.d.ts +1 -0
- package/dist/process/windows-conout-worker.js +90 -0
- package/dist/process/windows-conout-worker.js.map +1 -0
- package/dist/process/windows-conout.d.ts +46 -0
- package/dist/process/windows-conout.js +140 -0
- package/dist/process/windows-conout.js.map +1 -0
- package/dist/process/windows-helper.d.ts +43 -0
- package/dist/process/windows-helper.js +255 -0
- package/dist/process/windows-helper.js.map +1 -0
- package/dist/process/windows-job.d.ts +39 -0
- package/dist/process/windows-job.js +224 -0
- package/dist/process/windows-job.js.map +1 -0
- package/dist/process/windows-pipes.d.ts +16 -0
- package/dist/process/windows-pipes.js +475 -0
- package/dist/process/windows-pipes.js.map +1 -0
- package/dist/results/artifacts.d.ts +118 -0
- package/dist/results/artifacts.js +873 -0
- package/dist/results/artifacts.js.map +1 -0
- package/dist/results/encoder.d.ts +57 -0
- package/dist/results/encoder.js +1179 -0
- package/dist/results/encoder.js.map +1 -0
- package/dist/results/mcp.d.ts +95 -0
- package/dist/results/mcp.js +656 -0
- package/dist/results/mcp.js.map +1 -0
- package/dist/results/media.d.ts +19 -0
- package/dist/results/media.js +301 -0
- package/dist/results/media.js.map +1 -0
- package/dist/results/normalize.d.ts +29 -0
- package/dist/results/normalize.js +464 -0
- package/dist/results/normalize.js.map +1 -0
- package/dist/runtime/control-scripts.d.ts +23 -0
- package/dist/runtime/control-scripts.js +242 -0
- package/dist/runtime/control-scripts.js.map +1 -0
- package/dist/runtime/engine.d.ts +177 -0
- package/dist/runtime/engine.js +1159 -0
- package/dist/runtime/engine.js.map +1 -0
- package/dist/runtime/globals.d.ts +1 -0
- package/dist/runtime/globals.js +31 -0
- package/dist/runtime/globals.js.map +1 -0
- package/dist/runtime/material-retention.d.ts +34 -0
- package/dist/runtime/material-retention.js +671 -0
- package/dist/runtime/material-retention.js.map +1 -0
- package/dist/runtime/modules.d.ts +50 -0
- package/dist/runtime/modules.js +320 -0
- package/dist/runtime/modules.js.map +1 -0
- package/dist/runtime/names.d.ts +2 -0
- package/dist/runtime/names.js +22 -0
- package/dist/runtime/names.js.map +1 -0
- package/dist/runtime/operations.d.ts +20 -0
- package/dist/runtime/operations.js +137 -0
- package/dist/runtime/operations.js.map +1 -0
- package/dist/runtime/paths.d.ts +3 -0
- package/dist/runtime/paths.js +38 -0
- package/dist/runtime/paths.js.map +1 -0
- package/dist/runtime/promises.d.ts +9 -0
- package/dist/runtime/promises.js +78 -0
- package/dist/runtime/promises.js.map +1 -0
- package/dist/runtime/retention.d.ts +88 -0
- package/dist/runtime/retention.js +735 -0
- package/dist/runtime/retention.js.map +1 -0
- package/dist/runtime/run-log.d.ts +30 -0
- package/dist/runtime/run-log.js +207 -0
- package/dist/runtime/run-log.js.map +1 -0
- package/dist/runtime/scripts.d.ts +84 -0
- package/dist/runtime/scripts.js +387 -0
- package/dist/runtime/scripts.js.map +1 -0
- package/dist/runtime/tasks.d.ts +54 -0
- package/dist/runtime/tasks.js +290 -0
- package/dist/runtime/tasks.js.map +1 -0
- package/dist/sdk/maintenance.d.ts +3 -0
- package/dist/sdk/maintenance.js +80 -0
- package/dist/sdk/maintenance.js.map +1 -0
- package/dist/sdk/output-extension.d.ts +3 -0
- package/dist/sdk/output-extension.js +44 -0
- package/dist/sdk/output-extension.js.map +1 -0
- package/dist/sdk/output.d.ts +52 -0
- package/dist/sdk/output.js +350 -0
- package/dist/sdk/output.js.map +1 -0
- package/dist/sdk/runtime.d.ts +3 -0
- package/dist/sdk/runtime.js +26 -0
- package/dist/sdk/runtime.js.map +1 -0
- package/dist/sdk/sh.d.ts +3 -0
- package/dist/sdk/sh.js +384 -0
- package/dist/sdk/sh.js.map +1 -0
- package/dist/sdk/state.d.ts +2 -0
- package/dist/sdk/state.js +69 -0
- package/dist/sdk/state.js.map +1 -0
- package/dist/sdk/transfer.d.ts +3 -0
- package/dist/sdk/transfer.js +141 -0
- package/dist/sdk/transfer.js.map +1 -0
- package/dist/services/extensions.d.ts +19 -0
- package/dist/services/extensions.js +183 -0
- package/dist/services/extensions.js.map +1 -0
- package/dist/services/state.d.ts +37 -0
- package/dist/services/state.js +125 -0
- package/dist/services/state.js.map +1 -0
- package/dist/services/transfer.d.ts +86 -0
- package/dist/services/transfer.js +948 -0
- package/dist/services/transfer.js.map +1 -0
- package/dist/storage/schema.d.ts +8 -0
- package/dist/storage/schema.js +241 -0
- package/dist/storage/schema.js.map +1 -0
- package/dist/storage/sqlite.d.ts +241 -0
- package/dist/storage/sqlite.js +1855 -0
- package/dist/storage/sqlite.js.map +1 -0
- package/dist/storage/transfers.d.ts +90 -0
- package/dist/storage/transfers.js +2 -0
- package/dist/storage/transfers.js.map +1 -0
- package/dist/transfer/io.d.ts +74 -0
- package/dist/transfer/io.js +425 -0
- package/dist/transfer/io.js.map +1 -0
- package/dist/transfer/offers.d.ts +72 -0
- package/dist/transfer/offers.js +380 -0
- package/dist/transfer/offers.js.map +1 -0
- package/dist/transfer/stream-slots.d.ts +12 -0
- package/dist/transfer/stream-slots.js +28 -0
- package/dist/transfer/stream-slots.js.map +1 -0
- package/dist/work/catalog.d.ts +43 -0
- package/dist/work/catalog.js +198 -0
- package/dist/work/catalog.js.map +1 -0
- package/dist/work/discovery.d.ts +70 -0
- package/dist/work/discovery.js +465 -0
- package/dist/work/discovery.js.map +1 -0
- package/dist/work/service.d.ts +83 -0
- package/dist/work/service.js +703 -0
- package/dist/work/service.js.map +1 -0
- package/package.json +66 -4
|
@@ -0,0 +1,1503 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { constants, realpathSync, lstatSync, mkdirSync } from "node:fs";
|
|
3
|
+
import { open, rename, rm, writeFile, lstat } from "node:fs/promises";
|
|
4
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
5
|
+
import { pathToFileURL, fileURLToPath } from "node:url";
|
|
6
|
+
import { parseDocument } from "yaml";
|
|
7
|
+
import { AgentError, isAgentError, requireCondition, } from "../contracts/errors.js";
|
|
8
|
+
import { authorizeCall } from "../contracts/caller.js";
|
|
9
|
+
import { canonicalJson, isPlainRecord, newId } from "../contracts/json.js";
|
|
10
|
+
import { validateMcpConnectionConfig, } from "../adapters/mcp.js";
|
|
11
|
+
import { validateMcpOAuthConfig, } from "../adapters/mcp-oauth.js";
|
|
12
|
+
import { prepareOpenApi, } from "../adapters/openapi.js";
|
|
13
|
+
import { parseOpenApi, openApiLimits } from "../adapters/openapi-schema.js";
|
|
14
|
+
import { privateMaintenanceRead, privateMaintenanceWrite, } from "./credentials.js";
|
|
15
|
+
import { validateOAuthConfig, } from "./oauth.js";
|
|
16
|
+
const json = (value, cap = 64 * 1024 * 1024) => JSON.parse(canonicalJson(value, cap));
|
|
17
|
+
const hash = (value) => createHash("sha256")
|
|
18
|
+
.update(canonicalJson(value, 64 * 1024 * 1024))
|
|
19
|
+
.digest("hex");
|
|
20
|
+
const object = (value) => isPlainRecord(value);
|
|
21
|
+
const entry = (map, key) => Object.hasOwn(map, key) ? map[key] : undefined;
|
|
22
|
+
const put = (map, key, value) => {
|
|
23
|
+
Object.defineProperty(map, key, {
|
|
24
|
+
value,
|
|
25
|
+
writable: true,
|
|
26
|
+
enumerable: true,
|
|
27
|
+
configurable: true,
|
|
28
|
+
});
|
|
29
|
+
};
|
|
30
|
+
const nonempty = (value, max = 8192) => typeof value === "string" &&
|
|
31
|
+
value.length > 0 &&
|
|
32
|
+
Buffer.byteLength(value) <= max &&
|
|
33
|
+
!/[\0\r\n]/.test(value);
|
|
34
|
+
const credentialRef = (value) => typeof value === "string" && /^cred_[a-f0-9]{48}$/.test(value);
|
|
35
|
+
function name(value) {
|
|
36
|
+
requireCondition(/^[A-Za-z_$][A-Za-z0-9_$-]{0,127}$/.test(value), "invalid_maintenance_name", "Use one configuration namespace.");
|
|
37
|
+
}
|
|
38
|
+
/** Portable on case-insensitive filesystems; public config retains the exact logical name. */
|
|
39
|
+
export function configurationDirectoryName(namespace) {
|
|
40
|
+
name(namespace);
|
|
41
|
+
return /[A-Z]/.test(namespace) ||
|
|
42
|
+
/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])$/i.test(namespace)
|
|
43
|
+
? "~" + createHash("sha256").update(namespace, "utf8").digest("hex")
|
|
44
|
+
: namespace;
|
|
45
|
+
}
|
|
46
|
+
function current(scope) {
|
|
47
|
+
scope.signal.throwIfAborted();
|
|
48
|
+
authorizeCall(() => scope.assertCurrent());
|
|
49
|
+
}
|
|
50
|
+
function access(scope, type, value) {
|
|
51
|
+
current(scope);
|
|
52
|
+
authorizeCall(() => scope.authorize({ type, value, access: "read" }));
|
|
53
|
+
}
|
|
54
|
+
function publicFile(root, parts) {
|
|
55
|
+
requireCondition(parts.every((part) => /^[A-Za-z0-9_$~.-]+$/.test(part) && part !== "." && part !== ".."), "configuration_path_invalid", "Use fixed configuration path segments.");
|
|
56
|
+
let directory = path.join(root, "work");
|
|
57
|
+
requireCondition(realpathSync.native(directory) === directory &&
|
|
58
|
+
!lstatSync(directory).isSymbolicLink(), "configuration_path_invalid", "The Agent work directory cannot redirect.");
|
|
59
|
+
for (const part of parts.slice(0, -1)) {
|
|
60
|
+
const next = path.join(directory, part), existing = lstatSync(next, { throwIfNoEntry: false });
|
|
61
|
+
requireCondition(!existing || existing.isDirectory(), "configuration_path_invalid", "Configuration directories cannot be linked or special files.");
|
|
62
|
+
if (!existing)
|
|
63
|
+
mkdirSync(next, { mode: 0o700 });
|
|
64
|
+
requireCondition(realpathSync.native(next) === next, "configuration_path_invalid", "Configuration directories cannot redirect.");
|
|
65
|
+
directory = next;
|
|
66
|
+
}
|
|
67
|
+
return path.join(directory, parts.at(-1));
|
|
68
|
+
}
|
|
69
|
+
async function readPublic(filename, max = 4 * 1024 * 1024) {
|
|
70
|
+
let handle;
|
|
71
|
+
try {
|
|
72
|
+
handle = await open(filename, constants.O_RDONLY |
|
|
73
|
+
(constants.O_NOFOLLOW ?? 0) |
|
|
74
|
+
(constants.O_NONBLOCK ?? 0));
|
|
75
|
+
}
|
|
76
|
+
catch (cause) {
|
|
77
|
+
if (cause.code === "ENOENT")
|
|
78
|
+
return null;
|
|
79
|
+
throw new AgentError("configuration_path_invalid", "The configuration file could not be opened safely.");
|
|
80
|
+
}
|
|
81
|
+
try {
|
|
82
|
+
const before = await handle.stat();
|
|
83
|
+
requireCondition(before.isFile() && before.nlink === 1 && before.size <= max, "configuration_path_invalid", "Configuration files must be bounded regular files without hard links.");
|
|
84
|
+
const chunks = [];
|
|
85
|
+
let count = 0;
|
|
86
|
+
while (true) {
|
|
87
|
+
const buffer = Buffer.allocUnsafe(Math.min(65536, max - count + 1)), read = await handle.read(buffer, 0, buffer.length, null);
|
|
88
|
+
if (!read.bytesRead)
|
|
89
|
+
break;
|
|
90
|
+
count += read.bytesRead;
|
|
91
|
+
requireCondition(count <= max, "configuration_too_large", "Configuration data exceeds its budget.");
|
|
92
|
+
chunks.push(buffer.subarray(0, read.bytesRead));
|
|
93
|
+
}
|
|
94
|
+
const after = await handle.stat(), linked = await lstat(filename);
|
|
95
|
+
requireCondition(linked.isFile() &&
|
|
96
|
+
linked.nlink === 1 &&
|
|
97
|
+
linked.ino === after.ino &&
|
|
98
|
+
linked.dev === after.dev &&
|
|
99
|
+
before.size === after.size &&
|
|
100
|
+
before.mtimeMs === after.mtimeMs &&
|
|
101
|
+
before.ctimeMs === after.ctimeMs, "configuration_file_changed", "The configuration file changed while being read.");
|
|
102
|
+
return new TextDecoder("utf-8", { fatal: true }).decode(Buffer.concat(chunks, count));
|
|
103
|
+
}
|
|
104
|
+
finally {
|
|
105
|
+
await handle.close();
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
async function replacePublic(filename, text) {
|
|
109
|
+
await readPublic(filename, 64 * 1024 * 1024);
|
|
110
|
+
const parent = path.dirname(filename);
|
|
111
|
+
requireCondition(realpathSync.native(parent) === parent, "configuration_path_invalid", "Configuration parent cannot redirect.");
|
|
112
|
+
const temporary = path.join(parent, `.configuration-${randomBytes(24).toString("hex")}`);
|
|
113
|
+
try {
|
|
114
|
+
await writeFile(temporary, text, { flag: "wx", mode: 0o600 });
|
|
115
|
+
requireCondition(realpathSync.native(parent) === parent, "configuration_path_invalid", "Configuration parent changed while saving.");
|
|
116
|
+
await rename(temporary, filename);
|
|
117
|
+
}
|
|
118
|
+
finally {
|
|
119
|
+
await rm(temporary, { force: true });
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
/** Fixed approved snapshots own activation. work files are editable proposals, never approval records. */
|
|
123
|
+
export class ConfigurationMaintenanceBackend {
|
|
124
|
+
options;
|
|
125
|
+
#state;
|
|
126
|
+
constructor(options) {
|
|
127
|
+
this.options = options;
|
|
128
|
+
this.#state = {
|
|
129
|
+
binding: { agentId: options.agentId, profile: options.profile },
|
|
130
|
+
mcp: {},
|
|
131
|
+
api: {},
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
static async open(options) {
|
|
135
|
+
const root = realpathSync.native(options.root);
|
|
136
|
+
requireCondition(root === options.root && options.credentials.root === root, "configuration_profile_mismatch", "Configuration and credential stores require the same established profile root.");
|
|
137
|
+
const value = new ConfigurationMaintenanceBackend({ ...options, root }), saved = await privateMaintenanceRead(root, [
|
|
138
|
+
"configurations",
|
|
139
|
+
"approved.json",
|
|
140
|
+
]);
|
|
141
|
+
if (saved) {
|
|
142
|
+
requireCondition(object(saved.mcp) &&
|
|
143
|
+
object(saved.api) &&
|
|
144
|
+
object(saved.binding) &&
|
|
145
|
+
hash(saved.binding) === hash(value.#state.binding), "configuration_state_invalid", "The approved configuration state is invalid.");
|
|
146
|
+
value.#state = json(saved);
|
|
147
|
+
}
|
|
148
|
+
return value;
|
|
149
|
+
}
|
|
150
|
+
#kind(intent) {
|
|
151
|
+
requireCondition(intent.target === "api" || intent.target === "mcp", "maintenance_target_invalid", "This backend only owns MCP/API configurations.");
|
|
152
|
+
name(intent.name);
|
|
153
|
+
return intent.target;
|
|
154
|
+
}
|
|
155
|
+
#binding(snapshot, scheme, definition) {
|
|
156
|
+
const config = snapshot.config;
|
|
157
|
+
return {
|
|
158
|
+
owner: snapshot.owner,
|
|
159
|
+
agentId: this.options.agentId,
|
|
160
|
+
profile: this.options.profile,
|
|
161
|
+
target: snapshot.kind,
|
|
162
|
+
name: snapshot.name,
|
|
163
|
+
scheme,
|
|
164
|
+
service: snapshot.kind === "api"
|
|
165
|
+
? scheme === "source"
|
|
166
|
+
? snapshot.source
|
|
167
|
+
: (config.serviceUrl ?? null)
|
|
168
|
+
: (config.url ?? config.command ?? null),
|
|
169
|
+
authRevision: hash(definition),
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
#publicLocation(kind, namespace) {
|
|
173
|
+
return kind === "mcp"
|
|
174
|
+
? publicFile(this.options.root, ["mcp.json"])
|
|
175
|
+
: publicFile(this.options.root, [
|
|
176
|
+
"api",
|
|
177
|
+
configurationDirectoryName(namespace),
|
|
178
|
+
"config.json",
|
|
179
|
+
]);
|
|
180
|
+
}
|
|
181
|
+
async #workRevision(kind, namespace) {
|
|
182
|
+
const file = this.#publicLocation(kind, namespace), text = await readPublic(file);
|
|
183
|
+
if (kind === "api")
|
|
184
|
+
return hash(text);
|
|
185
|
+
const root = text === null ? { mcpServers: {} } : JSON.parse(text);
|
|
186
|
+
requireCondition(object(root) &&
|
|
187
|
+
Object.keys(root).every((key) => key === "mcpServers") &&
|
|
188
|
+
object(root.mcpServers), "invalid_mcp_config", "work/mcp.json must contain one mcpServers dictionary.");
|
|
189
|
+
return hash(entry(root.mcpServers, namespace) ?? null);
|
|
190
|
+
}
|
|
191
|
+
async #save(snapshot) {
|
|
192
|
+
const fixed = json(snapshot), id = hash(fixed), file = ["configurations", "candidates", `${id}.json`];
|
|
193
|
+
const existing = await privateMaintenanceRead(this.options.root, file);
|
|
194
|
+
if (existing)
|
|
195
|
+
requireCondition(hash(existing) === id, "configuration_candidate_invalid", "A configuration candidate identity has conflicting data.");
|
|
196
|
+
else
|
|
197
|
+
await privateMaintenanceWrite(this.options.root, file, fixed, true, this.options.reserve);
|
|
198
|
+
return {
|
|
199
|
+
objectId: fixed.baseRevision === null ? null : fixed.objectId,
|
|
200
|
+
baseRevision: fixed.baseRevision,
|
|
201
|
+
payload: { configurationId: id },
|
|
202
|
+
authStatus: fixed.authStatus,
|
|
203
|
+
summary: {
|
|
204
|
+
changeKinds: [
|
|
205
|
+
fixed.kind === "mcp" ? "connection" : "api",
|
|
206
|
+
"configuration",
|
|
207
|
+
"authentication",
|
|
208
|
+
"docs",
|
|
209
|
+
"capability",
|
|
210
|
+
],
|
|
211
|
+
permissions: [fixed.kind === "mcp" ? "mcp.use" : "api.use"],
|
|
212
|
+
version: null,
|
|
213
|
+
namespace: fixed.name,
|
|
214
|
+
restartMayBeRequired: false,
|
|
215
|
+
},
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
async #load(intent, candidate, scope) {
|
|
219
|
+
current(scope);
|
|
220
|
+
const id = candidate.payload.configurationId;
|
|
221
|
+
requireCondition(typeof id === "string" && /^[a-f0-9]{64}$/.test(id), "configuration_candidate_invalid", "Use the fixed private configuration candidate.");
|
|
222
|
+
const value = await privateMaintenanceRead(this.options.root, [
|
|
223
|
+
"configurations",
|
|
224
|
+
"candidates",
|
|
225
|
+
`${id}.json`,
|
|
226
|
+
]);
|
|
227
|
+
requireCondition(value &&
|
|
228
|
+
hash(value) === id &&
|
|
229
|
+
value.kind === this.#kind(intent) &&
|
|
230
|
+
value.agentId === this.options.agentId &&
|
|
231
|
+
value.profile === this.options.profile &&
|
|
232
|
+
value.name === intent.name &&
|
|
233
|
+
value.owner === scope.caller.principalId &&
|
|
234
|
+
value.baseRevision === candidate.baseRevision, "configuration_candidate_invalid", "The configuration candidate is missing or belongs to another target.");
|
|
235
|
+
return json(value);
|
|
236
|
+
}
|
|
237
|
+
async #approved() {
|
|
238
|
+
const state = await privateMaintenanceRead(this.options.root, [
|
|
239
|
+
"configurations",
|
|
240
|
+
"approved.json",
|
|
241
|
+
]);
|
|
242
|
+
if (state) {
|
|
243
|
+
requireCondition(object(state.mcp) &&
|
|
244
|
+
object(state.api) &&
|
|
245
|
+
object(state.binding) &&
|
|
246
|
+
hash(state.binding) === hash(this.#state.binding), "configuration_state_invalid", "Approved configuration state is invalid.");
|
|
247
|
+
this.#state = json(state);
|
|
248
|
+
}
|
|
249
|
+
return json(this.#state);
|
|
250
|
+
}
|
|
251
|
+
async #previous(record) {
|
|
252
|
+
if (!record)
|
|
253
|
+
return null;
|
|
254
|
+
const value = await privateMaintenanceRead(this.options.root, [
|
|
255
|
+
"configurations",
|
|
256
|
+
"candidates",
|
|
257
|
+
`${record.snapshot}.json`,
|
|
258
|
+
]);
|
|
259
|
+
requireCondition(value &&
|
|
260
|
+
hash(value) === record.snapshot &&
|
|
261
|
+
value.agentId === this.options.agentId &&
|
|
262
|
+
value.profile === this.options.profile &&
|
|
263
|
+
value.objectId === record.objectId &&
|
|
264
|
+
record.revision ===
|
|
265
|
+
hash({ snapshot: record.snapshot, objectId: record.objectId }), "configuration_candidate_unavailable", "The approved configuration snapshot is unavailable.");
|
|
266
|
+
return value;
|
|
267
|
+
}
|
|
268
|
+
async prepare(intent, scope) {
|
|
269
|
+
const kind = this.#kind(intent);
|
|
270
|
+
current(scope);
|
|
271
|
+
const state = await this.#approved(), old = entry(state[kind], intent.name), previous = await this.#previous(old);
|
|
272
|
+
requireCondition(!previous || previous.owner === scope.caller.principalId, "configuration_owner_mismatch", "The approved configuration is not available to this owner.");
|
|
273
|
+
requireCondition(intent.action === "add" || intent.action === "import" ? !old : !!old, "maintenance_precondition_changed", old
|
|
274
|
+
? "The configuration already exists; use update."
|
|
275
|
+
: "The configuration does not exist.");
|
|
276
|
+
const snapshot = {
|
|
277
|
+
agentId: this.options.agentId,
|
|
278
|
+
profile: this.options.profile,
|
|
279
|
+
kind,
|
|
280
|
+
name: intent.name,
|
|
281
|
+
owner: scope.caller.principalId,
|
|
282
|
+
objectId: old?.objectId ?? newId(kind),
|
|
283
|
+
baseRevision: old?.revision ?? null,
|
|
284
|
+
config: json(intent.config ?? previous?.config ?? {}),
|
|
285
|
+
secrets: previous ? json(previous.secrets) : {},
|
|
286
|
+
documents: previous ? json(previous.documents) : [],
|
|
287
|
+
source: intent.url ??
|
|
288
|
+
(intent.path
|
|
289
|
+
? pathToFileURL(intent.path).href
|
|
290
|
+
: (previous?.source ?? null)),
|
|
291
|
+
workRevision: await this.#workRevision(kind, intent.name),
|
|
292
|
+
authStatus: "not_required",
|
|
293
|
+
diagnostics: [],
|
|
294
|
+
};
|
|
295
|
+
if (intent.action === "remove")
|
|
296
|
+
return this.#save(snapshot);
|
|
297
|
+
await this.#normalize(snapshot, scope, previous);
|
|
298
|
+
await this.#isolate(snapshot);
|
|
299
|
+
if (kind === "api" &&
|
|
300
|
+
(intent.url || intent.path || !snapshot.documents.length))
|
|
301
|
+
await this.#readSources(snapshot, scope);
|
|
302
|
+
await this.#validate(snapshot, scope);
|
|
303
|
+
return this.#save(snapshot);
|
|
304
|
+
}
|
|
305
|
+
async #isolate(snapshot) {
|
|
306
|
+
const config = snapshot.config;
|
|
307
|
+
for (const [key, secret] of Object.entries(snapshot.secrets)) {
|
|
308
|
+
const value = await this.options.credentials.read(secret.ref, secret.binding);
|
|
309
|
+
secret.ref = await this.options.credentials.create(secret.binding, value);
|
|
310
|
+
if (snapshot.kind === "api" && key !== "source")
|
|
311
|
+
put(config.authentication.credentialBindings, key, secret.ref);
|
|
312
|
+
if (snapshot.kind === "mcp" && key !== "oauth")
|
|
313
|
+
put(config.credentialBindings, key, secret.ref);
|
|
314
|
+
if (key === "source" && object(config.sourceAuthentication?.headers))
|
|
315
|
+
for (const header of Object.keys(config.sourceAuthentication.headers))
|
|
316
|
+
config.sourceAuthentication.headers[header] = secret.ref;
|
|
317
|
+
}
|
|
318
|
+
}
|
|
319
|
+
async #normalize(snapshot, scope, previous) {
|
|
320
|
+
const config = snapshot.config;
|
|
321
|
+
requireCondition(object(config), "invalid_maintenance_config", "Use one configuration object.");
|
|
322
|
+
if (snapshot.kind === "mcp") {
|
|
323
|
+
requireCondition(Object.keys(config).every((key) => [
|
|
324
|
+
"transport",
|
|
325
|
+
"command",
|
|
326
|
+
"args",
|
|
327
|
+
"cwd",
|
|
328
|
+
"env",
|
|
329
|
+
"url",
|
|
330
|
+
"headers",
|
|
331
|
+
"credentialBindings",
|
|
332
|
+
"oauth",
|
|
333
|
+
].includes(key)), "invalid_mcp_config", "Unsupported MCP configuration option.");
|
|
334
|
+
const secrets = Object.create(null), bindings = object(config.credentialBindings)
|
|
335
|
+
? config.credentialBindings
|
|
336
|
+
: {};
|
|
337
|
+
for (const group of ["env", "headers"]) {
|
|
338
|
+
if (config[group] !== undefined)
|
|
339
|
+
requireCondition(object(config[group]), "invalid_mcp_config", "MCP environment and headers must be dictionaries.");
|
|
340
|
+
for (const [key, value] of Object.entries(config[group] ?? {})) {
|
|
341
|
+
requireCondition(nonempty(key, 256) &&
|
|
342
|
+
typeof value === "string" &&
|
|
343
|
+
Buffer.byteLength(value) <= 65536, "invalid_mcp_config", "MCP environment/header values must be bounded strings.");
|
|
344
|
+
const id = `${group}.${key}`, binding = this.#binding(snapshot, id, { group, key });
|
|
345
|
+
secrets[id] = {
|
|
346
|
+
ref: await this.options.credentials.create(binding, { value }),
|
|
347
|
+
binding,
|
|
348
|
+
};
|
|
349
|
+
}
|
|
350
|
+
delete config[group];
|
|
351
|
+
}
|
|
352
|
+
for (const [key, value] of Object.entries(bindings)) {
|
|
353
|
+
requireCondition(/^(?:env|headers)\.[^\0\r\n]{1,256}$/.test(key) &&
|
|
354
|
+
credentialRef(value), "invalid_mcp_config", "MCP credentialBindings need declared env/header references.");
|
|
355
|
+
if (secrets[key])
|
|
356
|
+
continue;
|
|
357
|
+
const old = previous?.secrets[key], binding = this.#binding(snapshot, key, {
|
|
358
|
+
group: key.split(".")[0],
|
|
359
|
+
key: key.slice(key.indexOf(".") + 1),
|
|
360
|
+
});
|
|
361
|
+
const secret = await this.options.credentials.read(value, old?.ref === value ? old.binding : binding);
|
|
362
|
+
secrets[key] = {
|
|
363
|
+
ref: old && hash(old.binding) === hash(binding)
|
|
364
|
+
? value
|
|
365
|
+
: await this.options.credentials.create(binding, secret),
|
|
366
|
+
binding,
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
if (config.oauth !== undefined) {
|
|
370
|
+
requireCondition(object(config.oauth) && config.transport === "streamable-http", "invalid_mcp_config", "MCP OAuth requires a remote HTTP connection configuration.");
|
|
371
|
+
config.oauth = validateMcpOAuthConfig(config.oauth);
|
|
372
|
+
const binding = this.#binding(snapshot, "oauth", config.oauth), old = previous?.secrets.oauth;
|
|
373
|
+
let values = old
|
|
374
|
+
? await this.options.credentials.read(old.ref, old.binding)
|
|
375
|
+
: {};
|
|
376
|
+
secrets.oauth = {
|
|
377
|
+
ref: old && hash(old.binding) === hash(binding)
|
|
378
|
+
? old.ref
|
|
379
|
+
: await this.options.credentials.create(binding, values),
|
|
380
|
+
binding,
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
snapshot.secrets = secrets;
|
|
384
|
+
config.credentialBindings = Object.fromEntries(Object.entries(secrets)
|
|
385
|
+
.filter(([key]) => key !== "oauth")
|
|
386
|
+
.map(([key, value]) => [key, value.ref]));
|
|
387
|
+
const resolved = await this.#mcp(snapshot, scope);
|
|
388
|
+
validateMcpConnectionConfig(resolved);
|
|
389
|
+
}
|
|
390
|
+
else {
|
|
391
|
+
requireCondition(Object.keys(config).every((key) => [
|
|
392
|
+
"serviceUrl",
|
|
393
|
+
"authentication",
|
|
394
|
+
"oauth",
|
|
395
|
+
"sourceAuthentication",
|
|
396
|
+
"identity",
|
|
397
|
+
"specification",
|
|
398
|
+
].includes(key)), "invalid_api_config", "Unsupported API configuration option.");
|
|
399
|
+
if (config.identity !== undefined) {
|
|
400
|
+
requireCondition(object(config.identity) &&
|
|
401
|
+
hash(config.identity) ===
|
|
402
|
+
hash({
|
|
403
|
+
name: snapshot.name,
|
|
404
|
+
directory: configurationDirectoryName(snapshot.name),
|
|
405
|
+
}), "configuration_target_fixed", "Public configuration identity cannot change its logical namespace or directory.");
|
|
406
|
+
delete config.identity;
|
|
407
|
+
}
|
|
408
|
+
if (config.specification !== undefined) {
|
|
409
|
+
requireCondition(snapshot.documents.length > 0 &&
|
|
410
|
+
hash(config.specification) === hash(this.#sourceIndex(snapshot)), "configuration_source_conflict", "Change specification sources through an explicit URL/path maintenance update.");
|
|
411
|
+
delete config.specification;
|
|
412
|
+
}
|
|
413
|
+
requireCondition(config.serviceUrl === undefined || nonempty(config.serviceUrl), "invalid_api_config", "Use one API service base URL.");
|
|
414
|
+
for (const key of ["authentication", "oauth", "sourceAuthentication"])
|
|
415
|
+
if (config[key] !== undefined)
|
|
416
|
+
requireCondition(object(config[key]), "invalid_api_config", "API authentication settings must be objects.");
|
|
417
|
+
config.authentication ??= {};
|
|
418
|
+
config.oauth ??= {};
|
|
419
|
+
requireCondition(Object.keys(config.authentication).every((key) => [
|
|
420
|
+
"credentialBindings",
|
|
421
|
+
"operationSelections",
|
|
422
|
+
"supplementalSchemes",
|
|
423
|
+
"supplementalSecurity",
|
|
424
|
+
].includes(key)), "invalid_api_config", "Authentication stores only supported non-secret bindings and scheme selections.");
|
|
425
|
+
for (const [key, value] of Object.entries(config.oauth))
|
|
426
|
+
config.oauth[key] = validateOAuthConfig(value);
|
|
427
|
+
if (config.sourceAuthentication !== undefined)
|
|
428
|
+
requireCondition(Object.keys(config.sourceAuthentication).every((key) => key === "headers") &&
|
|
429
|
+
object(config.sourceAuthentication.headers) &&
|
|
430
|
+
Object.values(config.sourceAuthentication.headers).every(credentialRef), "invalid_api_config", "Source authentication only stores protected header references.");
|
|
431
|
+
const bindings = config.authentication.credentialBindings ?? {};
|
|
432
|
+
requireCondition(object(bindings), "invalid_api_config", "API credential bindings must be an object.");
|
|
433
|
+
const retained = Object.create(null);
|
|
434
|
+
for (const [scheme, ref] of Object.entries(bindings)) {
|
|
435
|
+
requireCondition(credentialRef(ref), "credential_reference_invalid", "API authentication only stores protected credential references.");
|
|
436
|
+
const old = previous?.secrets[scheme];
|
|
437
|
+
requireCondition(old && old.ref === ref, "credential_binding_mismatch", "An API reference must belong to this approved target; configure new secrets in its authorization page.");
|
|
438
|
+
retained[scheme] = old;
|
|
439
|
+
}
|
|
440
|
+
if (previous?.secrets.source) {
|
|
441
|
+
const previousService = previous.secrets.source.binding.service;
|
|
442
|
+
const previousOrigin = typeof previousService === "string" &&
|
|
443
|
+
/^https?:/.test(previousService)
|
|
444
|
+
? new URL(previousService).origin
|
|
445
|
+
: null;
|
|
446
|
+
const nextOrigin = snapshot.source && /^https?:/.test(snapshot.source)
|
|
447
|
+
? new URL(snapshot.source).origin
|
|
448
|
+
: null;
|
|
449
|
+
if (previousOrigin !== null && previousOrigin === nextOrigin)
|
|
450
|
+
retained.source = previous.secrets.source;
|
|
451
|
+
else
|
|
452
|
+
delete config.sourceAuthentication;
|
|
453
|
+
}
|
|
454
|
+
snapshot.secrets = retained;
|
|
455
|
+
}
|
|
456
|
+
current(scope);
|
|
457
|
+
}
|
|
458
|
+
async #mcp(snapshot, scope) {
|
|
459
|
+
const value = json(snapshot.config);
|
|
460
|
+
delete value.credentialBindings;
|
|
461
|
+
delete value.oauth;
|
|
462
|
+
value.name = snapshot.name;
|
|
463
|
+
for (const [key, reference] of Object.entries(snapshot.secrets)) {
|
|
464
|
+
if (key === "oauth")
|
|
465
|
+
continue;
|
|
466
|
+
const at = key.indexOf("."), group = key.slice(0, at), field = key.slice(at + 1);
|
|
467
|
+
requireCondition(group === "env" || group === "headers", "invalid_mcp_config", "Unknown MCP credential destination.");
|
|
468
|
+
const saved = await this.options.credentials.read(reference.ref, reference.binding);
|
|
469
|
+
requireCondition(typeof saved.value === "string", "maintenance_auth_required", "The MCP credential is not configured.");
|
|
470
|
+
value[group] ??= Object.create(null);
|
|
471
|
+
put(value[group], field, saved.value);
|
|
472
|
+
}
|
|
473
|
+
current(scope);
|
|
474
|
+
return validateMcpConnectionConfig(value);
|
|
475
|
+
}
|
|
476
|
+
#documents(snapshot) {
|
|
477
|
+
requireCondition(snapshot.documents.length > 0, "configuration_source_unavailable", "The fixed API specification is unavailable.");
|
|
478
|
+
const docs = snapshot.documents.map((item) => ({
|
|
479
|
+
location: item.location,
|
|
480
|
+
bytes: Buffer.from(item.base64, "base64"),
|
|
481
|
+
}));
|
|
482
|
+
return { document: docs[0], references: docs.slice(1) };
|
|
483
|
+
}
|
|
484
|
+
async #parse(snapshot, scope) {
|
|
485
|
+
current(scope);
|
|
486
|
+
const docs = this.#documents(snapshot);
|
|
487
|
+
return parseOpenApi({
|
|
488
|
+
...docs,
|
|
489
|
+
name: snapshot.name,
|
|
490
|
+
revision: hash(snapshot.documents),
|
|
491
|
+
serviceUrl: snapshot.config.serviceUrl ?? snapshot.source,
|
|
492
|
+
}, openApiLimits({
|
|
493
|
+
documentBytes: this.options.maxSourceBytes ?? 8 * 1024 * 1024,
|
|
494
|
+
totalDocumentBytes: this.options.maxTotalSourceBytes ?? 32 * 1024 * 1024,
|
|
495
|
+
referenceCount: this.options.maxReferences ?? 128,
|
|
496
|
+
}), scope.signal);
|
|
497
|
+
}
|
|
498
|
+
async #sourceBytes(location, snapshot, scope) {
|
|
499
|
+
const maximum = this.options.maxSourceBytes ?? 8 * 1024 * 1024;
|
|
500
|
+
let url;
|
|
501
|
+
try {
|
|
502
|
+
url = new URL(location);
|
|
503
|
+
}
|
|
504
|
+
catch {
|
|
505
|
+
throw new AgentError("configuration_source_invalid", "Use an absolute fixed source URL or path.");
|
|
506
|
+
}
|
|
507
|
+
if (url.protocol === "file:") {
|
|
508
|
+
const requested = fileURLToPath(url);
|
|
509
|
+
access(scope, "path", requested);
|
|
510
|
+
const resolved = realpathSync.native(requested);
|
|
511
|
+
access(scope, "path", resolved);
|
|
512
|
+
const body = await readPublic(resolved, maximum);
|
|
513
|
+
requireCondition(body !== null, "configuration_source_unavailable", "The API source file is missing.");
|
|
514
|
+
current(scope);
|
|
515
|
+
return {
|
|
516
|
+
bytes: Buffer.from(body, "utf8"),
|
|
517
|
+
location: pathToFileURL(resolved).href,
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
requireCondition(["http:", "https:"].includes(url.protocol) &&
|
|
521
|
+
!url.username &&
|
|
522
|
+
!url.password &&
|
|
523
|
+
!url.hash, "configuration_source_invalid", "Use a credential-free HTTP(S) source endpoint.");
|
|
524
|
+
const credentialService = snapshot.secrets.source?.binding.service;
|
|
525
|
+
const credentialOrigin = typeof credentialService === "string" &&
|
|
526
|
+
/^https?:/.test(credentialService)
|
|
527
|
+
? new URL(credentialService).origin
|
|
528
|
+
: null, timeout = AbortSignal.timeout(this.options.sourceTimeoutMs ?? 30000), signal = AbortSignal.any([scope.signal, timeout]);
|
|
529
|
+
const publicAccept = "application/json, application/yaml, text/yaml, */*";
|
|
530
|
+
const headers = new Headers({ accept: publicAccept });
|
|
531
|
+
const source = snapshot.secrets.source;
|
|
532
|
+
if (source) {
|
|
533
|
+
const values = await this.options.credentials.read(source.ref, source.binding);
|
|
534
|
+
for (const [key, value] of Object.entries(values))
|
|
535
|
+
if (typeof value === "string") {
|
|
536
|
+
requireCondition(/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(key) &&
|
|
537
|
+
![
|
|
538
|
+
"host",
|
|
539
|
+
"content-length",
|
|
540
|
+
"connection",
|
|
541
|
+
"transfer-encoding",
|
|
542
|
+
"keep-alive",
|
|
543
|
+
"te",
|
|
544
|
+
"trailer",
|
|
545
|
+
"upgrade",
|
|
546
|
+
"proxy-authorization",
|
|
547
|
+
].includes(key.toLowerCase()) &&
|
|
548
|
+
!/[\0\r\n]/.test(value), "configuration_source_auth_invalid", "Source authentication needs safe explicit headers.");
|
|
549
|
+
headers.set(key, value);
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
for (let redirect = 0; redirect < 4; redirect++) {
|
|
553
|
+
access(scope, "url", url.href);
|
|
554
|
+
signal.throwIfAborted();
|
|
555
|
+
let response;
|
|
556
|
+
try {
|
|
557
|
+
response = await fetch(url, {
|
|
558
|
+
headers: url.origin === credentialOrigin
|
|
559
|
+
? headers
|
|
560
|
+
: new Headers({ accept: publicAccept }),
|
|
561
|
+
redirect: "manual",
|
|
562
|
+
signal,
|
|
563
|
+
});
|
|
564
|
+
}
|
|
565
|
+
catch {
|
|
566
|
+
signal.throwIfAborted();
|
|
567
|
+
throw new AgentError("configuration_source_unavailable", "The API source endpoint could not be read.");
|
|
568
|
+
}
|
|
569
|
+
if ([301, 302, 303, 307, 308].includes(response.status)) {
|
|
570
|
+
const target = response.headers.get("location");
|
|
571
|
+
await response.body?.cancel();
|
|
572
|
+
requireCondition(target !== null && redirect < 3, "configuration_source_redirect", "The API source returned an unsupported redirect.");
|
|
573
|
+
const next = new URL(target, url);
|
|
574
|
+
requireCondition(["http:", "https:"].includes(next.protocol) &&
|
|
575
|
+
!next.username &&
|
|
576
|
+
!next.password &&
|
|
577
|
+
!next.hash, "configuration_source_redirect", "The source redirect target is invalid.");
|
|
578
|
+
access(scope, "url", next.href);
|
|
579
|
+
url = next;
|
|
580
|
+
continue;
|
|
581
|
+
}
|
|
582
|
+
if (response.status === 401 || response.status === 403) {
|
|
583
|
+
await response.body?.cancel();
|
|
584
|
+
throw new AgentError("configuration_source_auth_required", "The specification endpoint needs source authentication.");
|
|
585
|
+
}
|
|
586
|
+
if (!response.ok) {
|
|
587
|
+
await response.body?.cancel();
|
|
588
|
+
throw new AgentError("configuration_source_unavailable", "The API source returned an unsuccessful response.");
|
|
589
|
+
}
|
|
590
|
+
const declared = response.headers.get("content-length");
|
|
591
|
+
if (declared !== null &&
|
|
592
|
+
/^\d+$/.test(declared) &&
|
|
593
|
+
Number(declared) > maximum) {
|
|
594
|
+
await response.body?.cancel();
|
|
595
|
+
throw new AgentError("configuration_source_too_large", "The API source exceeds its byte budget.");
|
|
596
|
+
}
|
|
597
|
+
const chunks = [];
|
|
598
|
+
let count = 0;
|
|
599
|
+
const reader = response.body?.getReader();
|
|
600
|
+
try {
|
|
601
|
+
if (reader)
|
|
602
|
+
while (true) {
|
|
603
|
+
current(scope);
|
|
604
|
+
const step = await reader.read();
|
|
605
|
+
current(scope);
|
|
606
|
+
if (step.done)
|
|
607
|
+
break;
|
|
608
|
+
count += step.value.byteLength;
|
|
609
|
+
requireCondition(count <= maximum, "configuration_source_too_large", "The API source exceeds its byte budget.");
|
|
610
|
+
chunks.push(step.value);
|
|
611
|
+
}
|
|
612
|
+
}
|
|
613
|
+
catch (cause) {
|
|
614
|
+
await reader?.cancel().catch(() => { });
|
|
615
|
+
signal.throwIfAborted();
|
|
616
|
+
if (isAgentError(cause))
|
|
617
|
+
throw cause;
|
|
618
|
+
throw new AgentError("configuration_source_unavailable", "The API source stream did not complete.");
|
|
619
|
+
}
|
|
620
|
+
finally {
|
|
621
|
+
reader?.releaseLock();
|
|
622
|
+
}
|
|
623
|
+
current(scope);
|
|
624
|
+
return { bytes: Buffer.concat(chunks, count), location: url.href };
|
|
625
|
+
}
|
|
626
|
+
throw new AgentError("configuration_source_redirect", "The API source exceeded its redirect limit.");
|
|
627
|
+
}
|
|
628
|
+
async #readSources(snapshot, scope) {
|
|
629
|
+
requireCondition(snapshot.source !== null, "configuration_source_unavailable", "API import requires a specification source.");
|
|
630
|
+
const sources = [], queued = [snapshot.source], seen = new Set();
|
|
631
|
+
let total = 0;
|
|
632
|
+
while (queued.length) {
|
|
633
|
+
const location = queued.shift();
|
|
634
|
+
if (seen.has(location))
|
|
635
|
+
continue;
|
|
636
|
+
requireCondition(seen.size < (this.options.maxReferences ?? 128) + 1, "configuration_source_too_large", "The API has too many referenced source documents.");
|
|
637
|
+
seen.add(location);
|
|
638
|
+
let source;
|
|
639
|
+
try {
|
|
640
|
+
source = await this.#sourceBytes(location, snapshot, scope);
|
|
641
|
+
}
|
|
642
|
+
catch (cause) {
|
|
643
|
+
if (isAgentError(cause) &&
|
|
644
|
+
cause.code === "configuration_source_auth_required" &&
|
|
645
|
+
!sources.length) {
|
|
646
|
+
snapshot.documents = [];
|
|
647
|
+
snapshot.diagnostics = [
|
|
648
|
+
"The specification endpoint needs source authentication.",
|
|
649
|
+
];
|
|
650
|
+
snapshot.authStatus = "required";
|
|
651
|
+
return;
|
|
652
|
+
}
|
|
653
|
+
throw cause;
|
|
654
|
+
}
|
|
655
|
+
total += source.bytes.byteLength;
|
|
656
|
+
requireCondition(total <= (this.options.maxTotalSourceBytes ?? 32 * 1024 * 1024), "configuration_source_too_large", "API source documents exceed their total byte budget.");
|
|
657
|
+
let value;
|
|
658
|
+
try {
|
|
659
|
+
const text = new TextDecoder("utf-8", { fatal: true }).decode(source.bytes), doc = parseDocument(text, { uniqueKeys: true });
|
|
660
|
+
requireCondition(doc.errors.length === 0, "configuration_source_invalid", "The API source is not valid JSON/YAML.");
|
|
661
|
+
value = doc.toJS({ maxAliasCount: 100 });
|
|
662
|
+
canonicalJson(value, Math.max(source.bytes.byteLength * 4, 65536));
|
|
663
|
+
}
|
|
664
|
+
catch (cause) {
|
|
665
|
+
if (isAgentError(cause))
|
|
666
|
+
throw cause;
|
|
667
|
+
throw new AgentError("configuration_source_invalid", "The API source is not valid bounded UTF-8 JSON/YAML.");
|
|
668
|
+
}
|
|
669
|
+
const file = sources.length === 0
|
|
670
|
+
? source.bytes.toString("utf8").trimStart().startsWith("{")
|
|
671
|
+
? "openapi.json"
|
|
672
|
+
: "openapi.yaml"
|
|
673
|
+
: `refs/ref-${hash(source.location)}.json`;
|
|
674
|
+
sources.push({
|
|
675
|
+
location: source.location,
|
|
676
|
+
base64: source.bytes.toString("base64"),
|
|
677
|
+
file,
|
|
678
|
+
});
|
|
679
|
+
if (source.location !== location)
|
|
680
|
+
seen.add(source.location);
|
|
681
|
+
const stack = [value];
|
|
682
|
+
let nodes = 0;
|
|
683
|
+
const visited = new Set();
|
|
684
|
+
while (stack.length) {
|
|
685
|
+
const item = stack.pop();
|
|
686
|
+
if (!item || typeof item !== "object" || visited.has(item))
|
|
687
|
+
continue;
|
|
688
|
+
visited.add(item);
|
|
689
|
+
requireCondition(++nodes <= 100000, "configuration_source_too_large", "The API source has too many nested objects.");
|
|
690
|
+
for (const [key, child] of Object.entries(item)) {
|
|
691
|
+
if (key === "$ref" &&
|
|
692
|
+
typeof child === "string" &&
|
|
693
|
+
!child.startsWith("#")) {
|
|
694
|
+
let target;
|
|
695
|
+
try {
|
|
696
|
+
target = new URL(child, source.location);
|
|
697
|
+
}
|
|
698
|
+
catch {
|
|
699
|
+
throw new AgentError("configuration_source_invalid", "An API reference URL is invalid.");
|
|
700
|
+
}
|
|
701
|
+
target.hash = "";
|
|
702
|
+
if (!seen.has(target.href))
|
|
703
|
+
queued.push(target.href);
|
|
704
|
+
}
|
|
705
|
+
else if (child && typeof child === "object")
|
|
706
|
+
stack.push(child);
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
snapshot.documents = sources;
|
|
711
|
+
snapshot.diagnostics = [];
|
|
712
|
+
}
|
|
713
|
+
async #definitions(snapshot, scope) {
|
|
714
|
+
const parsed = await this.#parse(snapshot, scope), document = parsed.document, config = snapshot.config;
|
|
715
|
+
const raw = parsed.sourceVersion === "2.0"
|
|
716
|
+
? document.securityDefinitions
|
|
717
|
+
: document.components?.securitySchemes, definitions = Object.create(null);
|
|
718
|
+
for (const [key, value] of Object.entries(raw ?? {}))
|
|
719
|
+
definitions[key] = parsed.resolve(value);
|
|
720
|
+
Object.assign(definitions, config.authentication?.supplementalSchemes ?? {});
|
|
721
|
+
return { definitions, parsed };
|
|
722
|
+
}
|
|
723
|
+
#fields(definition) {
|
|
724
|
+
if (definition.type === "apiKey")
|
|
725
|
+
return ["value"];
|
|
726
|
+
if (definition.type === "basic" ||
|
|
727
|
+
(definition.type === "http" &&
|
|
728
|
+
definition.scheme?.toLowerCase() === "basic"))
|
|
729
|
+
return ["username", "password"];
|
|
730
|
+
if (definition.type === "http" &&
|
|
731
|
+
definition.scheme?.toLowerCase() === "bearer")
|
|
732
|
+
return ["token"];
|
|
733
|
+
if (definition.type === "mutualTLS")
|
|
734
|
+
return ["cert", "key", "ca"];
|
|
735
|
+
if (definition.type === "oauth2" || definition.type === "openIdConnect")
|
|
736
|
+
return ["clientSecret"];
|
|
737
|
+
throw new AgentError("api_unsupported_authentication", "The authentication scheme needs an implemented credential provider.");
|
|
738
|
+
}
|
|
739
|
+
async #apiInput(snapshot, scope, placeholder) {
|
|
740
|
+
const { definitions, parsed } = await this.#definitions(snapshot, scope), config = snapshot.config, docs = this.#documents(snapshot), authentication = json(config.authentication ?? {});
|
|
741
|
+
authentication.credentialBindings = {};
|
|
742
|
+
for (const [key] of Object.entries(definitions)) {
|
|
743
|
+
const secret = snapshot.secrets[key];
|
|
744
|
+
if (secret)
|
|
745
|
+
put(authentication.credentialBindings, key, secret.ref);
|
|
746
|
+
else if (placeholder)
|
|
747
|
+
put(authentication.credentialBindings, key, `unconfigured_${key}`);
|
|
748
|
+
}
|
|
749
|
+
if (!config.serviceUrl) {
|
|
750
|
+
const document = parsed.document;
|
|
751
|
+
let service = parsed.sourceVersion === "2.0" && document.host
|
|
752
|
+
? `${document.schemes?.[0] ?? "https"}://${document.host}${document.basePath ?? ""}`
|
|
753
|
+
: document.servers?.[0]?.url;
|
|
754
|
+
if (service && snapshot.source)
|
|
755
|
+
service = new URL(service, snapshot.source).href;
|
|
756
|
+
requireCondition(nonempty(service), "api_service_required", "Set the API serviceUrl before confirmation.");
|
|
757
|
+
config.serviceUrl = service;
|
|
758
|
+
}
|
|
759
|
+
return {
|
|
760
|
+
name: snapshot.name,
|
|
761
|
+
revision: hash(snapshot),
|
|
762
|
+
...docs,
|
|
763
|
+
serviceUrl: config.serviceUrl,
|
|
764
|
+
authentication,
|
|
765
|
+
};
|
|
766
|
+
}
|
|
767
|
+
async #validate(snapshot, scope) {
|
|
768
|
+
if (snapshot.kind === "mcp") {
|
|
769
|
+
await this.#mcp(snapshot, scope);
|
|
770
|
+
const config = snapshot.config, secret = snapshot.secrets.oauth;
|
|
771
|
+
snapshot.authStatus = config.oauth
|
|
772
|
+
? secret &&
|
|
773
|
+
this.options.mcpOAuth &&
|
|
774
|
+
(await this.options.mcpOAuth.ready(config.oauth, secret.ref, secret.binding, scope))
|
|
775
|
+
? "ready"
|
|
776
|
+
: "required"
|
|
777
|
+
: Object.keys(snapshot.secrets).length
|
|
778
|
+
? "ready"
|
|
779
|
+
: "not_required";
|
|
780
|
+
return;
|
|
781
|
+
}
|
|
782
|
+
if (!snapshot.documents.length) {
|
|
783
|
+
snapshot.authStatus = "required";
|
|
784
|
+
return;
|
|
785
|
+
}
|
|
786
|
+
const { definitions, parsed } = await this.#definitions(snapshot, scope), config = snapshot.config;
|
|
787
|
+
for (const [key, definition] of Object.entries(definitions)) {
|
|
788
|
+
const prior = snapshot.secrets[key], binding = this.#binding(snapshot, key, {
|
|
789
|
+
definition,
|
|
790
|
+
oauth: config.oauth?.[key] ?? null,
|
|
791
|
+
});
|
|
792
|
+
if (prior && hash(prior.binding) !== hash(binding)) {
|
|
793
|
+
const value = await this.options.credentials.read(prior.ref, prior.binding);
|
|
794
|
+
snapshot.secrets[key] = {
|
|
795
|
+
ref: await this.options.credentials.create(binding, value),
|
|
796
|
+
binding,
|
|
797
|
+
};
|
|
798
|
+
}
|
|
799
|
+
if (!prior &&
|
|
800
|
+
object(config.oauth?.[key]) &&
|
|
801
|
+
["oauth2", "openIdConnect"].includes(definition.type))
|
|
802
|
+
snapshot.secrets[key] = {
|
|
803
|
+
ref: await this.options.credentials.create(binding, {}),
|
|
804
|
+
binding,
|
|
805
|
+
};
|
|
806
|
+
config.authentication ??= {};
|
|
807
|
+
config.authentication.credentialBindings ??= {};
|
|
808
|
+
if (snapshot.secrets[key])
|
|
809
|
+
put(config.authentication.credentialBindings, key, snapshot.secrets[key].ref);
|
|
810
|
+
}
|
|
811
|
+
requireCondition(Object.keys(config.oauth ?? {}).every((key) => Object.hasOwn(definitions, key) &&
|
|
812
|
+
["oauth2", "openIdConnect"].includes(definitions[key].type)), "invalid_api_config", "OAuth settings must name declared OAuth/OIDC security schemes.");
|
|
813
|
+
await prepareOpenApi(await this.#apiInput(snapshot, scope, true), {
|
|
814
|
+
signal: scope.signal,
|
|
815
|
+
credentials: this.#runtimeCredentials(snapshot).provider,
|
|
816
|
+
});
|
|
817
|
+
const ready = new Set();
|
|
818
|
+
for (const [key, definition] of Object.entries(definitions)) {
|
|
819
|
+
const secret = snapshot.secrets[key];
|
|
820
|
+
if (!secret)
|
|
821
|
+
continue;
|
|
822
|
+
const value = await this.options.credentials.read(secret.ref, secret.binding), fields = this.#fields(definition);
|
|
823
|
+
if (definition.type === "oauth2" || definition.type === "openIdConnect") {
|
|
824
|
+
if (object(value.tokens) &&
|
|
825
|
+
typeof value.tokens.access_token === "string" &&
|
|
826
|
+
value.tokens.token_type === "Bearer" &&
|
|
827
|
+
value.oauthConfigHash === hash(config.oauth?.[key] ?? null) &&
|
|
828
|
+
(value.tokens.expiresAt === null ||
|
|
829
|
+
value.tokens.expiresAt > Date.now() + 5000 ||
|
|
830
|
+
typeof value.tokens.refresh_token === "string" ||
|
|
831
|
+
config.oauth?.[key]?.flow === "clientCredentials"))
|
|
832
|
+
ready.add(key);
|
|
833
|
+
}
|
|
834
|
+
else if (fields
|
|
835
|
+
.filter((field) => field !== "ca")
|
|
836
|
+
.every((field) => typeof value[field] === "string" &&
|
|
837
|
+
value[field].length > 0))
|
|
838
|
+
ready.add(key);
|
|
839
|
+
}
|
|
840
|
+
let required = false, used = false;
|
|
841
|
+
const document = parsed.document;
|
|
842
|
+
for (const [pathname, item] of Object.entries(document.paths ?? {}))
|
|
843
|
+
for (const [method, operation] of Object.entries(item))
|
|
844
|
+
if ([
|
|
845
|
+
"get",
|
|
846
|
+
"post",
|
|
847
|
+
"put",
|
|
848
|
+
"patch",
|
|
849
|
+
"delete",
|
|
850
|
+
"options",
|
|
851
|
+
"head",
|
|
852
|
+
"trace",
|
|
853
|
+
].includes(method) &&
|
|
854
|
+
object(operation)) {
|
|
855
|
+
const alternatives = operation.security ??
|
|
856
|
+
config.authentication.supplementalSecurity ??
|
|
857
|
+
document.security ??
|
|
858
|
+
[], operationName = operation.operationId ?? `${method.toUpperCase()} ${pathname}`, selection = config.authentication.operationSelections?.[operationName], options = selection === undefined
|
|
859
|
+
? alternatives
|
|
860
|
+
: [alternatives[selection]];
|
|
861
|
+
used ||= alternatives.some((alternative) => Object.keys(alternative).length > 0);
|
|
862
|
+
if (alternatives.length &&
|
|
863
|
+
!options.some((alternative) => object(alternative) &&
|
|
864
|
+
Object.entries(alternative).every(([key, scopes]) => ready.has(key) &&
|
|
865
|
+
(!object(config.oauth?.[key]) ||
|
|
866
|
+
(Array.isArray(scopes) &&
|
|
867
|
+
scopes.every((scope) => config.oauth[key].scopes.includes(scope)))))))
|
|
868
|
+
required = true;
|
|
869
|
+
}
|
|
870
|
+
snapshot.authStatus = required
|
|
871
|
+
? "required"
|
|
872
|
+
: used
|
|
873
|
+
? "ready"
|
|
874
|
+
: "not_required";
|
|
875
|
+
}
|
|
876
|
+
async readDraft(intent, candidate, scope) {
|
|
877
|
+
const snapshot = await this.#load(intent, candidate, scope), state = await this.#approved(), previous = await this.#previous(entry(state[snapshot.kind], snapshot.name));
|
|
878
|
+
const authentication = [], security = [];
|
|
879
|
+
if (snapshot.kind === "mcp") {
|
|
880
|
+
for (const [key, reference] of Object.entries(snapshot.secrets))
|
|
881
|
+
if (key !== "oauth")
|
|
882
|
+
authentication.push({
|
|
883
|
+
id: key,
|
|
884
|
+
type: key.startsWith("env.") ? "environment" : "header",
|
|
885
|
+
oauth: false,
|
|
886
|
+
fields: [
|
|
887
|
+
{ key, label: key, configured: !!reference, required: true },
|
|
888
|
+
],
|
|
889
|
+
});
|
|
890
|
+
if (snapshot.config.oauth) {
|
|
891
|
+
const values = snapshot.secrets.oauth
|
|
892
|
+
? await this.options.credentials.read(snapshot.secrets.oauth.ref, snapshot.secrets.oauth.binding)
|
|
893
|
+
: {};
|
|
894
|
+
authentication.push({
|
|
895
|
+
id: "oauth",
|
|
896
|
+
type: "oauth2",
|
|
897
|
+
oauth: true,
|
|
898
|
+
flow: snapshot.config.oauth.flow ??
|
|
899
|
+
"authorizationCode",
|
|
900
|
+
fields: [
|
|
901
|
+
{
|
|
902
|
+
key: "oauth.clientSecret",
|
|
903
|
+
label: "Client secret",
|
|
904
|
+
configured: typeof values.clientSecret === "string",
|
|
905
|
+
required: false,
|
|
906
|
+
},
|
|
907
|
+
],
|
|
908
|
+
});
|
|
909
|
+
}
|
|
910
|
+
}
|
|
911
|
+
else {
|
|
912
|
+
if (snapshot.documents.length) {
|
|
913
|
+
const { definitions, parsed } = await this.#definitions(snapshot, scope);
|
|
914
|
+
for (const [id, definition] of Object.entries(definitions)) {
|
|
915
|
+
const secret = snapshot.secrets[id], values = secret
|
|
916
|
+
? await this.options.credentials.read(secret.ref, secret.binding)
|
|
917
|
+
: {};
|
|
918
|
+
authentication.push({
|
|
919
|
+
id,
|
|
920
|
+
type: definition.type === "http" ? definition.scheme : definition.type,
|
|
921
|
+
...(typeof definition.in === "string"
|
|
922
|
+
? { location: definition.in }
|
|
923
|
+
: {}),
|
|
924
|
+
...(typeof definition.name === "string"
|
|
925
|
+
? { name: definition.name }
|
|
926
|
+
: {}),
|
|
927
|
+
oauth: ["oauth2", "openIdConnect"].includes(definition.type),
|
|
928
|
+
...(snapshot.config.oauth?.[id]?.flow
|
|
929
|
+
? { flow: snapshot.config.oauth[id].flow }
|
|
930
|
+
: {}),
|
|
931
|
+
fields: this.#fields(definition).map((field) => ({
|
|
932
|
+
key: `${id}.${field}`,
|
|
933
|
+
label: field,
|
|
934
|
+
configured: typeof values[field] === "string" && !!values[field],
|
|
935
|
+
required: !["ca", "clientSecret"].includes(field),
|
|
936
|
+
})),
|
|
937
|
+
});
|
|
938
|
+
}
|
|
939
|
+
for (const requirement of parsed.document.security ??
|
|
940
|
+
[])
|
|
941
|
+
security.push(Object.keys(requirement));
|
|
942
|
+
}
|
|
943
|
+
if (!snapshot.documents.length ||
|
|
944
|
+
snapshot.secrets.source ||
|
|
945
|
+
snapshot.config.sourceAuthentication) {
|
|
946
|
+
const values = snapshot.secrets.source
|
|
947
|
+
? await this.options.credentials.read(snapshot.secrets.source.ref, snapshot.secrets.source.binding)
|
|
948
|
+
: {}, fields = new Set([
|
|
949
|
+
"Authorization",
|
|
950
|
+
...Object.keys(values),
|
|
951
|
+
...Object.keys(snapshot.config.sourceAuthentication?.headers ??
|
|
952
|
+
{}),
|
|
953
|
+
]);
|
|
954
|
+
authentication.push({
|
|
955
|
+
id: "source",
|
|
956
|
+
type: "sourceHeaders",
|
|
957
|
+
oauth: false,
|
|
958
|
+
fields: [...fields].map((field) => ({
|
|
959
|
+
key: `source.${field}`,
|
|
960
|
+
label: `Source ${field}`,
|
|
961
|
+
configured: typeof values[field] === "string" && !!values[field],
|
|
962
|
+
required: !snapshot.documents.length,
|
|
963
|
+
})),
|
|
964
|
+
});
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
current(scope);
|
|
968
|
+
return {
|
|
969
|
+
config: json(snapshot.config),
|
|
970
|
+
...(previous ? { currentConfig: json(previous.config) } : {}),
|
|
971
|
+
authentication,
|
|
972
|
+
security,
|
|
973
|
+
diagnostics: [...snapshot.diagnostics],
|
|
974
|
+
};
|
|
975
|
+
}
|
|
976
|
+
async prepareDraft(intent, candidate, input, scope) {
|
|
977
|
+
const original = await this.#load(intent, candidate, scope), snapshot = json(original);
|
|
978
|
+
snapshot.config = json(input.config ?? snapshot.config);
|
|
979
|
+
snapshot.diagnostics = [];
|
|
980
|
+
if (intent.action === "remove") {
|
|
981
|
+
requireCondition(input.config === undefined && !input.credentials?.length, "maintenance_target_fixed", "Deletion only confirms the fixed target; it cannot edit configuration.");
|
|
982
|
+
return candidate;
|
|
983
|
+
}
|
|
984
|
+
await this.#normalize(snapshot, scope, original);
|
|
985
|
+
await this.#isolate(snapshot);
|
|
986
|
+
const definitions = snapshot.kind === "api" && snapshot.documents.length
|
|
987
|
+
? (await this.#definitions(snapshot, scope)).definitions
|
|
988
|
+
: {};
|
|
989
|
+
const edits = new Map();
|
|
990
|
+
for (const change of input.credentials ?? []) {
|
|
991
|
+
requireCondition(nonempty(change.key, 1024) &&
|
|
992
|
+
["keep", "replace", "clear"].includes(change.operation), "credential_change_invalid", "Use a declared credential field operation.");
|
|
993
|
+
let scheme, field;
|
|
994
|
+
if (snapshot.kind === "mcp" && /^(?:env|headers)\./.test(change.key)) {
|
|
995
|
+
scheme = change.key;
|
|
996
|
+
field = "value";
|
|
997
|
+
}
|
|
998
|
+
else {
|
|
999
|
+
const at = change.key.lastIndexOf(".");
|
|
1000
|
+
requireCondition(at > 0, "credential_change_invalid", "Credential changes need a scheme and field.");
|
|
1001
|
+
scheme = change.key.slice(0, at);
|
|
1002
|
+
field = change.key.slice(at + 1);
|
|
1003
|
+
}
|
|
1004
|
+
const definition = definitions[scheme];
|
|
1005
|
+
requireCondition(snapshot.kind === "mcp"
|
|
1006
|
+
? scheme === "oauth"
|
|
1007
|
+
? field === "clientSecret"
|
|
1008
|
+
: /^(?:env|headers)\.[^\0\r\n]{1,256}$/.test(scheme)
|
|
1009
|
+
: scheme === "source"
|
|
1010
|
+
? /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/.test(field)
|
|
1011
|
+
: object(definition) && this.#fields(definition).includes(field), "credential_change_invalid", "The credential field is not part of this target's authentication.");
|
|
1012
|
+
requireCondition(change.operation === "replace"
|
|
1013
|
+
? typeof change.value === "string" &&
|
|
1014
|
+
change.value.length > 0 &&
|
|
1015
|
+
Buffer.byteLength(change.value) <= 1024 * 1024
|
|
1016
|
+
: change.value === undefined, "credential_change_invalid", "A replacement needs one bounded secret; keep/clear do not accept values.");
|
|
1017
|
+
let value = edits.get(scheme);
|
|
1018
|
+
if (!value) {
|
|
1019
|
+
const old = snapshot.secrets[scheme];
|
|
1020
|
+
value = old
|
|
1021
|
+
? await this.options.credentials.read(old.ref, old.binding)
|
|
1022
|
+
: {};
|
|
1023
|
+
edits.set(scheme, value);
|
|
1024
|
+
}
|
|
1025
|
+
if (change.operation === "keep")
|
|
1026
|
+
requireCondition(typeof value[field] === "string", "credential_change_invalid", "There is no configured value to keep.");
|
|
1027
|
+
if (change.operation === "replace")
|
|
1028
|
+
put(value, field, change.value);
|
|
1029
|
+
if (change.operation === "clear") {
|
|
1030
|
+
delete value[field];
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
for (const [scheme, value] of edits) {
|
|
1034
|
+
const config = snapshot.config, definition = scheme === "source"
|
|
1035
|
+
? { headers: Object.keys(value) }
|
|
1036
|
+
: snapshot.kind === "mcp"
|
|
1037
|
+
? scheme === "oauth"
|
|
1038
|
+
? config.oauth
|
|
1039
|
+
: {
|
|
1040
|
+
group: scheme.split(".")[0],
|
|
1041
|
+
key: scheme.slice(scheme.indexOf(".") + 1),
|
|
1042
|
+
}
|
|
1043
|
+
: {
|
|
1044
|
+
definition: definitions[scheme],
|
|
1045
|
+
oauth: config.oauth?.[scheme] ?? null,
|
|
1046
|
+
}, binding = this.#binding(snapshot, scheme, definition);
|
|
1047
|
+
if (!Object.keys(value).length)
|
|
1048
|
+
delete snapshot.secrets[scheme];
|
|
1049
|
+
else
|
|
1050
|
+
snapshot.secrets[scheme] = {
|
|
1051
|
+
ref: await this.options.credentials.create(binding, value),
|
|
1052
|
+
binding,
|
|
1053
|
+
};
|
|
1054
|
+
if (snapshot.kind === "api" && scheme !== "source") {
|
|
1055
|
+
config.authentication ??= {};
|
|
1056
|
+
config.authentication.credentialBindings ??= {};
|
|
1057
|
+
if (snapshot.secrets[scheme])
|
|
1058
|
+
put(config.authentication.credentialBindings, scheme, snapshot.secrets[scheme].ref);
|
|
1059
|
+
else
|
|
1060
|
+
delete config.authentication.credentialBindings[scheme];
|
|
1061
|
+
}
|
|
1062
|
+
if (snapshot.kind === "mcp" && scheme !== "oauth") {
|
|
1063
|
+
config.credentialBindings ??= {};
|
|
1064
|
+
if (snapshot.secrets[scheme])
|
|
1065
|
+
put(config.credentialBindings, scheme, snapshot.secrets[scheme].ref);
|
|
1066
|
+
else
|
|
1067
|
+
delete config.credentialBindings[scheme];
|
|
1068
|
+
}
|
|
1069
|
+
if (scheme === "source")
|
|
1070
|
+
config.sourceAuthentication = {
|
|
1071
|
+
headers: Object.fromEntries(Object.keys(value).map((key) => [
|
|
1072
|
+
key,
|
|
1073
|
+
snapshot.secrets.source.ref,
|
|
1074
|
+
])),
|
|
1075
|
+
};
|
|
1076
|
+
}
|
|
1077
|
+
if (snapshot.kind === "api" && !snapshot.documents.length)
|
|
1078
|
+
await this.#readSources(snapshot, scope);
|
|
1079
|
+
await this.#validate(snapshot, scope);
|
|
1080
|
+
if (snapshot.kind === "api" && this.options.oauth)
|
|
1081
|
+
for (const [scheme, raw] of Object.entries(snapshot.config.oauth ?? {})) {
|
|
1082
|
+
const config = raw, secret = snapshot.secrets[scheme];
|
|
1083
|
+
if (config.flow === "clientCredentials" && secret) {
|
|
1084
|
+
await this.options.oauth.prepareAuth(config, secret.ref, secret.binding, scope);
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
await this.#validate(snapshot, scope);
|
|
1088
|
+
return this.#save(snapshot);
|
|
1089
|
+
}
|
|
1090
|
+
async startOAuth(intent, candidate, binding, scope) {
|
|
1091
|
+
const snapshot = await this.#load(intent, candidate, scope), config = snapshot.config, scheme = binding.schemeId, secret = snapshot.secrets[scheme];
|
|
1092
|
+
requireCondition(secret, "maintenance_auth_required", "Save this authentication configuration before beginning OAuth.");
|
|
1093
|
+
if (snapshot.kind === "mcp") {
|
|
1094
|
+
requireCondition(scheme === "oauth" && this.options.mcpOAuth && object(config.oauth), "maintenance_oauth_unavailable", "The official MCP OAuth provider is unavailable.");
|
|
1095
|
+
return this.options.mcpOAuth.start(config.oauth, secret.ref, secret.binding, binding, scope);
|
|
1096
|
+
}
|
|
1097
|
+
requireCondition(this.options.oauthSessions && object(config.oauth?.[scheme]), "maintenance_oauth_unavailable", "Configure a supported OAuth flow before beginning authorization.");
|
|
1098
|
+
return this.options.oauthSessions.start(config.oauth[scheme], secret.ref, secret.binding, binding, scope);
|
|
1099
|
+
}
|
|
1100
|
+
async completeOAuth(intent, candidate, input, scope) {
|
|
1101
|
+
const snapshot = await this.#load(intent, candidate, scope), scheme = input.schemeId, secret = snapshot.secrets[scheme], config = snapshot.config;
|
|
1102
|
+
requireCondition(secret, "maintenance_auth_required", "The original protected OAuth reference is unavailable.");
|
|
1103
|
+
let ref;
|
|
1104
|
+
if (snapshot.kind === "mcp") {
|
|
1105
|
+
requireCondition(scheme === "oauth" && this.options.mcpOAuth && object(config.oauth), "maintenance_oauth_unavailable", "The official MCP OAuth provider is unavailable.");
|
|
1106
|
+
ref = await this.options.mcpOAuth.complete(config.oauth, secret.ref, secret.binding, input, scope);
|
|
1107
|
+
}
|
|
1108
|
+
else {
|
|
1109
|
+
requireCondition(this.options.oauthSessions && object(config.oauth?.[scheme]), "maintenance_oauth_unavailable", "The OAuth session provider is unavailable.");
|
|
1110
|
+
ref = await this.options.oauthSessions.complete(config.oauth[scheme], secret.ref, secret.binding, input, scope);
|
|
1111
|
+
}
|
|
1112
|
+
snapshot.secrets[scheme] = { ref, binding: secret.binding };
|
|
1113
|
+
await this.#validate(snapshot, scope);
|
|
1114
|
+
return this.#save(snapshot);
|
|
1115
|
+
}
|
|
1116
|
+
async verify(intent, candidate, scope) {
|
|
1117
|
+
const snapshot = await this.#load(intent, candidate, scope), state = await this.#approved(), old = entry(state[snapshot.kind], snapshot.name);
|
|
1118
|
+
requireCondition((old?.revision ?? null) === snapshot.baseRevision &&
|
|
1119
|
+
(old?.objectId ?? snapshot.objectId) === snapshot.objectId, "maintenance_precondition_changed", "The approved target changed after this candidate was prepared.");
|
|
1120
|
+
requireCondition((await this.#workRevision(snapshot.kind, snapshot.name)) ===
|
|
1121
|
+
snapshot.workRevision, "maintenance_precondition_changed", "The public configuration changed after this candidate was prepared.");
|
|
1122
|
+
if (intent.action !== "remove") {
|
|
1123
|
+
for (const reference of Object.values(snapshot.secrets))
|
|
1124
|
+
await this.options.credentials.read(reference.ref, reference.binding);
|
|
1125
|
+
await this.#validate(snapshot, scope);
|
|
1126
|
+
requireCondition(snapshot.authStatus === candidate.authStatus, "maintenance_precondition_changed", "The candidate authentication state changed; refresh its exact draft before approval.");
|
|
1127
|
+
}
|
|
1128
|
+
current(scope);
|
|
1129
|
+
}
|
|
1130
|
+
async #publicWritePlan(snapshot, remove = false) {
|
|
1131
|
+
const file = this.#publicLocation(snapshot.kind, snapshot.name), before = await readPublic(file);
|
|
1132
|
+
const plan = {
|
|
1133
|
+
file,
|
|
1134
|
+
before,
|
|
1135
|
+
after: this.#publicText(snapshot, before, remove),
|
|
1136
|
+
documents: [],
|
|
1137
|
+
};
|
|
1138
|
+
if (snapshot.kind === "mcp" || remove)
|
|
1139
|
+
return plan;
|
|
1140
|
+
let previousBytes = 0;
|
|
1141
|
+
for (const document of snapshot.documents) {
|
|
1142
|
+
const parts = document.file.split("/"), target = publicFile(this.options.root, [
|
|
1143
|
+
"api",
|
|
1144
|
+
configurationDirectoryName(snapshot.name),
|
|
1145
|
+
...parts,
|
|
1146
|
+
]);
|
|
1147
|
+
const previous = await readPublic(target, this.options.maxSourceBytes ?? 8 * 1024 * 1024);
|
|
1148
|
+
previousBytes += Buffer.byteLength(previous ?? "");
|
|
1149
|
+
requireCondition(previousBytes <= (this.options.maxTotalSourceBytes ?? 32 * 1024 * 1024), "configuration_source_too_large", "Existing public source rollback data exceeds the configured fixed-source budget.");
|
|
1150
|
+
plan.documents.push({
|
|
1151
|
+
file: target,
|
|
1152
|
+
before: previous,
|
|
1153
|
+
after: Buffer.from(document.base64, "base64").toString("utf8"),
|
|
1154
|
+
});
|
|
1155
|
+
}
|
|
1156
|
+
return plan;
|
|
1157
|
+
}
|
|
1158
|
+
async #writePublic(plan) {
|
|
1159
|
+
requireCondition((await readPublic(plan.file)) === plan.before, "maintenance_precondition_changed", "The public configuration changed while managed storage was being reserved.");
|
|
1160
|
+
const written = [];
|
|
1161
|
+
try {
|
|
1162
|
+
for (const document of plan.documents) {
|
|
1163
|
+
requireCondition((await readPublic(document.file, this.options.maxSourceBytes ?? 8 * 1024 * 1024)) === document.before, "maintenance_precondition_changed", "A fixed public source changed while managed storage was being reserved.");
|
|
1164
|
+
await replacePublic(document.file, document.after);
|
|
1165
|
+
written.push(document);
|
|
1166
|
+
}
|
|
1167
|
+
requireCondition((await readPublic(plan.file)) === plan.before, "maintenance_precondition_changed", "The public configuration changed before its fixed sources were published.");
|
|
1168
|
+
if (plan.after === null) {
|
|
1169
|
+
if (plan.before !== null)
|
|
1170
|
+
await rm(plan.file);
|
|
1171
|
+
}
|
|
1172
|
+
else
|
|
1173
|
+
await replacePublic(plan.file, plan.after);
|
|
1174
|
+
return plan;
|
|
1175
|
+
}
|
|
1176
|
+
catch (cause) {
|
|
1177
|
+
let rollbackFailure;
|
|
1178
|
+
for (const document of written.reverse()) {
|
|
1179
|
+
try {
|
|
1180
|
+
await this.#restorePublicFile(document);
|
|
1181
|
+
}
|
|
1182
|
+
catch (failure) {
|
|
1183
|
+
rollbackFailure ??= failure;
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
if (rollbackFailure)
|
|
1187
|
+
throw rollbackFailure;
|
|
1188
|
+
throw cause;
|
|
1189
|
+
}
|
|
1190
|
+
}
|
|
1191
|
+
/** The exact text used both for capacity admission and public persistence. */
|
|
1192
|
+
#publicText(snapshot, before, remove) {
|
|
1193
|
+
if (snapshot.kind === "mcp") {
|
|
1194
|
+
const root = before === null ? { mcpServers: {} } : JSON.parse(before);
|
|
1195
|
+
requireCondition(object(root) &&
|
|
1196
|
+
object(root.mcpServers) &&
|
|
1197
|
+
Object.keys(root).every((key) => key === "mcpServers"), "invalid_mcp_config", "work/mcp.json needs one mcpServers dictionary.");
|
|
1198
|
+
if (remove)
|
|
1199
|
+
delete root.mcpServers[snapshot.name];
|
|
1200
|
+
else
|
|
1201
|
+
put(root.mcpServers, snapshot.name, snapshot.config);
|
|
1202
|
+
return canonicalJson(root, 4 * 1024 * 1024);
|
|
1203
|
+
}
|
|
1204
|
+
if (remove)
|
|
1205
|
+
return null;
|
|
1206
|
+
return canonicalJson({
|
|
1207
|
+
...snapshot.config,
|
|
1208
|
+
identity: {
|
|
1209
|
+
name: snapshot.name,
|
|
1210
|
+
directory: configurationDirectoryName(snapshot.name),
|
|
1211
|
+
},
|
|
1212
|
+
specification: this.#sourceIndex(snapshot),
|
|
1213
|
+
}, 4 * 1024 * 1024);
|
|
1214
|
+
}
|
|
1215
|
+
#sourceIndex(snapshot) {
|
|
1216
|
+
return {
|
|
1217
|
+
file: snapshot.documents[0].file,
|
|
1218
|
+
location: snapshot.documents[0].location,
|
|
1219
|
+
references: snapshot.documents.slice(1).map((document) => ({
|
|
1220
|
+
file: document.file,
|
|
1221
|
+
location: document.location,
|
|
1222
|
+
})),
|
|
1223
|
+
};
|
|
1224
|
+
}
|
|
1225
|
+
async #restorePublicFile(write) {
|
|
1226
|
+
const current = await readPublic(write.file);
|
|
1227
|
+
// Preserve concurrent manual edits; their bytes remain an unapproved proposal.
|
|
1228
|
+
if (current !== write.after)
|
|
1229
|
+
return;
|
|
1230
|
+
if (write.before === null) {
|
|
1231
|
+
if (current !== null)
|
|
1232
|
+
await rm(write.file);
|
|
1233
|
+
}
|
|
1234
|
+
else
|
|
1235
|
+
await replacePublic(write.file, write.before);
|
|
1236
|
+
}
|
|
1237
|
+
async #restorePublic(write) {
|
|
1238
|
+
let failure;
|
|
1239
|
+
for (const file of [write, ...[...write.documents].reverse()]) {
|
|
1240
|
+
try {
|
|
1241
|
+
await this.#restorePublicFile(file);
|
|
1242
|
+
}
|
|
1243
|
+
catch (cause) {
|
|
1244
|
+
failure ??= cause;
|
|
1245
|
+
}
|
|
1246
|
+
}
|
|
1247
|
+
if (failure)
|
|
1248
|
+
throw failure;
|
|
1249
|
+
}
|
|
1250
|
+
#runtimeCredentials(snapshot) {
|
|
1251
|
+
const config = snapshot.config;
|
|
1252
|
+
const dispatchers = new Map();
|
|
1253
|
+
const provider = {
|
|
1254
|
+
get: async (request) => {
|
|
1255
|
+
request.signal.throwIfAborted();
|
|
1256
|
+
const caller = request.context.caller;
|
|
1257
|
+
requireCondition(object(caller) && caller.principalId === snapshot.owner, "credential_binding_mismatch", "The API credential is unavailable to this caller.");
|
|
1258
|
+
const liveScope = this.options.runtimeScope(request);
|
|
1259
|
+
requireCondition(liveScope.signal === request.signal &&
|
|
1260
|
+
liveScope.caller.principalId === caller.principalId &&
|
|
1261
|
+
liveScope.caller.clientId === caller.clientId &&
|
|
1262
|
+
liveScope.caller.grantId === caller.grantId, "credential_binding_mismatch", "Runtime authentication needs the current actual invocation identity.");
|
|
1263
|
+
current(liveScope);
|
|
1264
|
+
const reference = snapshot.secrets[request.scheme];
|
|
1265
|
+
requireCondition(reference && reference.ref === request.credentialRef, "credential_binding_mismatch", "The API credential does not belong to the approved scheme.");
|
|
1266
|
+
const value = await this.options.credentials.read(reference.ref, reference.binding), definition = request.definition;
|
|
1267
|
+
current(liveScope);
|
|
1268
|
+
if (definition.type === "apiKey") {
|
|
1269
|
+
requireCondition(typeof value.value === "string" && value.value.length > 0, "maintenance_auth_required", "The API key is not configured.");
|
|
1270
|
+
return { type: "apiKey", value: value.value };
|
|
1271
|
+
}
|
|
1272
|
+
if (definition.type === "basic" ||
|
|
1273
|
+
(definition.type === "http" &&
|
|
1274
|
+
definition.scheme?.toLowerCase() === "basic")) {
|
|
1275
|
+
requireCondition(typeof value.username === "string" &&
|
|
1276
|
+
typeof value.password === "string" &&
|
|
1277
|
+
value.password.length > 0, "maintenance_auth_required", "Basic authentication is not configured.");
|
|
1278
|
+
return {
|
|
1279
|
+
type: "basic",
|
|
1280
|
+
username: value.username,
|
|
1281
|
+
password: value.password,
|
|
1282
|
+
};
|
|
1283
|
+
}
|
|
1284
|
+
if (definition.type === "http" &&
|
|
1285
|
+
definition.scheme?.toLowerCase() === "bearer") {
|
|
1286
|
+
requireCondition(typeof value.token === "string" && value.token.length > 0, "maintenance_auth_required", "Bearer authentication is not configured.");
|
|
1287
|
+
return { type: "bearer", token: value.token };
|
|
1288
|
+
}
|
|
1289
|
+
if (definition.type === "mutualTLS") {
|
|
1290
|
+
requireCondition(typeof value.cert === "string" && typeof value.key === "string", "maintenance_auth_required", "mTLS credentials are not configured.");
|
|
1291
|
+
let dispatcher = dispatchers.get(reference.ref);
|
|
1292
|
+
if (!dispatcher) {
|
|
1293
|
+
const { Agent } = await import("undici");
|
|
1294
|
+
current(liveScope);
|
|
1295
|
+
dispatcher = dispatchers.get(reference.ref);
|
|
1296
|
+
if (!dispatcher) {
|
|
1297
|
+
dispatcher = new Agent({
|
|
1298
|
+
connect: {
|
|
1299
|
+
cert: value.cert,
|
|
1300
|
+
key: value.key,
|
|
1301
|
+
...(typeof value.ca === "string" ? { ca: value.ca } : {}),
|
|
1302
|
+
},
|
|
1303
|
+
});
|
|
1304
|
+
dispatchers.set(reference.ref, dispatcher);
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
return { type: "mutualTLS", dispatcher };
|
|
1308
|
+
}
|
|
1309
|
+
requireCondition(this.options.oauth && object(config.oauth?.[request.scheme]), "maintenance_auth_required", "Configure a supported OAuth provider for this scheme.");
|
|
1310
|
+
requireCondition(request.scopes.every((scope) => config.oauth[request.scheme].scopes.includes(scope)), "oauth_insufficient_scope", "The approved OAuth configuration does not include this operation's scopes.");
|
|
1311
|
+
return {
|
|
1312
|
+
type: "bearer",
|
|
1313
|
+
token: await this.options.oauth.getAccessToken(config.oauth[request.scheme], reference.ref, reference.binding, liveScope),
|
|
1314
|
+
};
|
|
1315
|
+
},
|
|
1316
|
+
};
|
|
1317
|
+
return {
|
|
1318
|
+
provider,
|
|
1319
|
+
async dispose() {
|
|
1320
|
+
await Promise.all([...dispatchers.values()].map((agent) => agent.close()));
|
|
1321
|
+
dispatchers.clear();
|
|
1322
|
+
},
|
|
1323
|
+
};
|
|
1324
|
+
}
|
|
1325
|
+
async #activate(snapshot, revision, scope) {
|
|
1326
|
+
current(scope);
|
|
1327
|
+
if (snapshot.kind === "api") {
|
|
1328
|
+
const credentials = this.#runtimeCredentials(snapshot);
|
|
1329
|
+
const prepared = await prepareOpenApi(await this.#apiInput(snapshot, scope, false), { credentials: credentials.provider, signal: scope.signal });
|
|
1330
|
+
const factory = async (host) => {
|
|
1331
|
+
const instance = await prepared.factory(host);
|
|
1332
|
+
return {
|
|
1333
|
+
...instance,
|
|
1334
|
+
async dispose() {
|
|
1335
|
+
try {
|
|
1336
|
+
await instance.dispose?.();
|
|
1337
|
+
}
|
|
1338
|
+
finally {
|
|
1339
|
+
await credentials.dispose();
|
|
1340
|
+
}
|
|
1341
|
+
},
|
|
1342
|
+
};
|
|
1343
|
+
};
|
|
1344
|
+
const api = {
|
|
1345
|
+
...prepared,
|
|
1346
|
+
factory,
|
|
1347
|
+
documentation: {
|
|
1348
|
+
...prepared.documentation,
|
|
1349
|
+
markdown: prepared.documentation.markdown +
|
|
1350
|
+
`\n\n配置目录:\`work/api/${configurationDirectoryName(snapshot.name)}/\`;逻辑命名空间保持 \`${snapshot.name}\`。实际目录映射同时记录在 config.json 的 identity 中。\n`,
|
|
1351
|
+
},
|
|
1352
|
+
};
|
|
1353
|
+
try {
|
|
1354
|
+
return await this.options.activation.prepare({
|
|
1355
|
+
kind: "api",
|
|
1356
|
+
name: snapshot.name,
|
|
1357
|
+
objectId: snapshot.objectId,
|
|
1358
|
+
revision,
|
|
1359
|
+
config: json(snapshot.config),
|
|
1360
|
+
api,
|
|
1361
|
+
}, scope);
|
|
1362
|
+
}
|
|
1363
|
+
catch (cause) {
|
|
1364
|
+
await credentials.dispose();
|
|
1365
|
+
throw cause;
|
|
1366
|
+
}
|
|
1367
|
+
}
|
|
1368
|
+
const mcp = await this.#mcp(snapshot, scope), oauth = snapshot.config.oauth, reference = snapshot.secrets.oauth;
|
|
1369
|
+
const mcpOAuth = oauth && reference && this.options.mcpOAuth
|
|
1370
|
+
? await this.options.mcpOAuth.provider(oauth, reference.ref, reference.binding, scope)
|
|
1371
|
+
: undefined;
|
|
1372
|
+
return this.options.activation.prepare({
|
|
1373
|
+
kind: "mcp",
|
|
1374
|
+
name: snapshot.name,
|
|
1375
|
+
objectId: snapshot.objectId,
|
|
1376
|
+
revision,
|
|
1377
|
+
config: json(snapshot.config),
|
|
1378
|
+
mcp,
|
|
1379
|
+
...(mcpOAuth ? { mcpOAuth } : {}),
|
|
1380
|
+
}, scope);
|
|
1381
|
+
}
|
|
1382
|
+
async apply(intent, candidate, scope) {
|
|
1383
|
+
await this.verify(intent, candidate, scope);
|
|
1384
|
+
const snapshot = await this.#load(intent, candidate, scope), state = await this.#approved(), id = candidate.payload.configurationId, old = entry(state[snapshot.kind], snapshot.name), revision = hash({ snapshot: id, objectId: snapshot.objectId }), remove = intent.action === "remove";
|
|
1385
|
+
const publicPlan = await this.#publicWritePlan(snapshot, remove), currentPublic = publicPlan.before, nextState = json(state);
|
|
1386
|
+
if (remove)
|
|
1387
|
+
delete nextState[snapshot.kind][snapshot.name];
|
|
1388
|
+
else
|
|
1389
|
+
put(nextState[snapshot.kind], snapshot.name, {
|
|
1390
|
+
objectId: snapshot.objectId,
|
|
1391
|
+
revision,
|
|
1392
|
+
snapshot: id,
|
|
1393
|
+
enabled: true,
|
|
1394
|
+
});
|
|
1395
|
+
const approvedBefore = canonicalJson(state, 64 * 1024 * 1024), approvedAfter = canonicalJson(nextState, 64 * 1024 * 1024);
|
|
1396
|
+
const publicBodies = [publicPlan, ...publicPlan.documents];
|
|
1397
|
+
const publicBytes = publicBodies.reduce((total, file) => total +
|
|
1398
|
+
Buffer.byteLength(file.before ?? "") +
|
|
1399
|
+
Buffer.byteLength(file.after ?? ""), 0);
|
|
1400
|
+
// Admit all fixed public bytes, including identity/source-index locations,
|
|
1401
|
+
// plus both approved/public rollback bodies and bounded filesystem metadata.
|
|
1402
|
+
// Existing files remain counted by Core until their actual replacement.
|
|
1403
|
+
const reservation = await this.options.reserve?.(publicBytes +
|
|
1404
|
+
Buffer.byteLength(approvedAfter) +
|
|
1405
|
+
Buffer.byteLength(approvedBefore) +
|
|
1406
|
+
(publicBodies.length + 3) * 1024);
|
|
1407
|
+
try {
|
|
1408
|
+
current(scope);
|
|
1409
|
+
await this.verify(intent, candidate, scope);
|
|
1410
|
+
current(scope);
|
|
1411
|
+
requireCondition(canonicalJson(await this.#approved(), 64 * 1024 * 1024) ===
|
|
1412
|
+
approvedBefore &&
|
|
1413
|
+
(await readPublic(this.#publicLocation(snapshot.kind, snapshot.name))) === currentPublic, "maintenance_precondition_changed", "The approved or public configuration changed while its fixed write was being admitted.");
|
|
1414
|
+
if (remove) {
|
|
1415
|
+
requireCondition(old, "maintenance_precondition_changed", "The configuration is already absent.");
|
|
1416
|
+
await this.options.activation.remove({
|
|
1417
|
+
kind: snapshot.kind,
|
|
1418
|
+
name: snapshot.name,
|
|
1419
|
+
objectId: old.objectId,
|
|
1420
|
+
revision: old.revision,
|
|
1421
|
+
}, scope);
|
|
1422
|
+
current(scope);
|
|
1423
|
+
await this.#writePublic(publicPlan);
|
|
1424
|
+
await privateMaintenanceWrite(this.options.root, ["configurations", "approved.json"], nextState);
|
|
1425
|
+
this.#state = nextState;
|
|
1426
|
+
return {
|
|
1427
|
+
changed: true,
|
|
1428
|
+
restartRequired: false,
|
|
1429
|
+
[snapshot.kind === "api" ? "api" : "connection"]: {
|
|
1430
|
+
name: snapshot.name,
|
|
1431
|
+
state: "removed",
|
|
1432
|
+
revision: null,
|
|
1433
|
+
},
|
|
1434
|
+
};
|
|
1435
|
+
}
|
|
1436
|
+
requireCondition(candidate.authStatus === "ready" ||
|
|
1437
|
+
candidate.authStatus === "not_required", "maintenance_auth_required", "Complete authentication before applying this confirmed configuration.");
|
|
1438
|
+
const prepared = await this.#activate(snapshot, revision, scope), previousState = json(state);
|
|
1439
|
+
let publicWrite;
|
|
1440
|
+
let saved = false;
|
|
1441
|
+
try {
|
|
1442
|
+
current(scope);
|
|
1443
|
+
await this.verify(intent, candidate, scope);
|
|
1444
|
+
requireCondition(canonicalJson(await this.#approved(), 64 * 1024 * 1024) ===
|
|
1445
|
+
approvedBefore, "maintenance_precondition_changed", "The approved configuration changed before this fixed publication.");
|
|
1446
|
+
publicWrite = await this.#writePublic(publicPlan);
|
|
1447
|
+
current(scope);
|
|
1448
|
+
await privateMaintenanceWrite(this.options.root, ["configurations", "approved.json"], nextState);
|
|
1449
|
+
saved = true;
|
|
1450
|
+
current(scope);
|
|
1451
|
+
prepared.publish();
|
|
1452
|
+
this.#state = nextState;
|
|
1453
|
+
}
|
|
1454
|
+
catch (cause) {
|
|
1455
|
+
try {
|
|
1456
|
+
if (saved)
|
|
1457
|
+
await privateMaintenanceWrite(this.options.root, ["configurations", "approved.json"], previousState);
|
|
1458
|
+
if (publicWrite)
|
|
1459
|
+
await this.#restorePublic(publicWrite);
|
|
1460
|
+
}
|
|
1461
|
+
finally {
|
|
1462
|
+
await prepared.dispose();
|
|
1463
|
+
}
|
|
1464
|
+
throw cause;
|
|
1465
|
+
}
|
|
1466
|
+
return {
|
|
1467
|
+
changed: true,
|
|
1468
|
+
restartRequired: false,
|
|
1469
|
+
[snapshot.kind === "api" ? "api" : "connection"]: {
|
|
1470
|
+
name: snapshot.name,
|
|
1471
|
+
state: "ready",
|
|
1472
|
+
revision,
|
|
1473
|
+
},
|
|
1474
|
+
};
|
|
1475
|
+
}
|
|
1476
|
+
finally {
|
|
1477
|
+
reservation?.release();
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
/** Startup reuses only immutable privately approved snapshots; work edits are never auto-approved. */
|
|
1481
|
+
async restore(scope) {
|
|
1482
|
+
const state = await this.#approved(), result = [];
|
|
1483
|
+
for (const kind of ["mcp", "api"])
|
|
1484
|
+
for (const [namespace, record] of Object.entries(state[kind]))
|
|
1485
|
+
if (record.enabled) {
|
|
1486
|
+
let prepared;
|
|
1487
|
+
try {
|
|
1488
|
+
const snapshot = await this.#previous(record);
|
|
1489
|
+
requireCondition(snapshot && snapshot.owner === scope.caller.principalId, "configuration_owner_mismatch", "The approved configuration has another owner.");
|
|
1490
|
+
prepared = await this.#activate(snapshot, record.revision, scope);
|
|
1491
|
+
current(scope);
|
|
1492
|
+
prepared.publish();
|
|
1493
|
+
result.push({ kind, name: namespace, state: "ready" });
|
|
1494
|
+
}
|
|
1495
|
+
catch {
|
|
1496
|
+
await prepared?.dispose();
|
|
1497
|
+
result.push({ kind, name: namespace, state: "unavailable" });
|
|
1498
|
+
}
|
|
1499
|
+
}
|
|
1500
|
+
return result;
|
|
1501
|
+
}
|
|
1502
|
+
}
|
|
1503
|
+
//# sourceMappingURL=configuration.js.map
|