@usemcpkit/core 0.8.4 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +13 -11
- package/build/{mcpkit.core.d.ts → usemcpkit.core.d.ts} +10 -154
- package/build/usemcpkit.core.js +293 -0
- package/package.json +7 -7
- package/build/mcpkit.core.js +0 -2341
package/build/mcpkit.core.js
DELETED
|
@@ -1,2341 +0,0 @@
|
|
|
1
|
-
import { mkdir, readFile, rename, rm, writeFile } from "node:fs/promises";
|
|
2
|
-
import { basename, dirname, join } from "node:path";
|
|
3
|
-
import { homedir } from "node:os";
|
|
4
|
-
import { createHash, randomBytes } from "node:crypto";
|
|
5
|
-
import { createServer } from "node:http";
|
|
6
|
-
import { execFile } from "node:child_process";
|
|
7
|
-
//#region src/auth/auth-error.ts
|
|
8
|
-
var AuthError = class extends Error {};
|
|
9
|
-
//#endregion
|
|
10
|
-
//#region src/auth/const.ts
|
|
11
|
-
var TOKENS_FILE_NAME = "tokens.json";
|
|
12
|
-
var LOOPBACK_HOST = "127.0.0.1";
|
|
13
|
-
var CALLBACK_PATH = "/callback";
|
|
14
|
-
var SIGN_IN_TIMEOUT_MS = 3e5;
|
|
15
|
-
var TOKEN_REQUEST_TIMEOUT_MS = 3e4;
|
|
16
|
-
var CALLBACK_PAGE = "<!doctype html><meta charset=\"utf-8\"><title>mcpkit</title><p>mcpkit received the authorization. You can close this window.</p>";
|
|
17
|
-
var MS_PER_SECOND = 1e3;
|
|
18
|
-
/** HTTP contract between the CLI's loopback credentials form server and the page it serves. */
|
|
19
|
-
var CREDENTIALS_FORM_API = {
|
|
20
|
-
submit: "/api/submit",
|
|
21
|
-
cancel: "/api/cancel",
|
|
22
|
-
import: "/api/import"
|
|
23
|
-
};
|
|
24
|
-
var CREDENTIALS_REQUEST_ELEMENT_ID = "mcpkit-request";
|
|
25
|
-
/**
|
|
26
|
-
* Functions the CLI's native form window binds into the page: close it, fit it to `{ width, height }`, and open a link
|
|
27
|
-
* in the default browser (a webview has no tabs, so `target="_blank"` links go nowhere).
|
|
28
|
-
*/
|
|
29
|
-
var FORM_WINDOW_BINDINGS = {
|
|
30
|
-
close: "mcpkitCloseWindow",
|
|
31
|
-
fit: "mcpkitFitWindow",
|
|
32
|
-
openLink: "mcpkitOpenLink"
|
|
33
|
-
};
|
|
34
|
-
var CREDENTIALS_FORM_SESSION_HEADER = "X-Mcpkit-Session";
|
|
35
|
-
var CONFIG_FILE_NAME = "config.json";
|
|
36
|
-
var SECRETS_FILE_NAME = "secrets.json";
|
|
37
|
-
/** The host key of a server that has no domain, so its credentials still live under `hosts`. */
|
|
38
|
-
var DEFAULT_HOST_KEY = "default";
|
|
39
|
-
var GIT_COMMAND_TIMEOUT_MS = 3e3;
|
|
40
|
-
/** The category of the servers that existed before the config grouped them by category. */
|
|
41
|
-
var LEGACY_SERVER_CATEGORIES = {
|
|
42
|
-
confluence: "atlassian",
|
|
43
|
-
jira: "atlassian",
|
|
44
|
-
github: "git",
|
|
45
|
-
gitlab: "git"
|
|
46
|
-
};
|
|
47
|
-
//#endregion
|
|
48
|
-
//#region src/manifest/auth/describe-auth-type.ts
|
|
49
|
-
var describeAuthType = (auth) => auth.type === "oauth" ? "oauth pkce" : auth.type;
|
|
50
|
-
//#endregion
|
|
51
|
-
//#region src/manifest/auth/list-auth-env-names.ts
|
|
52
|
-
var listAuthEnvNames = (auth) => {
|
|
53
|
-
switch (auth.type) {
|
|
54
|
-
case "none": return [];
|
|
55
|
-
case "basic": return [auth.usernameEnv, auth.passwordEnv];
|
|
56
|
-
case "oauth": return auth.clientSecretEnv ? [auth.clientSecretEnv] : [];
|
|
57
|
-
case "bearer":
|
|
58
|
-
case "header":
|
|
59
|
-
case "query": return [auth.env];
|
|
60
|
-
default: return auth;
|
|
61
|
-
}
|
|
62
|
-
};
|
|
63
|
-
//#endregion
|
|
64
|
-
//#region src/manifest/auth/describe-auth-spec.ts
|
|
65
|
-
var describeAuthSpec = (auth) => {
|
|
66
|
-
if (auth.type === "none") return "no auth";
|
|
67
|
-
return [describeAuthType(auth), listAuthEnvNames(auth).join(", ")].filter(Boolean).join(" ");
|
|
68
|
-
};
|
|
69
|
-
//#endregion
|
|
70
|
-
//#region src/manifest/auth/describe-auth.ts
|
|
71
|
-
var describeAuth = (auth) => {
|
|
72
|
-
if (!auth || auth.length === 0) return "no auth";
|
|
73
|
-
return auth.map(describeAuthSpec).join(" → ");
|
|
74
|
-
};
|
|
75
|
-
//#endregion
|
|
76
|
-
//#region src/manifest/auth/is-interactive-auth.ts
|
|
77
|
-
/** OAuth2 auth signs in through the browser and keeps its token in `tokens.json`. */
|
|
78
|
-
var isInteractiveAuth = (auth) => auth.type === "oauth";
|
|
79
|
-
//#endregion
|
|
80
|
-
//#region src/manifest/const.ts
|
|
81
|
-
var SERVER_NAME_PATTERN = /^[a-z][a-z0-9_]*$/;
|
|
82
|
-
/** `resource:action`, for example `pull_request:list`; the action part is optional. */
|
|
83
|
-
var TOOL_NAME_PATTERN = /^[a-z][a-z0-9_]*(:[a-z][a-z0-9_]*)*$/;
|
|
84
|
-
var SERVER_CATEGORY_PATTERN = /^[a-z][a-z0-9-]*$/;
|
|
85
|
-
var HTTP_METHODS = [
|
|
86
|
-
"GET",
|
|
87
|
-
"POST",
|
|
88
|
-
"PUT",
|
|
89
|
-
"PATCH",
|
|
90
|
-
"DELETE"
|
|
91
|
-
];
|
|
92
|
-
var AUTH_REQUIRED_KEYS = {
|
|
93
|
-
none: [],
|
|
94
|
-
bearer: ["env"],
|
|
95
|
-
header: ["env", "name"],
|
|
96
|
-
query: ["env", "name"],
|
|
97
|
-
basic: ["usernameEnv", "passwordEnv"],
|
|
98
|
-
oauth: [
|
|
99
|
-
"authorizationUrl",
|
|
100
|
-
"tokenUrl",
|
|
101
|
-
"clientId"
|
|
102
|
-
]
|
|
103
|
-
};
|
|
104
|
-
var AUTH_TYPES = Object.keys(AUTH_REQUIRED_KEYS);
|
|
105
|
-
var INTERACTIVE_AUTH_TYPES = ["oauth"];
|
|
106
|
-
var DOMAIN_PLACEHOLDER = "{domain}";
|
|
107
|
-
/** A host with an optional port and path, for example `ghe.example.com/api/v3`. */
|
|
108
|
-
var DOMAIN_VALUE_PATTERN = /^[a-z0-9]([a-z0-9.-]*[a-z0-9])?(:\d{1,5})?(\/[a-z0-9._~-]+)*$/i;
|
|
109
|
-
var EDITION_NAME_PATTERN = /^[a-z][a-z0-9-]*$/;
|
|
110
|
-
//#endregion
|
|
111
|
-
//#region src/manifest/domain/fill-domain.ts
|
|
112
|
-
var fillDomain = (template, domain) => template.replaceAll(DOMAIN_PLACEHOLDER, domain);
|
|
113
|
-
//#endregion
|
|
114
|
-
//#region src/manifest/domain/apply-auth-domain.ts
|
|
115
|
-
var applyAuthDomain = (auth, domain) => {
|
|
116
|
-
if (auth.type !== "oauth") return auth;
|
|
117
|
-
return {
|
|
118
|
-
...auth,
|
|
119
|
-
authorizationUrl: fillDomain(auth.authorizationUrl, domain),
|
|
120
|
-
tokenUrl: fillDomain(auth.tokenUrl, domain)
|
|
121
|
-
};
|
|
122
|
-
};
|
|
123
|
-
//#endregion
|
|
124
|
-
//#region src/manifest/domain/apply-tool-edition.ts
|
|
125
|
-
var applyToolEdition = (tool, editionName) => {
|
|
126
|
-
const edition = editionName === void 0 ? void 0 : tool.editions?.[editionName];
|
|
127
|
-
if (!edition) return tool;
|
|
128
|
-
return {
|
|
129
|
-
...tool,
|
|
130
|
-
request: edition.request,
|
|
131
|
-
response: edition.response ?? tool.response
|
|
132
|
-
};
|
|
133
|
-
};
|
|
134
|
-
//#endregion
|
|
135
|
-
//#region src/manifest/domain/find-edition.ts
|
|
136
|
-
var findEdition = (editions, domain) => {
|
|
137
|
-
const host = (domain.split("/")[0] ?? "").split(":")[0]?.toLowerCase() ?? "";
|
|
138
|
-
return Object.entries(editions ?? {}).find(([, edition]) => edition.hosts.some((suffix) => host.endsWith(suffix.toLowerCase())))?.[0];
|
|
139
|
-
};
|
|
140
|
-
//#endregion
|
|
141
|
-
//#region src/manifest/domain/apply-domain.ts
|
|
142
|
-
/** A copy of the manifest with `{domain}` filled in and each tool set to the domain's edition; without a domain the manifest is returned as is. */
|
|
143
|
-
var applyDomain = (manifest, domain) => {
|
|
144
|
-
if (domain === void 0) return manifest;
|
|
145
|
-
const editionName = findEdition(manifest.editions, domain);
|
|
146
|
-
return {
|
|
147
|
-
...manifest,
|
|
148
|
-
baseUrl: fillDomain(manifest.baseUrl, domain),
|
|
149
|
-
upstream: manifest.upstream?.type === "http" ? {
|
|
150
|
-
...manifest.upstream,
|
|
151
|
-
url: fillDomain(manifest.upstream.url, domain)
|
|
152
|
-
} : manifest.upstream,
|
|
153
|
-
auth: manifest.auth?.map((auth) => applyAuthDomain(auth, domain)),
|
|
154
|
-
tools: manifest.tools.map((tool) => applyToolEdition(tool, editionName))
|
|
155
|
-
};
|
|
156
|
-
};
|
|
157
|
-
//#endregion
|
|
158
|
-
//#region src/manifest/domain/is-domain-value.ts
|
|
159
|
-
var isDomainValue = (value) => typeof value === "string" && DOMAIN_VALUE_PATTERN.test(value);
|
|
160
|
-
//#endregion
|
|
161
|
-
//#region src/json/is-json-object.ts
|
|
162
|
-
var isJsonObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
163
|
-
//#endregion
|
|
164
|
-
//#region src/json/is-string-record.ts
|
|
165
|
-
var isStringRecord$1 = (value) => isJsonObject(value) && Object.values(value).every((entry) => typeof entry === "string");
|
|
166
|
-
//#endregion
|
|
167
|
-
//#region src/manifest/validation/guards/is-interactive-auth-type.ts
|
|
168
|
-
var isInteractiveAuthType = (type) => INTERACTIVE_AUTH_TYPES.some((interactiveType) => interactiveType === type);
|
|
169
|
-
//#endregion
|
|
170
|
-
//#region src/manifest/validation/auth/read-auth-type.ts
|
|
171
|
-
var readAuthType = (entry) => isJsonObject(entry) ? entry.type : void 0;
|
|
172
|
-
//#endregion
|
|
173
|
-
//#region src/manifest/validation/auth/validate-auth-order.ts
|
|
174
|
-
/**
|
|
175
|
-
* OAuth2 entries come first, fallbacks after them.
|
|
176
|
-
* `none` always succeeds, so anything after it would never be tried.
|
|
177
|
-
*/
|
|
178
|
-
var validateAuthOrder = (entries) => {
|
|
179
|
-
const types = entries.map(readAuthType);
|
|
180
|
-
const errors = [];
|
|
181
|
-
const firstFallback = types.findIndex((type) => !isInteractiveAuthType(type));
|
|
182
|
-
if (firstFallback !== -1 && types.slice(firstFallback).some(isInteractiveAuthType)) errors.push("auth: fallback entries must come after every oauth entry");
|
|
183
|
-
if (types.slice(0, -1).includes("none")) errors.push("auth: \"none\" can only be the last entry");
|
|
184
|
-
return errors;
|
|
185
|
-
};
|
|
186
|
-
//#endregion
|
|
187
|
-
//#region src/manifest/validation/guards/is-auth-type.ts
|
|
188
|
-
var isAuthType = (value) => AUTH_TYPES.some((type) => type === value);
|
|
189
|
-
//#endregion
|
|
190
|
-
//#region src/manifest/ui/const.ts
|
|
191
|
-
var DEFAULT_UI_TEXTS = {
|
|
192
|
-
brand: "mcpkit",
|
|
193
|
-
pageTitle: "mcpkit · Connect",
|
|
194
|
-
title: "Connect {server}",
|
|
195
|
-
intro: "A tool call needs access to {server}. What you enter is saved in ~/.mcpkit/config.json and used for later calls.",
|
|
196
|
-
domainLabel: "Domain",
|
|
197
|
-
domainHint: "Host, optionally with a port and path, without https://",
|
|
198
|
-
domainPlaceholder: "api.example.com",
|
|
199
|
-
domainNewHost: "New host, saved with its own credentials.",
|
|
200
|
-
domainShowHosts: "Show saved hosts",
|
|
201
|
-
signInLabel: "Sign in with OAuth2",
|
|
202
|
-
tokenDivider: "or use an access token",
|
|
203
|
-
credentialLegend: "Credential",
|
|
204
|
-
fieldHint: "Or set the {key} environment variable.",
|
|
205
|
-
tokenLabel: "Access token",
|
|
206
|
-
usernameLabel: "Username",
|
|
207
|
-
passwordLabel: "Password",
|
|
208
|
-
headerLabel: "{name} header",
|
|
209
|
-
queryLabel: "{name} query parameter",
|
|
210
|
-
actionsDivider: "or get a token",
|
|
211
|
-
cancel: "Cancel",
|
|
212
|
-
submit: "Save and continue",
|
|
213
|
-
checking: "Checking with {server}…",
|
|
214
|
-
requiredField: "{label} is required",
|
|
215
|
-
savedTitle: "{server} is connected",
|
|
216
|
-
savedBody: "The credentials are saved in ~/.mcpkit/config.json. This window closes by itself in a few seconds; you can also close it and go back to your MCP client.",
|
|
217
|
-
signingInTitle: "Continue in the new tab",
|
|
218
|
-
signingInBody: "Approve access to {server} in the sign-in tab that just opened. You can close this one.",
|
|
219
|
-
cancelledTitle: "Cancelled",
|
|
220
|
-
cancelledBody: "Nothing was saved. The tool call that asked for credentials fails; calling it again reopens this form.",
|
|
221
|
-
failedTitle: "Something went wrong",
|
|
222
|
-
requestFailed: "the CLI answered {status}"
|
|
223
|
-
};
|
|
224
|
-
var UI_TEXT_KEYS = Object.keys(DEFAULT_UI_TEXTS);
|
|
225
|
-
/** A program found on PATH by name; never a path, so a manifest cannot point at a file it ships. */
|
|
226
|
-
var CLI_COMMAND_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
227
|
-
var UI_ACTION_TYPES = ["link", "cli"];
|
|
228
|
-
var UI_URL_PLACEHOLDERS = [
|
|
229
|
-
"domain",
|
|
230
|
-
"webHost",
|
|
231
|
-
"server"
|
|
232
|
-
];
|
|
233
|
-
var UI_DOMAIN_PLACEHOLDERS = ["domain", "webHost"];
|
|
234
|
-
var UI_PLACEHOLDER_PATTERN = /\{(\w+)\}/g;
|
|
235
|
-
var UI_INPUT_KEYS = [
|
|
236
|
-
"label",
|
|
237
|
-
"hint",
|
|
238
|
-
"placeholder"
|
|
239
|
-
];
|
|
240
|
-
var UI_AUTH_TYPES = [
|
|
241
|
-
"bearer",
|
|
242
|
-
"header",
|
|
243
|
-
"query",
|
|
244
|
-
"basic"
|
|
245
|
-
];
|
|
246
|
-
var UI_SERVER_KEYS = ["texts"];
|
|
247
|
-
var UI_AUTH_KEYS = ["inputs", "actions"];
|
|
248
|
-
//#endregion
|
|
249
|
-
//#region src/manifest/ui/read-placeholders.ts
|
|
250
|
-
var readPlaceholders = (template) => Array.from(template.matchAll(UI_PLACEHOLDER_PATTERN), (match) => match[1] ?? "");
|
|
251
|
-
//#endregion
|
|
252
|
-
//#region src/manifest/validation/guards/is-https-url.ts
|
|
253
|
-
var isHttpsUrl = (value) => typeof value === "string" && value.startsWith("https://");
|
|
254
|
-
//#endregion
|
|
255
|
-
//#region src/manifest/validation/ui/validate-cli-args.ts
|
|
256
|
-
var validateCliArgs = (args, location, hasDomain) => {
|
|
257
|
-
if (!Array.isArray(args) || !args.every((arg) => typeof arg === "string")) return [`${location}.args must be an array of strings`];
|
|
258
|
-
const placeholders = args.flatMap((arg) => readPlaceholders(arg));
|
|
259
|
-
const unknown = placeholders.filter((name) => !UI_DOMAIN_PLACEHOLDERS.includes(name));
|
|
260
|
-
if (unknown.length > 0) return [`${location}.args has unknown placeholders: ${unknown.map((name) => `{${name}}`).join(", ")}`];
|
|
261
|
-
if (!hasDomain && placeholders.length > 0) return [`${location}.args uses the domain, so the manifest needs a domain`];
|
|
262
|
-
return [];
|
|
263
|
-
};
|
|
264
|
-
//#endregion
|
|
265
|
-
//#region src/manifest/validation/ui/validate-ui-action.ts
|
|
266
|
-
var validateLinkUrl = (url, location, hasDomain) => {
|
|
267
|
-
if (!isHttpsUrl(url)) return [`${location}.url must be an https:// URL`];
|
|
268
|
-
const placeholders = readPlaceholders(url);
|
|
269
|
-
const unknown = placeholders.filter((name) => !UI_URL_PLACEHOLDERS.includes(name));
|
|
270
|
-
if (unknown.length > 0) return [`${location}.url has unknown placeholders: ${unknown.map((name) => `{${name}}`).join(", ")}`];
|
|
271
|
-
if (!hasDomain && placeholders.some((name) => UI_DOMAIN_PLACEHOLDERS.includes(name))) return [`${location}.url uses the domain, so the manifest needs a domain`];
|
|
272
|
-
return [];
|
|
273
|
-
};
|
|
274
|
-
var validateUiAction = (action, location, hasDomain, allowsCli) => {
|
|
275
|
-
if (!isJsonObject(action) || typeof action.type !== "string" || !UI_ACTION_TYPES.includes(action.type)) return [`${location}.type must be one of: ${UI_ACTION_TYPES.join(", ")}`];
|
|
276
|
-
const labelErrors = typeof action.label === "string" && action.label.trim() ? [] : [`${location}.label must be a non-empty string`];
|
|
277
|
-
if (action.type === "link") return [...labelErrors, ...validateLinkUrl(action.url, location, hasDomain)];
|
|
278
|
-
const commandErrors = typeof action.command === "string" && CLI_COMMAND_PATTERN.test(action.command) ? [] : [`${location}.command must be a program name found on PATH, without a path or arguments`];
|
|
279
|
-
const authErrors = allowsCli ? [] : [`${location}: a CLI prints one token, so it needs an auth entry with a single credential`];
|
|
280
|
-
return [
|
|
281
|
-
...labelErrors,
|
|
282
|
-
...commandErrors,
|
|
283
|
-
...validateCliArgs(action.args, location, hasDomain),
|
|
284
|
-
...authErrors
|
|
285
|
-
];
|
|
286
|
-
};
|
|
287
|
-
//#endregion
|
|
288
|
-
//#region src/manifest/validation/ui/validate-ui-actions.ts
|
|
289
|
-
var validateUiActions = (actions, location, hasDomain, allowsCli) => {
|
|
290
|
-
if (actions === void 0) return [];
|
|
291
|
-
if (!Array.isArray(actions)) return [`${location} must be an array`];
|
|
292
|
-
return actions.flatMap((action, index) => validateUiAction(action, `${location}[${index}]`, hasDomain, allowsCli));
|
|
293
|
-
};
|
|
294
|
-
//#endregion
|
|
295
|
-
//#region src/manifest/validation/ui/validate-ui-inputs.ts
|
|
296
|
-
var validateUiInputs = (inputs, location, envNames) => {
|
|
297
|
-
if (inputs === void 0) return [];
|
|
298
|
-
if (!isJsonObject(inputs)) return [`${location} must map env var names to objects`];
|
|
299
|
-
return Object.entries(inputs).flatMap(([name, input]) => {
|
|
300
|
-
const inputLocation = `${location}.${name}`;
|
|
301
|
-
if (!envNames.includes(name)) return [`${inputLocation}: "${name}" is not a credential of this auth entry (${envNames.join(", ")})`];
|
|
302
|
-
if (!isJsonObject(input)) return [`${inputLocation} must be an object`];
|
|
303
|
-
const textErrors = UI_INPUT_KEYS.filter((key) => input[key] !== void 0 && typeof input[key] !== "string").map((key) => `${inputLocation}.${key} must be a string`);
|
|
304
|
-
const secretErrors = input.secret === void 0 || typeof input.secret === "boolean" ? [] : [`${inputLocation}.secret must be a boolean`];
|
|
305
|
-
return [...textErrors, ...secretErrors];
|
|
306
|
-
});
|
|
307
|
-
};
|
|
308
|
-
//#endregion
|
|
309
|
-
//#region src/manifest/validation/ui/validate-auth-ui.ts
|
|
310
|
-
var ENV_KEYS = [
|
|
311
|
-
"env",
|
|
312
|
-
"usernameEnv",
|
|
313
|
-
"passwordEnv"
|
|
314
|
-
];
|
|
315
|
-
var validateAuthUi = (auth, location, hasDomain) => {
|
|
316
|
-
const { ui } = auth;
|
|
317
|
-
const uiLocation = `${location}.ui`;
|
|
318
|
-
if (ui === void 0) return [];
|
|
319
|
-
if (typeof auth.type !== "string" || !UI_AUTH_TYPES.includes(auth.type)) return [`${uiLocation} is only allowed for auth types: ${UI_AUTH_TYPES.join(", ")}`];
|
|
320
|
-
if (!isJsonObject(ui)) return [`${uiLocation} must be an object`];
|
|
321
|
-
const envNames = ENV_KEYS.flatMap((key) => typeof auth[key] === "string" ? [auth[key]] : []);
|
|
322
|
-
return [
|
|
323
|
-
...Object.keys(ui).filter((key) => !UI_AUTH_KEYS.includes(key)).map((key) => `${uiLocation}.${key} is not allowed here, use it on the manifest`),
|
|
324
|
-
...validateUiInputs(ui.inputs, `${uiLocation}.inputs`, envNames),
|
|
325
|
-
...validateUiActions(ui.actions, `${uiLocation}.actions`, hasDomain, auth.type !== "basic")
|
|
326
|
-
];
|
|
327
|
-
};
|
|
328
|
-
//#endregion
|
|
329
|
-
//#region src/manifest/validation/guards/is-port.ts
|
|
330
|
-
var isPort = (value) => Number.isInteger(value) && Number(value) >= 0 && Number(value) <= 65535;
|
|
331
|
-
//#endregion
|
|
332
|
-
//#region src/manifest/validation/guards/is-string-list.ts
|
|
333
|
-
var isStringList = (value) => Array.isArray(value) && value.every((entry) => typeof entry === "string");
|
|
334
|
-
//#endregion
|
|
335
|
-
//#region src/manifest/validation/auth/validate-sign-in-fields.ts
|
|
336
|
-
/** Fields shared by every interactive auth type. */
|
|
337
|
-
var validateSignInFields = (auth, location) => {
|
|
338
|
-
const errors = [];
|
|
339
|
-
if (auth.scopes !== void 0 && !isStringList(auth.scopes)) errors.push(`${location}.scopes must be an array of strings`);
|
|
340
|
-
if (auth.redirectPort !== void 0 && !isPort(auth.redirectPort)) errors.push(`${location}.redirectPort must be an integer between 0 and 65535`);
|
|
341
|
-
return errors;
|
|
342
|
-
};
|
|
343
|
-
//#endregion
|
|
344
|
-
//#region src/manifest/validation/auth/validate-oauth-fields.ts
|
|
345
|
-
var validateOAuthFields = (auth, location) => {
|
|
346
|
-
const errors = [];
|
|
347
|
-
if (!isHttpsUrl(auth.authorizationUrl)) errors.push(`${location}.authorizationUrl must be an https:// URL`);
|
|
348
|
-
if (!isHttpsUrl(auth.tokenUrl)) errors.push(`${location}.tokenUrl must be an https:// URL`);
|
|
349
|
-
if (auth.clientSecretEnv !== void 0 && typeof auth.clientSecretEnv !== "string") errors.push(`${location}.clientSecretEnv must be a string`);
|
|
350
|
-
if (auth.clientAuthentication !== void 0 && auth.clientAuthentication !== "body" && auth.clientAuthentication !== "basic") errors.push(`${location}.clientAuthentication must be "body" or "basic"`);
|
|
351
|
-
return [...errors, ...validateSignInFields(auth, location)];
|
|
352
|
-
};
|
|
353
|
-
//#endregion
|
|
354
|
-
//#region src/manifest/validation/auth/validate-auth-spec.ts
|
|
355
|
-
var validateAuthSpec = (auth, location, hasDomain) => {
|
|
356
|
-
if (!isJsonObject(auth) || !isAuthType(auth.type)) return [`${location}.type must be one of: ${AUTH_TYPES.join(", ")}`];
|
|
357
|
-
const authType = auth.type;
|
|
358
|
-
const missing = AUTH_REQUIRED_KEYS[authType].filter((key) => typeof auth[key] !== "string").map((key) => `${location}.${key} is required for auth type "${authType}"`);
|
|
359
|
-
if (missing.length > 0) return missing;
|
|
360
|
-
const uiErrors = [...auth.label === void 0 || typeof auth.label === "string" ? [] : [`${location}.label must be a string`], ...validateAuthUi(auth, location, hasDomain)];
|
|
361
|
-
return authType === "oauth" ? [...validateOAuthFields(auth, location), ...uiErrors] : uiErrors;
|
|
362
|
-
};
|
|
363
|
-
//#endregion
|
|
364
|
-
//#region src/manifest/validation/auth/validate-auth.ts
|
|
365
|
-
var validateAuth = (auth, hasDomain) => {
|
|
366
|
-
if (auth === void 0) return [];
|
|
367
|
-
if (!Array.isArray(auth) || auth.length === 0) return ["auth must be a non-empty array, tried from top to bottom"];
|
|
368
|
-
return [...auth.flatMap((entry, index) => validateAuthSpec(entry, `auth[${index}]`, hasDomain)), ...validateAuthOrder(auth)];
|
|
369
|
-
};
|
|
370
|
-
//#endregion
|
|
371
|
-
//#region src/manifest/validation/tool/read-templatable-urls.ts
|
|
372
|
-
/** The URLs that may contain `{domain}`: baseUrl and the oauth endpoints. */
|
|
373
|
-
var readTemplatableUrls = (manifest) => {
|
|
374
|
-
const authUrls = (Array.isArray(manifest.auth) ? manifest.auth.filter(isJsonObject) : []).flatMap((auth) => [auth.authorizationUrl, auth.tokenUrl]);
|
|
375
|
-
return [manifest.baseUrl, ...authUrls].filter((url) => typeof url === "string");
|
|
376
|
-
};
|
|
377
|
-
//#endregion
|
|
378
|
-
//#region src/manifest/validation/server/validate-domain-spec.ts
|
|
379
|
-
var validateDomainSpec = (manifest) => {
|
|
380
|
-
const { domain } = manifest;
|
|
381
|
-
const usesDomain = readTemplatableUrls(manifest).some((url) => url.includes(DOMAIN_PLACEHOLDER));
|
|
382
|
-
if (domain === void 0) return usesDomain ? [`domain is required when a URL uses ${DOMAIN_PLACEHOLDER}`] : [];
|
|
383
|
-
if (!isJsonObject(domain)) return ["domain must be an object"];
|
|
384
|
-
const errors = [];
|
|
385
|
-
if (!usesDomain) errors.push(`domain is set but no URL uses ${DOMAIN_PLACEHOLDER}`);
|
|
386
|
-
if (domain.default !== void 0 && !isDomainValue(domain.default)) errors.push("domain.default must look like host[:port][/path]");
|
|
387
|
-
for (const key of [
|
|
388
|
-
"label",
|
|
389
|
-
"env",
|
|
390
|
-
"hint",
|
|
391
|
-
"placeholder"
|
|
392
|
-
]) if (domain[key] !== void 0 && typeof domain[key] !== "string") errors.push(`domain.${key} must be a string`);
|
|
393
|
-
if (domain.matchGitRemote !== void 0 && typeof domain.matchGitRemote !== "boolean") errors.push("domain.matchGitRemote must be a boolean");
|
|
394
|
-
return errors;
|
|
395
|
-
};
|
|
396
|
-
//#endregion
|
|
397
|
-
//#region src/manifest/validation/server/validate-editions.ts
|
|
398
|
-
var validateEditions = (editions) => {
|
|
399
|
-
if (editions === void 0) return [];
|
|
400
|
-
if (!isJsonObject(editions)) return ["editions must be an object"];
|
|
401
|
-
return Object.entries(editions).flatMap(([name, edition]) => {
|
|
402
|
-
const location = `editions.${name}`;
|
|
403
|
-
if (!EDITION_NAME_PATTERN.test(name)) return [`${location}: name must match ${EDITION_NAME_PATTERN}`];
|
|
404
|
-
if (!isJsonObject(edition) || !isStringList(edition.hosts) || edition.hosts.length === 0) return [`${location}.hosts must be a non-empty array of host suffixes`];
|
|
405
|
-
return edition.label === void 0 || typeof edition.label === "string" ? [] : [`${location}.label must be a string`];
|
|
406
|
-
});
|
|
407
|
-
};
|
|
408
|
-
//#endregion
|
|
409
|
-
//#region src/manifest/validation/guards/is-base-url.ts
|
|
410
|
-
var isBaseUrl = (value) => isHttpsUrl(value) && URL.canParse(fillDomain(value, "example.com"));
|
|
411
|
-
//#endregion
|
|
412
|
-
//#region src/manifest/validation/server/validate-server-fields.ts
|
|
413
|
-
var validateServerFields = (manifest) => {
|
|
414
|
-
const errors = [];
|
|
415
|
-
if (!SERVER_NAME_PATTERN.test(String(manifest.name ?? ""))) errors.push(`name must match ${SERVER_NAME_PATTERN}`);
|
|
416
|
-
if (!SERVER_CATEGORY_PATTERN.test(String(manifest.category ?? ""))) errors.push(`category must match ${SERVER_CATEGORY_PATTERN}`);
|
|
417
|
-
if (typeof manifest.version !== "string") errors.push("version is required");
|
|
418
|
-
if (!isBaseUrl(manifest.baseUrl)) errors.push("baseUrl must be an https:// URL");
|
|
419
|
-
if (manifest.headers !== void 0 && !isStringRecord$1(manifest.headers)) errors.push("headers must be an object of strings");
|
|
420
|
-
return errors;
|
|
421
|
-
};
|
|
422
|
-
//#endregion
|
|
423
|
-
//#region src/manifest/validation/ui/validate-stdio-ui.ts
|
|
424
|
-
/** A stdio upstream's form asks for its `forwardEnv` credentials; it has no domain and no CLI to take a token from. */
|
|
425
|
-
var validateStdioUi = (upstream) => {
|
|
426
|
-
const { ui } = upstream;
|
|
427
|
-
if (ui === void 0) return [];
|
|
428
|
-
if (!isJsonObject(ui)) return ["upstream.ui must be an object"];
|
|
429
|
-
const forwardEnv = Array.isArray(upstream.forwardEnv) ? upstream.forwardEnv.map(String) : [];
|
|
430
|
-
return [
|
|
431
|
-
...Object.keys(ui).filter((key) => !UI_AUTH_KEYS.includes(key)).map((key) => `upstream.ui.${key} is not allowed here`),
|
|
432
|
-
...validateUiInputs(ui.inputs, "upstream.ui.inputs", forwardEnv),
|
|
433
|
-
...validateUiActions(ui.actions, "upstream.ui.actions", false, false)
|
|
434
|
-
];
|
|
435
|
-
};
|
|
436
|
-
//#endregion
|
|
437
|
-
//#region src/errors/describe-error.ts
|
|
438
|
-
var describeError = (error) => error instanceof Error ? error.message : String(error);
|
|
439
|
-
//#endregion
|
|
440
|
-
//#region src/errors/is-missing-file-error.ts
|
|
441
|
-
var isMissingFileError = (error) => error instanceof Error && "code" in error && error.code === "ENOENT";
|
|
442
|
-
//#endregion
|
|
443
|
-
//#region src/manifest/validation/server/validate-upstream-naming.ts
|
|
444
|
-
var MAX_MATCH_LENGTH = 200;
|
|
445
|
-
var NAME_TEMPLATE_PATTERN = /^[a-z0-9_$&]+(:[a-z0-9_$&]+){2,}$/;
|
|
446
|
-
var validateRule = (rule, position) => {
|
|
447
|
-
const label = `upstream.naming[${position}]`;
|
|
448
|
-
if (!isJsonObject(rule)) return [`${label} must be an object`];
|
|
449
|
-
const errors = [];
|
|
450
|
-
if (typeof rule.match !== "string" || rule.match === "" || rule.match.length > MAX_MATCH_LENGTH) errors.push(`${label}.match must be a regular expression of at most ${MAX_MATCH_LENGTH} characters`);
|
|
451
|
-
else try {
|
|
452
|
-
new RegExp(rule.match);
|
|
453
|
-
} catch (error) {
|
|
454
|
-
errors.push(`${label}.match is not a valid regular expression: ${describeError(error)}`);
|
|
455
|
-
}
|
|
456
|
-
if (typeof rule.name !== "string" || !NAME_TEMPLATE_PATTERN.test(rule.name)) errors.push(`${label}.name must be <group>:<resource>:<action> with $1… or $& for the upstream name`);
|
|
457
|
-
return errors;
|
|
458
|
-
};
|
|
459
|
-
var validateUpstreamNaming = (naming) => Array.isArray(naming) ? naming.flatMap(validateRule) : ["upstream.naming must be a list of rules"];
|
|
460
|
-
//#endregion
|
|
461
|
-
//#region src/manifest/validation/server/validate-upstream-repo.ts
|
|
462
|
-
var PROGRAM_NAME_PATTERN$1 = /^[A-Za-z0-9._-]+$/;
|
|
463
|
-
var REF_PATTERN = /^[A-Za-z0-9._][A-Za-z0-9._/-]*$/;
|
|
464
|
-
var validateSetupStep = (step, position) => {
|
|
465
|
-
const label = `upstream.repo.setup[${position}]`;
|
|
466
|
-
if (!isJsonObject(step)) return [`${label} must be an object`];
|
|
467
|
-
const errors = [];
|
|
468
|
-
if (typeof step.command !== "string" || !PROGRAM_NAME_PATTERN$1.test(step.command)) errors.push(`${label}.command must be a program name on PATH, not a path`);
|
|
469
|
-
if (step.args !== void 0 && !isStringList(step.args)) errors.push(`${label}.args must be a list of strings`);
|
|
470
|
-
return errors;
|
|
471
|
-
};
|
|
472
|
-
var validateUpstreamRepo = (repo) => {
|
|
473
|
-
if (!isJsonObject(repo)) return ["upstream.repo must be an object"];
|
|
474
|
-
const errors = [];
|
|
475
|
-
if (!isHttpsUrl(repo.url)) errors.push("upstream.repo.url must be an https:// URL");
|
|
476
|
-
if (typeof repo.ref !== "string" || !REF_PATTERN.test(repo.ref)) errors.push("upstream.repo.ref must be a commit, tag or branch, not starting with '-'");
|
|
477
|
-
if (repo.setup !== void 0) {
|
|
478
|
-
if (Array.isArray(repo.setup)) errors.push(...repo.setup.flatMap(validateSetupStep));
|
|
479
|
-
else errors.push("upstream.repo.setup must be a list of steps");
|
|
480
|
-
}
|
|
481
|
-
return errors;
|
|
482
|
-
};
|
|
483
|
-
//#endregion
|
|
484
|
-
//#region src/manifest/validation/server/validate-upstream.ts
|
|
485
|
-
var PROGRAM_NAME_PATTERN = /^[A-Za-z0-9._-]+$/;
|
|
486
|
-
var validateHttp = (upstream) => isHttpsUrl(upstream.url) ? [] : ["upstream.url must be an https:// URL"];
|
|
487
|
-
var validateStdio = (upstream) => {
|
|
488
|
-
const errors = [];
|
|
489
|
-
if (typeof upstream.command !== "string" || !PROGRAM_NAME_PATTERN.test(upstream.command)) errors.push("upstream.command must be a program name on PATH, not a path");
|
|
490
|
-
if (upstream.args !== void 0 && !isStringList(upstream.args)) errors.push("upstream.args must be a list of strings");
|
|
491
|
-
if (upstream.forwardEnv !== void 0 && !isStringList(upstream.forwardEnv)) errors.push("upstream.forwardEnv must be a list of strings");
|
|
492
|
-
if (upstream.optionalEnv !== void 0 && !isStringList(upstream.optionalEnv)) errors.push("upstream.optionalEnv must be a list of strings");
|
|
493
|
-
if (upstream.repo !== void 0) errors.push(...validateUpstreamRepo(upstream.repo));
|
|
494
|
-
return [...errors, ...validateStdioUi(upstream)];
|
|
495
|
-
};
|
|
496
|
-
var validateUpstream = (upstream) => {
|
|
497
|
-
if (!isJsonObject(upstream)) return ["upstream must be an object"];
|
|
498
|
-
if (upstream.type !== "http" && upstream.type !== "stdio") return ["upstream.type must be \"http\" or \"stdio\""];
|
|
499
|
-
return [...upstream.type === "http" ? validateHttp(upstream) : validateStdio(upstream), ...upstream.naming === void 0 ? [] : validateUpstreamNaming(upstream.naming)];
|
|
500
|
-
};
|
|
501
|
-
//#endregion
|
|
502
|
-
//#region src/manifest/validation/find-duplicates.ts
|
|
503
|
-
var findDuplicates = (values) => [...new Set(values.filter((value, index) => values.indexOf(value) !== index))];
|
|
504
|
-
//#endregion
|
|
505
|
-
//#region src/manifest/validation/tool/describe-tool-location.ts
|
|
506
|
-
var describeToolLocation = (tool, index) => {
|
|
507
|
-
return `tools[${index}]${isJsonObject(tool) && typeof tool.name === "string" ? ` (${tool.name})` : ""}`;
|
|
508
|
-
};
|
|
509
|
-
//#endregion
|
|
510
|
-
//#region src/manifest/validation/guards/is-http-method.ts
|
|
511
|
-
var isHttpMethod = (value) => HTTP_METHODS.some((method) => method === value);
|
|
512
|
-
//#endregion
|
|
513
|
-
//#region src/manifest/validation/tool/read-arg-names.ts
|
|
514
|
-
var readArgNames = (spec) => {
|
|
515
|
-
if (isStringList(spec)) return spec;
|
|
516
|
-
if (isStringRecord$1(spec)) return Object.values(spec);
|
|
517
|
-
};
|
|
518
|
-
//#endregion
|
|
519
|
-
//#region src/manifest/validation/tool/validate-arg-spec.ts
|
|
520
|
-
var validateArgSpec = (spec, declaredArgs, location) => {
|
|
521
|
-
if (spec === void 0) return [];
|
|
522
|
-
const names = readArgNames(spec);
|
|
523
|
-
if (!names) return [`${location} must be an array of arg names or an object of strings`];
|
|
524
|
-
return names.filter((name) => !declaredArgs.has(name)).map((name) => `${location} uses undeclared arg "${name}"`);
|
|
525
|
-
};
|
|
526
|
-
//#endregion
|
|
527
|
-
//#region src/manifest/validation/tool/validate-body-arg.ts
|
|
528
|
-
var validateBodyArg = (request, declaredArgs, location) => {
|
|
529
|
-
const { bodyArg, body, fixedBody } = request;
|
|
530
|
-
if (bodyArg === void 0) return [];
|
|
531
|
-
if (typeof bodyArg !== "string" || !declaredArgs.has(bodyArg)) return [`${location}.request.bodyArg must name a declared arg`];
|
|
532
|
-
return body !== void 0 || fixedBody !== void 0 ? [`${location}.request.bodyArg cannot be combined with body or fixedBody`] : [];
|
|
533
|
-
};
|
|
534
|
-
//#endregion
|
|
535
|
-
//#region src/manifest/validation/tool/validate-comma-query.ts
|
|
536
|
-
var validateCommaQuery = (keys, location) => {
|
|
537
|
-
if (keys === void 0) return [];
|
|
538
|
-
return Array.isArray(keys) && keys.every((key) => typeof key === "string") ? [] : [`${location} must be an array of strings`];
|
|
539
|
-
};
|
|
540
|
-
//#endregion
|
|
541
|
-
//#region src/manifest/validation/tool/validate-content-type.ts
|
|
542
|
-
var validateContentType = (request, location) => {
|
|
543
|
-
const { contentType, bodyArg } = request;
|
|
544
|
-
if (contentType === void 0) return [];
|
|
545
|
-
if (typeof contentType !== "string" || contentType.trim() === "") return [`${location}.request.contentType must be a non-empty string`];
|
|
546
|
-
if (contentType.startsWith("text/") && bodyArg === void 0) return [`${location}.request.contentType ${contentType} requires bodyArg`];
|
|
547
|
-
return contentType === "multipart/form-data" && bodyArg !== void 0 ? [`${location}.request.contentType ${contentType} cannot be combined with bodyArg`] : [];
|
|
548
|
-
};
|
|
549
|
-
//#endregion
|
|
550
|
-
//#region src/manifest/validation/tool/validate-file-args.ts
|
|
551
|
-
var validateFileArgs = (fileArgs, declaredArgs, location) => {
|
|
552
|
-
if (fileArgs === void 0) return [];
|
|
553
|
-
if (!Array.isArray(fileArgs)) return [`${location} must be an array of argument names`];
|
|
554
|
-
return fileArgs.filter((name) => typeof name !== "string" || !declaredArgs.has(name)).map((name) => `${location} names an undeclared arg: ${String(name)}`);
|
|
555
|
-
};
|
|
556
|
-
//#endregion
|
|
557
|
-
//#region src/manifest/validation/tool/validate-fixed-headers.ts
|
|
558
|
-
var validateFixedHeaders = (headers, location) => {
|
|
559
|
-
if (headers === void 0) return [];
|
|
560
|
-
if (!isJsonObject(headers)) return [`${location} must be an object`];
|
|
561
|
-
return Object.entries(headers).filter(([, value]) => typeof value !== "string").map(([name]) => `${location}.${name} must be a string`);
|
|
562
|
-
};
|
|
563
|
-
//#endregion
|
|
564
|
-
//#region src/manifest/validation/tool/validate-fixed-values.ts
|
|
565
|
-
var validateFixedValues = (values, location) => {
|
|
566
|
-
if (values === void 0) return [];
|
|
567
|
-
if (!isJsonObject(values)) return [`${location} must be an object`];
|
|
568
|
-
return Object.entries(values).filter(([, value]) => ![
|
|
569
|
-
"string",
|
|
570
|
-
"number",
|
|
571
|
-
"boolean"
|
|
572
|
-
].includes(typeof value)).map(([key]) => `${location}.${key} must be a string, number or boolean`);
|
|
573
|
-
};
|
|
574
|
-
//#endregion
|
|
575
|
-
//#region src/manifest/validation/tool/validate-request-path.ts
|
|
576
|
-
var validateRequestPath = (path, declaredArgs, location) => {
|
|
577
|
-
if (typeof path !== "string" || !path.startsWith("/")) return [`${location}.request.path must start with "/"`];
|
|
578
|
-
return [...path.matchAll(/\{(\w+)\}/g)].map((match) => match[1] ?? "").filter((name) => !declaredArgs.has(name)).map((name) => `${location}.request.path uses undeclared arg "${name}"`);
|
|
579
|
-
};
|
|
580
|
-
//#endregion
|
|
581
|
-
//#region src/manifest/validation/tool/validate-save-to-arg.ts
|
|
582
|
-
var validateSaveToArg = (saveToArg, declaredArgs, location) => {
|
|
583
|
-
if (saveToArg === void 0) return [];
|
|
584
|
-
return typeof saveToArg === "string" && declaredArgs.has(saveToArg) ? [] : [`${location}.request.saveToArg must name a declared arg`];
|
|
585
|
-
};
|
|
586
|
-
//#endregion
|
|
587
|
-
//#region src/manifest/validation/tool/validate-request.ts
|
|
588
|
-
var validateRequest = (request, declaredArgs, location) => {
|
|
589
|
-
if (!isJsonObject(request)) return [`${location}.request is required`];
|
|
590
|
-
return [
|
|
591
|
-
...isHttpMethod(request.method) ? [] : [`${location}.request.method must be one of: ${HTTP_METHODS.join(", ")}`],
|
|
592
|
-
...validateRequestPath(request.path, declaredArgs, location),
|
|
593
|
-
...validateArgSpec(request.query, declaredArgs, `${location}.request.query`),
|
|
594
|
-
...validateArgSpec(request.body, declaredArgs, `${location}.request.body`),
|
|
595
|
-
...validateSaveToArg(request.saveToArg, declaredArgs, location),
|
|
596
|
-
...validateFileArgs(request.fileArgs, declaredArgs, `${location}.request.fileArgs`),
|
|
597
|
-
...validateContentType(request, location),
|
|
598
|
-
...validateBodyArg(request, declaredArgs, location),
|
|
599
|
-
...validateFixedValues(request.fixedQuery, `${location}.request.fixedQuery`),
|
|
600
|
-
...validateCommaQuery(request.commaQuery, `${location}.request.commaQuery`),
|
|
601
|
-
...validateFixedHeaders(request.fixedHeaders, `${location}.request.fixedHeaders`),
|
|
602
|
-
...validateFixedValues(request.fixedBody, `${location}.request.fixedBody`)
|
|
603
|
-
];
|
|
604
|
-
};
|
|
605
|
-
//#endregion
|
|
606
|
-
//#region src/manifest/validation/tool/validate-tool-editions.ts
|
|
607
|
-
var validateToolEditions = (tool, declaredArgs, editionNames, location) => {
|
|
608
|
-
const { editions } = tool;
|
|
609
|
-
if (editions === void 0) return [];
|
|
610
|
-
if (!isJsonObject(editions)) return [`${location}.editions must be an object`];
|
|
611
|
-
return Object.entries(editions).flatMap(([name, edition]) => {
|
|
612
|
-
const editionLocation = `${location}.editions.${name}`;
|
|
613
|
-
if (!editionNames.has(name)) return [`${editionLocation}: "${name}" is not in the manifest's editions`];
|
|
614
|
-
if (!isJsonObject(edition)) return [`${editionLocation} must be an object`];
|
|
615
|
-
const responseErrors = edition.response === void 0 || isJsonObject(edition.response) ? [] : [`${editionLocation}.response must be an object`];
|
|
616
|
-
return [...validateRequest(edition.request, declaredArgs, editionLocation), ...responseErrors];
|
|
617
|
-
});
|
|
618
|
-
};
|
|
619
|
-
//#endregion
|
|
620
|
-
//#region src/manifest/validation/tool/validate-tool-fields.ts
|
|
621
|
-
var validateToolFields = (tool, location) => {
|
|
622
|
-
const errors = [];
|
|
623
|
-
if (!TOOL_NAME_PATTERN.test(String(tool.name ?? ""))) errors.push(`${location}.name must match ${TOOL_NAME_PATTERN}`);
|
|
624
|
-
if (typeof tool.description !== "string") errors.push(`${location}.description is required`);
|
|
625
|
-
if (tool.response !== void 0 && !isJsonObject(tool.response)) errors.push(`${location}.response must be an object`);
|
|
626
|
-
return errors;
|
|
627
|
-
};
|
|
628
|
-
//#endregion
|
|
629
|
-
//#region src/manifest/validation/tool/validate-tool.ts
|
|
630
|
-
var validateTool = (tool, index, editionNames) => {
|
|
631
|
-
const location = describeToolLocation(tool, index);
|
|
632
|
-
if (!isJsonObject(tool)) return [`${location} must be an object`];
|
|
633
|
-
const fieldErrors = validateToolFields(tool, location);
|
|
634
|
-
const input = tool.input;
|
|
635
|
-
if (!isJsonObject(input) || input.type !== "object") return [...fieldErrors, `${location}.input must be a JSON Schema with type "object"`];
|
|
636
|
-
const declaredArgs = new Set(isJsonObject(input.properties) ? Object.keys(input.properties) : []);
|
|
637
|
-
return [
|
|
638
|
-
...fieldErrors,
|
|
639
|
-
...validateRequest(tool.request, declaredArgs, location),
|
|
640
|
-
...validateToolEditions(tool, declaredArgs, editionNames, location)
|
|
641
|
-
];
|
|
642
|
-
};
|
|
643
|
-
//#endregion
|
|
644
|
-
//#region src/manifest/validation/tool/validate-tools.ts
|
|
645
|
-
var validateTools = (tools, editionNames) => {
|
|
646
|
-
if (!Array.isArray(tools) || tools.length === 0) return ["tools must be a non-empty array"];
|
|
647
|
-
const toolErrors = tools.flatMap((tool, index) => validateTool(tool, index, editionNames));
|
|
648
|
-
const duplicates = findDuplicates(tools.map((tool) => isJsonObject(tool) ? tool.name : void 0));
|
|
649
|
-
const duplicateErrors = duplicates.length ? [`duplicate tool names: ${duplicates.join(", ")}`] : [];
|
|
650
|
-
return [...toolErrors, ...duplicateErrors];
|
|
651
|
-
};
|
|
652
|
-
//#endregion
|
|
653
|
-
//#region src/manifest/validation/tool/validate-upstream-tools.ts
|
|
654
|
-
var validateUpstreamTools = (tools) => Array.isArray(tools) && tools.length === 0 ? [] : ["tools must be empty when the manifest has an upstream"];
|
|
655
|
-
//#endregion
|
|
656
|
-
//#region src/manifest/validation/ui/validate-ui-texts.ts
|
|
657
|
-
var KNOWN_TEXT_KEYS = UI_TEXT_KEYS;
|
|
658
|
-
var validateUiTexts = (texts, location) => {
|
|
659
|
-
if (texts === void 0) return [];
|
|
660
|
-
if (!isJsonObject(texts)) return [`${location} must be an object of strings`];
|
|
661
|
-
return Object.entries(texts).flatMap(([key, value]) => {
|
|
662
|
-
if (!KNOWN_TEXT_KEYS.includes(key)) return [`${location}.${key} is not a text of the page, use one of: ${KNOWN_TEXT_KEYS.join(", ")}`];
|
|
663
|
-
return typeof value === "string" ? [] : [`${location}.${key} must be a string`];
|
|
664
|
-
});
|
|
665
|
-
};
|
|
666
|
-
//#endregion
|
|
667
|
-
//#region src/manifest/validation/ui/validate-server-ui.ts
|
|
668
|
-
var validateServerUi = (manifest) => {
|
|
669
|
-
const { ui } = manifest;
|
|
670
|
-
if (ui === void 0) return [];
|
|
671
|
-
if (!isJsonObject(ui)) return ["ui must be an object"];
|
|
672
|
-
return [...Object.keys(ui).filter((key) => !UI_SERVER_KEYS.includes(key)).map((key) => `ui.${key} is not allowed here, use it on an auth entry`), ...validateUiTexts(ui.texts, "ui.texts")];
|
|
673
|
-
};
|
|
674
|
-
//#endregion
|
|
675
|
-
//#region src/manifest/validation/validate-manifest.ts
|
|
676
|
-
/** Manifests can be downloaded at runtime, so they are treated as untrusted input. */
|
|
677
|
-
var validateManifest = (manifest) => {
|
|
678
|
-
if (!isJsonObject(manifest)) return ["manifest must be a JSON object"];
|
|
679
|
-
const editionNames = new Set(isJsonObject(manifest.editions) ? Object.keys(manifest.editions) : []);
|
|
680
|
-
const toolErrors = manifest.upstream === void 0 ? validateTools(manifest.tools, editionNames) : [...validateUpstream(manifest.upstream), ...validateUpstreamTools(manifest.tools)];
|
|
681
|
-
return [
|
|
682
|
-
...validateServerFields(manifest),
|
|
683
|
-
...validateDomainSpec(manifest),
|
|
684
|
-
...validateEditions(manifest.editions),
|
|
685
|
-
...validateAuth(manifest.auth, manifest.domain !== void 0),
|
|
686
|
-
...validateServerUi(manifest),
|
|
687
|
-
...toolErrors
|
|
688
|
-
];
|
|
689
|
-
};
|
|
690
|
-
//#endregion
|
|
691
|
-
//#region src/manifest/is-valid-manifest.ts
|
|
692
|
-
var isValidManifest = (value) => validateManifest(value).length === 0;
|
|
693
|
-
//#endregion
|
|
694
|
-
//#region src/manifest/is-name-list.ts
|
|
695
|
-
var isNameList = (spec) => Array.isArray(spec);
|
|
696
|
-
//#endregion
|
|
697
|
-
//#region src/manifest/to-name-mapping.ts
|
|
698
|
-
var toNameMapping = (spec) => {
|
|
699
|
-
if (!isNameList(spec)) return spec;
|
|
700
|
-
return Object.fromEntries(spec.map((name) => [name, name]));
|
|
701
|
-
};
|
|
702
|
-
//#endregion
|
|
703
|
-
//#region src/manifest/ui/fill-template.ts
|
|
704
|
-
/** Replaces `{name}` with its value; a placeholder without a value stays as it is. */
|
|
705
|
-
var fillTemplate = (template, values) => template.replace(UI_PLACEHOLDER_PATTERN, (placeholder, name) => values[name] ?? placeholder);
|
|
706
|
-
//#endregion
|
|
707
|
-
//#region src/auth/config/list-known-hosts.ts
|
|
708
|
-
/** The hosts a server has been used with: those with saved settings. */
|
|
709
|
-
var listKnownHosts = (server) => Object.keys(server?.hosts ?? {});
|
|
710
|
-
//#endregion
|
|
711
|
-
//#region src/auth/secret-file/merge-legacy-secrets.ts
|
|
712
|
-
/** Adds the credentials of the old secrets file under the host the server uses; a value already in the config wins. */
|
|
713
|
-
var mergeLegacySecrets = (config, legacy) => {
|
|
714
|
-
const servers = { ...config.servers };
|
|
715
|
-
for (const [name, secrets] of Object.entries(legacy)) {
|
|
716
|
-
const category = LEGACY_SERVER_CATEGORIES[name] ?? "other";
|
|
717
|
-
const server = servers[category]?.[name] ?? {};
|
|
718
|
-
const known = listKnownHosts(server);
|
|
719
|
-
const [onlyHost] = known;
|
|
720
|
-
const host = known.length === 1 && onlyHost !== void 0 ? onlyHost : DEFAULT_HOST_KEY;
|
|
721
|
-
servers[category] = {
|
|
722
|
-
...servers[category],
|
|
723
|
-
[name]: {
|
|
724
|
-
...server,
|
|
725
|
-
hosts: {
|
|
726
|
-
...server.hosts,
|
|
727
|
-
[host]: {
|
|
728
|
-
...server.hosts?.[host],
|
|
729
|
-
secrets: {
|
|
730
|
-
...secrets,
|
|
731
|
-
...server.hosts?.[host]?.secrets
|
|
732
|
-
}
|
|
733
|
-
}
|
|
734
|
-
}
|
|
735
|
-
}
|
|
736
|
-
};
|
|
737
|
-
}
|
|
738
|
-
return {
|
|
739
|
-
...config,
|
|
740
|
-
servers
|
|
741
|
-
};
|
|
742
|
-
};
|
|
743
|
-
//#endregion
|
|
744
|
-
//#region src/auth/token-store/read-tokens-text.ts
|
|
745
|
-
var readTokensText = async (file) => {
|
|
746
|
-
try {
|
|
747
|
-
return await readFile(file, "utf8");
|
|
748
|
-
} catch (error) {
|
|
749
|
-
if (isMissingFileError(error)) return;
|
|
750
|
-
throw error;
|
|
751
|
-
}
|
|
752
|
-
};
|
|
753
|
-
//#endregion
|
|
754
|
-
//#region src/auth/secret-file/is-stored-secrets.ts
|
|
755
|
-
var isServerSecrets = (value) => isJsonObject(value) && Object.values(value).every((entry) => typeof entry === "string");
|
|
756
|
-
var isStoredSecrets = (value) => isJsonObject(value) && Object.values(value).every(isServerSecrets);
|
|
757
|
-
//#endregion
|
|
758
|
-
//#region src/auth/secret-file/read-stored-secrets.ts
|
|
759
|
-
/** A missing file means nothing is saved; a malformed one fails instead of being overwritten. */
|
|
760
|
-
var readStoredSecrets = async (file) => {
|
|
761
|
-
const text = await readTokensText(file);
|
|
762
|
-
if (text === void 0) return {};
|
|
763
|
-
const data = JSON.parse(text);
|
|
764
|
-
if (!isStoredSecrets(data)) throw new AuthError(`${file} is not a valid mcpkit secrets file`);
|
|
765
|
-
return data;
|
|
766
|
-
};
|
|
767
|
-
//#endregion
|
|
768
|
-
//#region src/home/resolve-home-dir.ts
|
|
769
|
-
var resolveHomeDir = (env = process.env) => env.MCPKIT_HOME ?? join(homedir(), ".mcpkit");
|
|
770
|
-
//#endregion
|
|
771
|
-
//#region src/auth/secret-file/resolve-secrets-file.ts
|
|
772
|
-
var resolveSecretsFile = (env) => join(resolveHomeDir(env), SECRETS_FILE_NAME);
|
|
773
|
-
//#endregion
|
|
774
|
-
//#region src/auth/secrets/write-json-file.ts
|
|
775
|
-
/** Writes through a temp file and rename so a crash never leaves a half-written file. */
|
|
776
|
-
var writeJsonFile = async (file, value) => {
|
|
777
|
-
await mkdir(dirname(file), {
|
|
778
|
-
recursive: true,
|
|
779
|
-
mode: 448
|
|
780
|
-
});
|
|
781
|
-
const tempFile = `${file}.${process.pid}.tmp`;
|
|
782
|
-
await writeFile(tempFile, `${JSON.stringify(value, null, 2)}\n`, { mode: 384 });
|
|
783
|
-
await rename(tempFile, file);
|
|
784
|
-
};
|
|
785
|
-
/** Data without a `version` is the first version. */
|
|
786
|
-
var readVersion = (data) => isJsonObject(data) && data.version !== void 0 ? data.version : 1;
|
|
787
|
-
//#endregion
|
|
788
|
-
//#region src/migrations/migrate-data.ts
|
|
789
|
-
/**
|
|
790
|
-
* Runs the migrations from the data's version up to the latest, which is `migrations.length + 1`, and stamps it.
|
|
791
|
-
* Adding a version means appending one migration to the list; nothing else changes. Data from a newer version throws
|
|
792
|
-
* instead of being rewritten.
|
|
793
|
-
*/
|
|
794
|
-
var migrateData = (data, migrations) => {
|
|
795
|
-
const latest = 1 + migrations.length;
|
|
796
|
-
const version = readVersion(data);
|
|
797
|
-
if (!isJsonObject(data) || typeof version !== "number" || !Number.isInteger(version) || version < 1) throw new Error("is not valid versioned data");
|
|
798
|
-
if (version > latest) throw new Error(`is version ${version}; this mcpkit reads up to version ${latest}, update mcpkit`);
|
|
799
|
-
return {
|
|
800
|
-
...migrations.slice(version - 1).reduce((current, migrate) => migrate(current), data),
|
|
801
|
-
version: latest
|
|
802
|
-
};
|
|
803
|
-
};
|
|
804
|
-
//#endregion
|
|
805
|
-
//#region src/auth/config/migrations/drop-last-used-domain.ts
|
|
806
|
-
/** 2 → 3: the last used `domain` is dropped, the hosts it was kept in already list it. */
|
|
807
|
-
var dropLastUsedDomain = (server) => {
|
|
808
|
-
const { domain, ...rest } = server;
|
|
809
|
-
if (typeof domain !== "string") return rest;
|
|
810
|
-
const hosts = isJsonObject(rest.hosts) ? rest.hosts : {};
|
|
811
|
-
return {
|
|
812
|
-
...rest,
|
|
813
|
-
hosts: {
|
|
814
|
-
[domain]: {},
|
|
815
|
-
...hosts
|
|
816
|
-
}
|
|
817
|
-
};
|
|
818
|
-
};
|
|
819
|
-
//#endregion
|
|
820
|
-
//#region src/auth/config/migrations/group-servers.ts
|
|
821
|
-
var groupServers = (toGroup) => (data) => {
|
|
822
|
-
if (!isJsonObject(data.servers)) return { ...data };
|
|
823
|
-
const grouped = {};
|
|
824
|
-
for (const [name, server] of Object.entries(data.servers)) {
|
|
825
|
-
const group = toGroup(name);
|
|
826
|
-
grouped[group] = {
|
|
827
|
-
...grouped[group],
|
|
828
|
-
[name]: server
|
|
829
|
-
};
|
|
830
|
-
}
|
|
831
|
-
return {
|
|
832
|
-
...data,
|
|
833
|
-
servers: grouped
|
|
834
|
-
};
|
|
835
|
-
};
|
|
836
|
-
//#endregion
|
|
837
|
-
//#region src/auth/config/migrations/migrate-servers.ts
|
|
838
|
-
var migrateServers = (migrateServer) => (data) => {
|
|
839
|
-
if (!isJsonObject(data.servers)) return { ...data };
|
|
840
|
-
const servers = Object.entries(data.servers).map(([name, server]) => [name, isJsonObject(server) ? migrateServer(server) : server]);
|
|
841
|
-
return {
|
|
842
|
-
...data,
|
|
843
|
-
servers: Object.fromEntries(servers)
|
|
844
|
-
};
|
|
845
|
-
};
|
|
846
|
-
//#endregion
|
|
847
|
-
//#region src/auth/config/migrations/move-secrets-under-host.ts
|
|
848
|
-
/** 1 → 2: a server's `secrets` move under the host of its domain, and the domain itself becomes a known host. */
|
|
849
|
-
var moveSecretsUnderHost = (server) => {
|
|
850
|
-
const { secrets, ...rest } = server;
|
|
851
|
-
const domain = typeof rest.domain === "string" ? rest.domain : void 0;
|
|
852
|
-
const hosts = {
|
|
853
|
-
...domain === void 0 ? {} : { [domain]: {} },
|
|
854
|
-
...isJsonObject(rest.hosts) ? rest.hosts : {}
|
|
855
|
-
};
|
|
856
|
-
const host = domain ?? "default";
|
|
857
|
-
if (isJsonObject(secrets)) {
|
|
858
|
-
const current = isJsonObject(hosts[host]) ? hosts[host] : {};
|
|
859
|
-
const currentSecrets = isJsonObject(current.secrets) ? current.secrets : {};
|
|
860
|
-
hosts[host] = {
|
|
861
|
-
...current,
|
|
862
|
-
secrets: {
|
|
863
|
-
...secrets,
|
|
864
|
-
...currentSecrets
|
|
865
|
-
}
|
|
866
|
-
};
|
|
867
|
-
}
|
|
868
|
-
return Object.keys(hosts).length === 0 ? rest : {
|
|
869
|
-
...rest,
|
|
870
|
-
hosts
|
|
871
|
-
};
|
|
872
|
-
};
|
|
873
|
-
//#endregion
|
|
874
|
-
//#region src/auth/config/migrations/to-legacy-category.ts
|
|
875
|
-
/** 3 → 4: `servers.<name>` becomes `servers.<category>.<name>`. */
|
|
876
|
-
var toLegacyCategory = (name) => LEGACY_SERVER_CATEGORIES[name] ?? "other";
|
|
877
|
-
//#endregion
|
|
878
|
-
//#region src/auth/config/config-migrations.ts
|
|
879
|
-
/** One entry per version bump, in order; the version of the config file is the list length plus one. */
|
|
880
|
-
var CONFIG_MIGRATIONS = [
|
|
881
|
-
migrateServers(moveSecretsUnderHost),
|
|
882
|
-
migrateServers(dropLastUsedDomain),
|
|
883
|
-
groupServers(toLegacyCategory)
|
|
884
|
-
];
|
|
885
|
-
var CONFIG_VERSION = CONFIG_MIGRATIONS.length + 1;
|
|
886
|
-
//#endregion
|
|
887
|
-
//#region src/auth/config/resolve-config-file.ts
|
|
888
|
-
var resolveConfigFile = (env) => join(resolveHomeDir(env), CONFIG_FILE_NAME);
|
|
889
|
-
//#endregion
|
|
890
|
-
//#region src/auth/config/needs-migration.ts
|
|
891
|
-
/** True when the config file is an older version or the old `secrets.json` is still there. */
|
|
892
|
-
var needsMigration = async (env) => {
|
|
893
|
-
if (await readTokensText(resolveSecretsFile(env)) !== void 0) return true;
|
|
894
|
-
const text = await readTokensText(resolveConfigFile(env));
|
|
895
|
-
return text !== void 0 && readVersion(JSON.parse(text)) !== CONFIG_VERSION;
|
|
896
|
-
};
|
|
897
|
-
//#endregion
|
|
898
|
-
//#region src/auth/config/is-mcpkit-config.ts
|
|
899
|
-
var isStringRecord = (value) => isJsonObject(value) && Object.values(value).every((entry) => typeof entry === "string");
|
|
900
|
-
var isHostConfig = (value) => isJsonObject(value) && (value.secrets === void 0 || isStringRecord(value.secrets));
|
|
901
|
-
var isServerConfig = (value) => isJsonObject(value) && (value.hosts === void 0 || isJsonObject(value.hosts) && Object.values(value.hosts).every(isHostConfig)) && (value.projects === void 0 || isStringRecord(value.projects));
|
|
902
|
-
var isMcpkitConfig = (value) => isJsonObject(value) && value.version === CONFIG_VERSION && (value.servers === void 0 || isJsonObject(value.servers) && Object.values(value.servers).every((group) => isJsonObject(group) && Object.values(group).every(isServerConfig)));
|
|
903
|
-
//#endregion
|
|
904
|
-
//#region src/auth/config/read-config.ts
|
|
905
|
-
/**
|
|
906
|
-
* A missing file means no settings; an older version is migrated in memory (writing happens on the next save);
|
|
907
|
-
* a malformed file or one from a newer mcpkit fails instead of being overwritten.
|
|
908
|
-
*/
|
|
909
|
-
var readConfig = async (file) => {
|
|
910
|
-
const text = await readTokensText(file);
|
|
911
|
-
if (text === void 0) return { version: CONFIG_VERSION };
|
|
912
|
-
let migrated;
|
|
913
|
-
try {
|
|
914
|
-
migrated = migrateData(JSON.parse(text), CONFIG_MIGRATIONS);
|
|
915
|
-
} catch (error) {
|
|
916
|
-
throw new AuthError(`${file} ${error instanceof Error ? error.message : "is not a valid mcpkit config file"}`);
|
|
917
|
-
}
|
|
918
|
-
if (!isMcpkitConfig(migrated)) throw new AuthError(`${file} is not a valid mcpkit config file`);
|
|
919
|
-
return migrated;
|
|
920
|
-
};
|
|
921
|
-
//#endregion
|
|
922
|
-
//#region src/auth/config/migrate-config.ts
|
|
923
|
-
/** Writes the config in the current version and folds in the old `secrets.json`, then removes it. Call it under the config lock. */
|
|
924
|
-
var migrateConfig = async (env) => {
|
|
925
|
-
if (!await needsMigration(env)) return;
|
|
926
|
-
const configFile = resolveConfigFile(env);
|
|
927
|
-
const legacyFile = resolveSecretsFile(env);
|
|
928
|
-
const config = await readConfig(configFile);
|
|
929
|
-
const legacy = await readTokensText(legacyFile) === void 0 ? void 0 : await readStoredSecrets(legacyFile);
|
|
930
|
-
await writeJsonFile(configFile, legacy ? mergeLegacySecrets(config, legacy) : config);
|
|
931
|
-
if (legacy) await rm(legacyFile);
|
|
932
|
-
};
|
|
933
|
-
//#endregion
|
|
934
|
-
//#region src/auth/secret-file/create-exclusive-runner.ts
|
|
935
|
-
/** Runs tasks one at a time, so read-modify-write cycles on one file never lose each other's changes. */
|
|
936
|
-
var createExclusiveRunner = () => {
|
|
937
|
-
let pending = Promise.resolve();
|
|
938
|
-
return (task) => {
|
|
939
|
-
const run = pending.then(task);
|
|
940
|
-
pending = run.catch(() => void 0);
|
|
941
|
-
return run;
|
|
942
|
-
};
|
|
943
|
-
};
|
|
944
|
-
//#endregion
|
|
945
|
-
//#region src/auth/config/run-config-exclusive.ts
|
|
946
|
-
var runConfigExclusive = createExclusiveRunner();
|
|
947
|
-
//#endregion
|
|
948
|
-
//#region src/auth/config/load-config.ts
|
|
949
|
-
/** Reads the config, first migrating an older file or an old `secrets.json` to the current version. */
|
|
950
|
-
var loadConfig = async (env) => {
|
|
951
|
-
if (await needsMigration(env)) await runConfigExclusive(() => migrateConfig(env));
|
|
952
|
-
return readConfig(resolveConfigFile(env));
|
|
953
|
-
};
|
|
954
|
-
//#endregion
|
|
955
|
-
//#region src/auth/config/read-server-config.ts
|
|
956
|
-
var readServerConfig = (config, server) => config.servers?.[server.category]?.[server.name];
|
|
957
|
-
//#endregion
|
|
958
|
-
//#region src/auth/secrets/to-auth-key.ts
|
|
959
|
-
var toAuthKey = (auth) => `oauth ${auth.tokenUrl}`;
|
|
960
|
-
//#endregion
|
|
961
|
-
//#region src/auth/oauth/sign-in/pending-sign-ins.ts
|
|
962
|
-
/** Concurrent tool calls for one server and auth entry share a single browser sign-in. */
|
|
963
|
-
var pendingSignIns = /* @__PURE__ */ new Map();
|
|
964
|
-
//#endregion
|
|
965
|
-
//#region src/auth/token-store/is-optional-of-type.ts
|
|
966
|
-
var isOptionalOfType = (value, type) => value === void 0 || typeof value === type;
|
|
967
|
-
//#endregion
|
|
968
|
-
//#region src/auth/token-store/is-stored-token.ts
|
|
969
|
-
var isStoredToken = (value) => isJsonObject(value) && typeof value.accessToken === "string" && typeof value.tokenType === "string" && isOptionalOfType(value.refreshToken, "string") && isOptionalOfType(value.expiresAt, "number") && isOptionalOfType(value.scope, "string") && isOptionalOfType(value.authKey, "string");
|
|
970
|
-
//#endregion
|
|
971
|
-
//#region src/auth/token-store/is-stored-tokens.ts
|
|
972
|
-
var isStoredTokens = (value) => isJsonObject(value) && Object.values(value).every(isStoredToken);
|
|
973
|
-
//#endregion
|
|
974
|
-
//#region src/auth/token-store/read-tokens.ts
|
|
975
|
-
/** A missing file means no sessions; a malformed one fails instead of being overwritten. */
|
|
976
|
-
var readTokens = async (file) => {
|
|
977
|
-
const text = await readTokensText(file);
|
|
978
|
-
if (text === void 0) return {};
|
|
979
|
-
const data = JSON.parse(text);
|
|
980
|
-
if (!isStoredTokens(data)) throw new AuthError(`${file} is not a valid tokens file`);
|
|
981
|
-
return data;
|
|
982
|
-
};
|
|
983
|
-
//#endregion
|
|
984
|
-
//#region src/auth/token-store/resolve-tokens-file.ts
|
|
985
|
-
var resolveTokensFile = (env) => join(resolveHomeDir(env), TOKENS_FILE_NAME);
|
|
986
|
-
//#endregion
|
|
987
|
-
//#region src/auth/token-store/save-token.ts
|
|
988
|
-
var saveToken = async (env, serverName, token) => {
|
|
989
|
-
const file = resolveTokensFile(env);
|
|
990
|
-
await writeJsonFile(file, {
|
|
991
|
-
...await readTokens(file),
|
|
992
|
-
[serverName]: token
|
|
993
|
-
});
|
|
994
|
-
return file;
|
|
995
|
-
};
|
|
996
|
-
//#endregion
|
|
997
|
-
//#region src/auth/oauth/pkce/build-authorization-url.ts
|
|
998
|
-
var buildAuthorizationUrl = (auth, { redirectUri, challenge, state }) => {
|
|
999
|
-
const url = new URL(auth.authorizationUrl);
|
|
1000
|
-
for (const [name, value] of Object.entries(auth.authorizationParams ?? {})) url.searchParams.set(name, value);
|
|
1001
|
-
url.searchParams.set("response_type", "code");
|
|
1002
|
-
url.searchParams.set("client_id", auth.clientId);
|
|
1003
|
-
url.searchParams.set("redirect_uri", redirectUri);
|
|
1004
|
-
url.searchParams.set("code_challenge", challenge);
|
|
1005
|
-
url.searchParams.set("code_challenge_method", "S256");
|
|
1006
|
-
url.searchParams.set("state", state);
|
|
1007
|
-
if (auth.scopes && auth.scopes.length > 0) url.searchParams.set("scope", auth.scopes.join(" "));
|
|
1008
|
-
return url.toString();
|
|
1009
|
-
};
|
|
1010
|
-
//#endregion
|
|
1011
|
-
//#region src/auth/oauth/pkce/create-random-token.ts
|
|
1012
|
-
var createRandomToken = () => randomBytes(32).toString("base64url");
|
|
1013
|
-
//#endregion
|
|
1014
|
-
//#region src/auth/oauth/pkce/create-pkce-pair.ts
|
|
1015
|
-
/** RFC 7636 S256: the challenge is the base64url SHA-256 of the verifier. */
|
|
1016
|
-
var createPkcePair = () => {
|
|
1017
|
-
const verifier = createRandomToken();
|
|
1018
|
-
return {
|
|
1019
|
-
verifier,
|
|
1020
|
-
challenge: createHash("sha256").update(verifier).digest("base64url")
|
|
1021
|
-
};
|
|
1022
|
-
};
|
|
1023
|
-
//#endregion
|
|
1024
|
-
//#region src/auth/secrets/read-secret.ts
|
|
1025
|
-
var readSecret = (env, envName, serverName) => {
|
|
1026
|
-
const value = env[envName];
|
|
1027
|
-
if (!value) throw new AuthError(`${serverName}: missing credential, set the ${envName} environment variable or enter it in the credentials form`);
|
|
1028
|
-
return value;
|
|
1029
|
-
};
|
|
1030
|
-
//#endregion
|
|
1031
|
-
//#region src/auth/oauth/sign-in/parse-token-response.ts
|
|
1032
|
-
/** Some providers (GitHub) report token errors with HTTP 200, so the body decides. */
|
|
1033
|
-
var parseTokenResponse = (body, status, serverName, now) => {
|
|
1034
|
-
if (!isJsonObject(body)) throw new AuthError(`${serverName}: token endpoint returned ${status} without a JSON body`);
|
|
1035
|
-
if (typeof body.error === "string") throw new AuthError(`${serverName}: token request failed: ${typeof body.error_description === "string" ? body.error_description : body.error}`);
|
|
1036
|
-
if (typeof body.access_token !== "string") throw new AuthError(`${serverName}: token endpoint returned ${status} without an access_token`);
|
|
1037
|
-
return {
|
|
1038
|
-
accessToken: body.access_token,
|
|
1039
|
-
tokenType: typeof body.token_type === "string" ? body.token_type : "bearer",
|
|
1040
|
-
refreshToken: typeof body.refresh_token === "string" ? body.refresh_token : void 0,
|
|
1041
|
-
expiresAt: typeof body.expires_in === "number" ? now + body.expires_in * MS_PER_SECOND : void 0,
|
|
1042
|
-
scope: typeof body.scope === "string" ? body.scope : void 0
|
|
1043
|
-
};
|
|
1044
|
-
};
|
|
1045
|
-
//#endregion
|
|
1046
|
-
//#region src/auth/oauth/sign-in/read-json-body.ts
|
|
1047
|
-
var readJsonBody = async (response, serverName) => {
|
|
1048
|
-
const text = await response.text();
|
|
1049
|
-
try {
|
|
1050
|
-
return JSON.parse(text);
|
|
1051
|
-
} catch (error) {
|
|
1052
|
-
throw new AuthError(`${serverName}: token endpoint returned ${response.status} with invalid JSON: ${describeError(error)}`);
|
|
1053
|
-
}
|
|
1054
|
-
};
|
|
1055
|
-
//#endregion
|
|
1056
|
-
//#region src/auth/oauth/sign-in/request-token.ts
|
|
1057
|
-
var requestToken = async (auth, grant, serverName, { env, fetchImpl }) => {
|
|
1058
|
-
const secret = auth.clientSecretEnv ? readSecret(env, auth.clientSecretEnv, serverName) : void 0;
|
|
1059
|
-
const headers = {
|
|
1060
|
-
Accept: "application/json",
|
|
1061
|
-
"Content-Type": "application/x-www-form-urlencoded",
|
|
1062
|
-
...auth.tokenHeaders
|
|
1063
|
-
};
|
|
1064
|
-
const body = new URLSearchParams(grant);
|
|
1065
|
-
if (auth.clientAuthentication === "basic") headers.Authorization = `Basic ${Buffer.from(`${auth.clientId}:${secret ?? ""}`).toString("base64")}`;
|
|
1066
|
-
else {
|
|
1067
|
-
body.set("client_id", auth.clientId);
|
|
1068
|
-
if (secret !== void 0) body.set("client_secret", secret);
|
|
1069
|
-
}
|
|
1070
|
-
const response = await fetchImpl(auth.tokenUrl, {
|
|
1071
|
-
method: "POST",
|
|
1072
|
-
headers,
|
|
1073
|
-
body,
|
|
1074
|
-
signal: AbortSignal.timeout(TOKEN_REQUEST_TIMEOUT_MS)
|
|
1075
|
-
});
|
|
1076
|
-
return parseTokenResponse(await readJsonBody(response, serverName), response.status, serverName, Date.now());
|
|
1077
|
-
};
|
|
1078
|
-
//#endregion
|
|
1079
|
-
//#region src/auth/oauth/sign-in/exchange-authorization-code.ts
|
|
1080
|
-
var exchangeAuthorizationCode = (auth, { code, verifier, redirectUri }, serverName, context) => requestToken(auth, {
|
|
1081
|
-
grant_type: "authorization_code",
|
|
1082
|
-
code,
|
|
1083
|
-
redirect_uri: redirectUri,
|
|
1084
|
-
code_verifier: verifier
|
|
1085
|
-
}, serverName, context);
|
|
1086
|
-
//#endregion
|
|
1087
|
-
//#region src/auth/oauth/sign-in/listen-for-callback.ts
|
|
1088
|
-
/** Starts the loopback redirect target (RFC 8252) and resolves with the first callback's query. */
|
|
1089
|
-
var listenForCallback = async (port) => {
|
|
1090
|
-
const server = createServer();
|
|
1091
|
-
const params = new Promise((resolve) => {
|
|
1092
|
-
server.on("request", (request, response) => {
|
|
1093
|
-
const url = new URL(request.url ?? "/", `http://${LOOPBACK_HOST}`);
|
|
1094
|
-
if (url.pathname !== "/callback") {
|
|
1095
|
-
response.writeHead(404).end();
|
|
1096
|
-
return;
|
|
1097
|
-
}
|
|
1098
|
-
response.writeHead(200, { "content-type": "text/html; charset=utf-8" }).end(CALLBACK_PAGE);
|
|
1099
|
-
resolve(url.searchParams);
|
|
1100
|
-
});
|
|
1101
|
-
});
|
|
1102
|
-
await new Promise((resolve, reject) => {
|
|
1103
|
-
server.once("error", reject);
|
|
1104
|
-
server.listen(port, LOOPBACK_HOST, resolve);
|
|
1105
|
-
});
|
|
1106
|
-
const address = server.address();
|
|
1107
|
-
if (address === null || typeof address === "string") {
|
|
1108
|
-
server.close();
|
|
1109
|
-
throw new Error("callback server has no TCP address");
|
|
1110
|
-
}
|
|
1111
|
-
return {
|
|
1112
|
-
redirectUri: `http://${LOOPBACK_HOST}:${address.port}${CALLBACK_PATH}`,
|
|
1113
|
-
params,
|
|
1114
|
-
close: () => new Promise((resolve, reject) => {
|
|
1115
|
-
server.closeAllConnections();
|
|
1116
|
-
server.close((error) => error ? reject(error) : resolve());
|
|
1117
|
-
})
|
|
1118
|
-
};
|
|
1119
|
-
};
|
|
1120
|
-
//#endregion
|
|
1121
|
-
//#region src/auth/oauth/sign-in/read-authorization-code.ts
|
|
1122
|
-
var readAuthorizationCode = (params, expectedState, serverName) => {
|
|
1123
|
-
const error = params.get("error");
|
|
1124
|
-
if (error) throw new AuthError(`${serverName}: authorization denied: ${params.get("error_description") ?? error}`);
|
|
1125
|
-
if (params.get("state") !== expectedState) throw new AuthError(`${serverName}: authorization state mismatch, sign-in aborted`);
|
|
1126
|
-
const code = params.get("code");
|
|
1127
|
-
if (!code) throw new AuthError(`${serverName}: authorization callback has no code`);
|
|
1128
|
-
return code;
|
|
1129
|
-
};
|
|
1130
|
-
//#endregion
|
|
1131
|
-
//#region src/auth/oauth/sign-in/wait-with-timeout.ts
|
|
1132
|
-
var waitWithTimeout = async (promise, timeoutMs, message) => {
|
|
1133
|
-
let timer;
|
|
1134
|
-
const timeout = new Promise((_, reject) => {
|
|
1135
|
-
timer = setTimeout(() => reject(new Error(message)), timeoutMs);
|
|
1136
|
-
});
|
|
1137
|
-
try {
|
|
1138
|
-
return await Promise.race([promise, timeout]);
|
|
1139
|
-
} finally {
|
|
1140
|
-
clearTimeout(timer);
|
|
1141
|
-
}
|
|
1142
|
-
};
|
|
1143
|
-
//#endregion
|
|
1144
|
-
//#region src/auth/oauth/sign-in/sign-in.ts
|
|
1145
|
-
/** Runs the authorization code + PKCE flow through a loopback redirect and stores the token. */
|
|
1146
|
-
var signIn = async (serverName, auth, { context, onAuthorizationUrl }) => {
|
|
1147
|
-
const { verifier, challenge } = createPkcePair();
|
|
1148
|
-
const state = createRandomToken();
|
|
1149
|
-
const listener = await listenForCallback(auth.redirectPort ?? 8976);
|
|
1150
|
-
try {
|
|
1151
|
-
const { redirectUri } = listener;
|
|
1152
|
-
onAuthorizationUrl(buildAuthorizationUrl(auth, {
|
|
1153
|
-
redirectUri,
|
|
1154
|
-
challenge,
|
|
1155
|
-
state
|
|
1156
|
-
}));
|
|
1157
|
-
const token = {
|
|
1158
|
-
...await exchangeAuthorizationCode(auth, {
|
|
1159
|
-
code: readAuthorizationCode(await waitWithTimeout(listener.params, SIGN_IN_TIMEOUT_MS, `${serverName}: sign-in timed out`), state, serverName),
|
|
1160
|
-
verifier,
|
|
1161
|
-
redirectUri
|
|
1162
|
-
}, serverName, context),
|
|
1163
|
-
authKey: toAuthKey(auth)
|
|
1164
|
-
};
|
|
1165
|
-
return {
|
|
1166
|
-
token,
|
|
1167
|
-
tokensFile: await saveToken(context.env, serverName, token)
|
|
1168
|
-
};
|
|
1169
|
-
} finally {
|
|
1170
|
-
await listener.close();
|
|
1171
|
-
}
|
|
1172
|
-
};
|
|
1173
|
-
//#endregion
|
|
1174
|
-
//#region src/auth/oauth/sign-in/sign-in-once.ts
|
|
1175
|
-
var signInOnce = (serverName, auth, options) => {
|
|
1176
|
-
const key = `${serverName} ${toAuthKey(auth)}`;
|
|
1177
|
-
const pending = pendingSignIns.get(key);
|
|
1178
|
-
if (pending) return pending;
|
|
1179
|
-
const signingIn = signIn(serverName, auth, options).finally(() => {
|
|
1180
|
-
pendingSignIns.delete(key);
|
|
1181
|
-
});
|
|
1182
|
-
pendingSignIns.set(key, signingIn);
|
|
1183
|
-
return signingIn;
|
|
1184
|
-
};
|
|
1185
|
-
//#endregion
|
|
1186
|
-
//#region src/auth/resolve/create-resolved-auth.ts
|
|
1187
|
-
var createResolvedAuth = (headers = {}, query = {}) => {
|
|
1188
|
-
return {
|
|
1189
|
-
headers,
|
|
1190
|
-
query
|
|
1191
|
-
};
|
|
1192
|
-
};
|
|
1193
|
-
//#endregion
|
|
1194
|
-
//#region src/auth/resolve/resolve-signed-in-auth.ts
|
|
1195
|
-
/** Runs the browser sign-in for one OAuth2 entry and stores the token in `tokens.json`. */
|
|
1196
|
-
var resolveSignedInAuth = async (serverName, auth, context) => {
|
|
1197
|
-
const { onAuthorizationUrl } = context;
|
|
1198
|
-
if (!onAuthorizationUrl) throw new AuthError(`${serverName}: sign-in needs a browser, which this caller does not provide`);
|
|
1199
|
-
const { token } = await signInOnce(serverName, auth, {
|
|
1200
|
-
context,
|
|
1201
|
-
onAuthorizationUrl
|
|
1202
|
-
});
|
|
1203
|
-
return createResolvedAuth({ Authorization: `Bearer ${token.accessToken}` });
|
|
1204
|
-
};
|
|
1205
|
-
//#endregion
|
|
1206
|
-
//#region src/auth/config/update-server-config.ts
|
|
1207
|
-
/** Read-modify-write of one server's entry, serialized so concurrent saves never lose each other's changes. */
|
|
1208
|
-
var updateServerConfig = (env, server, change) => runConfigExclusive(async () => {
|
|
1209
|
-
await migrateConfig(env);
|
|
1210
|
-
const file = resolveConfigFile(env);
|
|
1211
|
-
const config = await readConfig(file);
|
|
1212
|
-
await writeJsonFile(file, {
|
|
1213
|
-
...config,
|
|
1214
|
-
servers: {
|
|
1215
|
-
...config.servers,
|
|
1216
|
-
[server.category]: {
|
|
1217
|
-
...config.servers?.[server.category],
|
|
1218
|
-
[server.name]: change(readServerConfig(config, server) ?? {})
|
|
1219
|
-
}
|
|
1220
|
-
}
|
|
1221
|
-
});
|
|
1222
|
-
return file;
|
|
1223
|
-
});
|
|
1224
|
-
//#endregion
|
|
1225
|
-
//#region src/auth/config/save-server-domain.ts
|
|
1226
|
-
/** Makes the host a known host and, with a project, binds the project to it. */
|
|
1227
|
-
var saveServerDomain = (env, server, domain, projectKey) => updateServerConfig(env, server, (current) => ({
|
|
1228
|
-
...current,
|
|
1229
|
-
hosts: {
|
|
1230
|
-
...current.hosts,
|
|
1231
|
-
[domain]: { ...current.hosts?.[domain] }
|
|
1232
|
-
},
|
|
1233
|
-
...projectKey === void 0 ? {} : { projects: {
|
|
1234
|
-
...current.projects,
|
|
1235
|
-
[projectKey]: domain
|
|
1236
|
-
} }
|
|
1237
|
-
}));
|
|
1238
|
-
//#endregion
|
|
1239
|
-
//#region src/auth/project/parse-remote-host.ts
|
|
1240
|
-
var SCP_LIKE_REMOTE = /^(?:[^@/]+@)?([^:/]+):(?!\/\/)/;
|
|
1241
|
-
/** The host of a git remote URL (https, ssh or scp-like `git@host:path`), lowercase and without a port. */
|
|
1242
|
-
var parseRemoteHost = (remote) => {
|
|
1243
|
-
if (remote.includes("://")) try {
|
|
1244
|
-
return new URL(remote).hostname.toLowerCase() || void 0;
|
|
1245
|
-
} catch {
|
|
1246
|
-
return;
|
|
1247
|
-
}
|
|
1248
|
-
return SCP_LIKE_REMOTE.exec(remote)?.[1]?.toLowerCase();
|
|
1249
|
-
};
|
|
1250
|
-
//#endregion
|
|
1251
|
-
//#region src/auth/project/read-git-output.ts
|
|
1252
|
-
/** Trimmed stdout of a git command in `cwd`; undefined when git is missing, `cwd` is not a repository or there is no such setting. */
|
|
1253
|
-
var readGitOutput = (cwd, args) => new Promise((resolve) => {
|
|
1254
|
-
execFile("git", [...args], {
|
|
1255
|
-
cwd,
|
|
1256
|
-
timeout: GIT_COMMAND_TIMEOUT_MS
|
|
1257
|
-
}, (error, stdout) => {
|
|
1258
|
-
resolve(error ? void 0 : stdout.trim() || void 0);
|
|
1259
|
-
});
|
|
1260
|
-
});
|
|
1261
|
-
//#endregion
|
|
1262
|
-
//#region src/auth/project/resolve-project.ts
|
|
1263
|
-
/** The project a call belongs to: its git root (else the directory itself) and the host of its `origin` remote. */
|
|
1264
|
-
var resolveProject = async (directory) => {
|
|
1265
|
-
const root = await readGitOutput(directory, ["rev-parse", "--show-toplevel"]);
|
|
1266
|
-
const remote = root === void 0 ? void 0 : await readGitOutput(root, [
|
|
1267
|
-
"remote",
|
|
1268
|
-
"get-url",
|
|
1269
|
-
"origin"
|
|
1270
|
-
]);
|
|
1271
|
-
return {
|
|
1272
|
-
key: root ?? directory,
|
|
1273
|
-
remoteHost: remote && parseRemoteHost(remote)
|
|
1274
|
-
};
|
|
1275
|
-
};
|
|
1276
|
-
//#endregion
|
|
1277
|
-
//#region src/auth/credentials/resolve/save-credentials.ts
|
|
1278
|
-
var saveCredentials = async (owner, values, secretStore) => {
|
|
1279
|
-
if (!secretStore) return;
|
|
1280
|
-
await Promise.all(Object.entries(values).map(([key, value]) => secretStore.set(owner, key, value)));
|
|
1281
|
-
};
|
|
1282
|
-
//#endregion
|
|
1283
|
-
//#region src/auth/credentials/resolve/save-form-answer.ts
|
|
1284
|
-
/** Credentials go to the secret store under their host; the host is remembered for the project that asked for it. */
|
|
1285
|
-
var saveFormAnswer = async (manifest, values, domain, context) => {
|
|
1286
|
-
await saveCredentials({
|
|
1287
|
-
name: manifest.name,
|
|
1288
|
-
category: manifest.category,
|
|
1289
|
-
domain
|
|
1290
|
-
}, values, context.secretStore);
|
|
1291
|
-
if (domain === void 0) return;
|
|
1292
|
-
const project = context.projectDir === void 0 ? void 0 : await resolveProject(context.projectDir);
|
|
1293
|
-
await saveServerDomain(context.env, manifest, domain, project?.key);
|
|
1294
|
-
};
|
|
1295
|
-
//#endregion
|
|
1296
|
-
//#region src/auth/credentials/resolve/resolve-form-sign-in.ts
|
|
1297
|
-
var resolveFormSignIn = async (manifest, response, domain, context) => {
|
|
1298
|
-
const oauth = manifest.auth?.find(isInteractiveAuth);
|
|
1299
|
-
if (!oauth) throw new AuthError(`${manifest.name}: this server has no sign-in`);
|
|
1300
|
-
return {
|
|
1301
|
-
auth: await resolveSignedInAuth(manifest.name, oauth, context),
|
|
1302
|
-
manifest,
|
|
1303
|
-
commit: () => saveFormAnswer(manifest, {}, domain, context)
|
|
1304
|
-
};
|
|
1305
|
-
};
|
|
1306
|
-
//#endregion
|
|
1307
|
-
//#region src/auth/resolve/encode-basic-credentials.ts
|
|
1308
|
-
var encodeBasicCredentials = (username, password) => `Basic ${Buffer.from(`${username}:${password}`).toString("base64")}`;
|
|
1309
|
-
//#endregion
|
|
1310
|
-
//#region src/auth/resolve/resolve-static-auth.ts
|
|
1311
|
-
/** Builds a fallback entry's auth from its credential values, keyed by env var name. */
|
|
1312
|
-
var resolveStaticAuth = (auth, serverName, env) => {
|
|
1313
|
-
switch (auth.type) {
|
|
1314
|
-
case "none": return createResolvedAuth();
|
|
1315
|
-
case "bearer": return createResolvedAuth({ Authorization: `Bearer ${readSecret(env, auth.env, serverName)}` });
|
|
1316
|
-
case "header": return createResolvedAuth({ [auth.name]: `${auth.prefix ?? ""}${readSecret(env, auth.env, serverName)}` });
|
|
1317
|
-
case "query": return createResolvedAuth({}, { [auth.name]: readSecret(env, auth.env, serverName) });
|
|
1318
|
-
case "basic": return createResolvedAuth({ Authorization: encodeBasicCredentials(readSecret(env, auth.usernameEnv, serverName), readSecret(env, auth.passwordEnv, serverName)) });
|
|
1319
|
-
default: throw new AuthError(`${serverName}: unsupported auth ${JSON.stringify(auth)}`);
|
|
1320
|
-
}
|
|
1321
|
-
};
|
|
1322
|
-
//#endregion
|
|
1323
|
-
//#region src/auth/credentials/response/trim-values.ts
|
|
1324
|
-
var trimValues = (values) => Object.fromEntries(Object.entries(values).map(([key, value]) => [key, value.trim()]));
|
|
1325
|
-
//#endregion
|
|
1326
|
-
//#region src/auth/credentials/resolve/resolve-form-token.ts
|
|
1327
|
-
var resolveFormToken = (manifest, response, domain, context) => {
|
|
1328
|
-
const auth = manifest.auth?.[response.option];
|
|
1329
|
-
if (!auth || isInteractiveAuth(auth)) throw new AuthError(`${manifest.name}: auth[${response.option}] does not take credentials`);
|
|
1330
|
-
const values = trimValues(response.values);
|
|
1331
|
-
return {
|
|
1332
|
-
auth: resolveStaticAuth(auth, manifest.name, values),
|
|
1333
|
-
manifest,
|
|
1334
|
-
commit: () => saveFormAnswer(manifest, values, domain, context)
|
|
1335
|
-
};
|
|
1336
|
-
};
|
|
1337
|
-
//#endregion
|
|
1338
|
-
//#region src/auth/credentials/response/validate-response-domain.ts
|
|
1339
|
-
var validateResponseDomain = (request, domain) => {
|
|
1340
|
-
if (!request.domain) return domain === void 0 ? [] : ["the domain of this server cannot be changed"];
|
|
1341
|
-
if (!isDomainValue(domain)) return [`${request.domain.label} must look like host[:port][/path]`];
|
|
1342
|
-
return [];
|
|
1343
|
-
};
|
|
1344
|
-
//#endregion
|
|
1345
|
-
//#region src/auth/credentials/response/validate-token-response.ts
|
|
1346
|
-
var validateTokenResponse = (request, response) => {
|
|
1347
|
-
const option = request.options.find((candidate) => candidate.index === response.option);
|
|
1348
|
-
if (!option) return ["choose one of the offered credentials"];
|
|
1349
|
-
const values = isStringRecord$1(response.values) ? response.values : {};
|
|
1350
|
-
return option.fields.filter((field) => !values[field.key]?.trim()).map((field) => fillTemplate(request.texts.requiredField, { label: field.label }));
|
|
1351
|
-
};
|
|
1352
|
-
//#endregion
|
|
1353
|
-
//#region src/auth/credentials/response/validate-credential-response.ts
|
|
1354
|
-
/** The form answer comes over a local HTTP request, so it is checked against what was asked. */
|
|
1355
|
-
var validateCredentialResponse = (request, response) => {
|
|
1356
|
-
if (!isJsonObject(response)) return ["the answer must be a JSON object"];
|
|
1357
|
-
const domainErrors = validateResponseDomain(request, response.domain);
|
|
1358
|
-
if (response.method === "sign-in") return request.signIn ? domainErrors : ["this server has no sign-in", ...domainErrors];
|
|
1359
|
-
if (response.method === "token") return [...domainErrors, ...validateTokenResponse(request, response)];
|
|
1360
|
-
return ["method must be \"token\" or \"sign-in\""];
|
|
1361
|
-
};
|
|
1362
|
-
//#endregion
|
|
1363
|
-
//#region src/auth/ui/build-ui-texts.ts
|
|
1364
|
-
/** The manifest's texts over the defaults, with the server's name filled in. */
|
|
1365
|
-
var buildUiTexts = (manifest) => {
|
|
1366
|
-
const merged = {
|
|
1367
|
-
...DEFAULT_UI_TEXTS,
|
|
1368
|
-
...manifest.ui?.texts
|
|
1369
|
-
};
|
|
1370
|
-
const texts = { ...merged };
|
|
1371
|
-
for (const key of UI_TEXT_KEYS) texts[key] = fillTemplate(merged[key], { server: manifest.name });
|
|
1372
|
-
return texts;
|
|
1373
|
-
};
|
|
1374
|
-
//#endregion
|
|
1375
|
-
//#region src/auth/credentials/request/build-domain-field.ts
|
|
1376
|
-
/** A domain set through its env var is not offered for editing. */
|
|
1377
|
-
var buildDomainField = (manifest, domain, knownHosts, env, texts) => {
|
|
1378
|
-
const spec = manifest.domain;
|
|
1379
|
-
if (!spec || spec.env && env[spec.env]) return;
|
|
1380
|
-
return {
|
|
1381
|
-
label: spec.label ?? texts.domainLabel,
|
|
1382
|
-
hint: spec.hint ?? texts.domainHint,
|
|
1383
|
-
placeholder: spec.placeholder ?? texts.domainPlaceholder,
|
|
1384
|
-
value: domain ?? "",
|
|
1385
|
-
knownHosts
|
|
1386
|
-
};
|
|
1387
|
-
};
|
|
1388
|
-
//#endregion
|
|
1389
|
-
//#region src/auth/ui/to-option-actions.ts
|
|
1390
|
-
/** `{server}` is known when the form opens; the domain can still change while it is open. A CLI prints one token. */
|
|
1391
|
-
var toOptionActions = (ui, serverName, fieldCount) => (ui?.actions ?? []).flatMap((action) => {
|
|
1392
|
-
if (action.type === "cli") return fieldCount === 1 ? [action] : [];
|
|
1393
|
-
return [{
|
|
1394
|
-
...action,
|
|
1395
|
-
url: fillTemplate(action.url, { server: encodeURIComponent(serverName) })
|
|
1396
|
-
}];
|
|
1397
|
-
});
|
|
1398
|
-
//#endregion
|
|
1399
|
-
//#region src/auth/credentials/request/to-credential-field.ts
|
|
1400
|
-
var toCredentialField = (key, label, secret, texts, spec) => {
|
|
1401
|
-
return {
|
|
1402
|
-
key,
|
|
1403
|
-
label: spec?.label ?? label,
|
|
1404
|
-
hint: spec?.hint ?? fillTemplate(texts.fieldHint, { key }),
|
|
1405
|
-
placeholder: spec?.placeholder ?? "",
|
|
1406
|
-
secret: spec?.secret ?? secret
|
|
1407
|
-
};
|
|
1408
|
-
};
|
|
1409
|
-
//#endregion
|
|
1410
|
-
//#region src/auth/credentials/request/list-credential-fields.ts
|
|
1411
|
-
var listCredentialFields = (auth, texts) => {
|
|
1412
|
-
if (auth.type === "none") return [];
|
|
1413
|
-
const inputs = auth.ui?.inputs;
|
|
1414
|
-
switch (auth.type) {
|
|
1415
|
-
case "bearer": return [toCredentialField(auth.env, texts.tokenLabel, true, texts, inputs?.[auth.env])];
|
|
1416
|
-
case "header": return [toCredentialField(auth.env, fillTemplate(texts.headerLabel, { name: auth.name }), true, texts, inputs?.[auth.env])];
|
|
1417
|
-
case "query": return [toCredentialField(auth.env, fillTemplate(texts.queryLabel, { name: auth.name }), true, texts, inputs?.[auth.env])];
|
|
1418
|
-
case "basic": return [toCredentialField(auth.usernameEnv, texts.usernameLabel, false, texts, inputs?.[auth.usernameEnv]), toCredentialField(auth.passwordEnv, texts.passwordLabel, true, texts, inputs?.[auth.passwordEnv])];
|
|
1419
|
-
default: return auth;
|
|
1420
|
-
}
|
|
1421
|
-
};
|
|
1422
|
-
//#endregion
|
|
1423
|
-
//#region src/auth/credentials/request/to-credential-options.ts
|
|
1424
|
-
var toCredentialOptions = (auth, index, serverName, texts) => {
|
|
1425
|
-
if (isInteractiveAuth(auth)) return [];
|
|
1426
|
-
const fields = listCredentialFields(auth, texts);
|
|
1427
|
-
if (fields.length === 0) return [];
|
|
1428
|
-
return [{
|
|
1429
|
-
index,
|
|
1430
|
-
label: "label" in auth && auth.label || describeAuthSpec(auth),
|
|
1431
|
-
fields,
|
|
1432
|
-
actions: toOptionActions("ui" in auth ? auth.ui : void 0, serverName, fields.length)
|
|
1433
|
-
}];
|
|
1434
|
-
};
|
|
1435
|
-
//#endregion
|
|
1436
|
-
//#region src/auth/credentials/request/build-credential-request.ts
|
|
1437
|
-
var buildCredentialRequest = (manifest, domain, knownHosts, env) => {
|
|
1438
|
-
const auth = manifest.auth ?? [];
|
|
1439
|
-
const texts = buildUiTexts(manifest);
|
|
1440
|
-
const domainField = buildDomainField(manifest, domain, knownHosts, env, texts);
|
|
1441
|
-
return {
|
|
1442
|
-
serverName: manifest.name,
|
|
1443
|
-
texts,
|
|
1444
|
-
...domainField ? { domain: domainField } : {},
|
|
1445
|
-
...domain === void 0 ? {} : { domainInUse: domain },
|
|
1446
|
-
options: auth.flatMap((entry, index) => toCredentialOptions(entry, index, manifest.name, texts)),
|
|
1447
|
-
signIn: auth.some(isInteractiveAuth)
|
|
1448
|
-
};
|
|
1449
|
-
};
|
|
1450
|
-
//#endregion
|
|
1451
|
-
//#region src/auth/credentials/request/pending-credential-requests.ts
|
|
1452
|
-
/** Per server: the open credentials form, shared by calls that arrive while it is open. */
|
|
1453
|
-
var pendingCredentialRequests = /* @__PURE__ */ new Map();
|
|
1454
|
-
//#endregion
|
|
1455
|
-
//#region src/auth/credentials/request/request-credentials-once.ts
|
|
1456
|
-
/** One form per server at a time; the request is built only by the call that opens it. */
|
|
1457
|
-
var requestCredentialsOnce = (serverName, createRequest, requestCredentials) => {
|
|
1458
|
-
const pending = pendingCredentialRequests.get(serverName);
|
|
1459
|
-
if (pending) return pending;
|
|
1460
|
-
const exchange = createRequest().then(async (request) => ({
|
|
1461
|
-
request,
|
|
1462
|
-
response: await requestCredentials(request)
|
|
1463
|
-
})).finally(() => {
|
|
1464
|
-
pendingCredentialRequests.delete(serverName);
|
|
1465
|
-
});
|
|
1466
|
-
pendingCredentialRequests.set(serverName, exchange);
|
|
1467
|
-
return exchange;
|
|
1468
|
-
};
|
|
1469
|
-
//#endregion
|
|
1470
|
-
//#region src/auth/credentials/request/resolve-credential-form.ts
|
|
1471
|
-
/** Asks the user for a domain and credentials, or to sign in; what they enter is saved once the API accepts it. */
|
|
1472
|
-
var resolveCredentialForm = async (manifest, domain, context) => {
|
|
1473
|
-
const { requestCredentials } = context;
|
|
1474
|
-
if (!requestCredentials) throw new AuthError(`${manifest.name}: asking for credentials needs a form, which this caller does not provide`);
|
|
1475
|
-
const { request, response } = await requestCredentialsOnce(manifest.name, async () => {
|
|
1476
|
-
return buildCredentialRequest(manifest, domain, listKnownHosts(readServerConfig(await loadConfig(context.env), manifest)), context.env);
|
|
1477
|
-
}, requestCredentials);
|
|
1478
|
-
const errors = validateCredentialResponse(request, response);
|
|
1479
|
-
if (errors.length > 0) throw new AuthError(`${manifest.name}: invalid credentials form answer: ${errors.join("; ")}`);
|
|
1480
|
-
const chosen = response.domain ?? domain;
|
|
1481
|
-
const target = applyDomain(manifest, chosen);
|
|
1482
|
-
if (response.method === "sign-in") return resolveFormSignIn(target, response, chosen, context);
|
|
1483
|
-
return resolveFormToken(target, response, chosen, context);
|
|
1484
|
-
};
|
|
1485
|
-
//#endregion
|
|
1486
|
-
//#region src/auth/ui/const.ts
|
|
1487
|
-
var WEB_HOST_API_PREFIX = "api.";
|
|
1488
|
-
//#endregion
|
|
1489
|
-
//#region src/auth/ui/to-web-host.ts
|
|
1490
|
-
/** `api.github.com` → `github.com`, `api.acme.ghe.com` → `acme.ghe.com`, `ghe.example.com/api/v3` → `ghe.example.com`. */
|
|
1491
|
-
var toWebHost = (domain) => {
|
|
1492
|
-
const [host = domain, ...path] = domain.split("/");
|
|
1493
|
-
if (path.length === 0 && host.startsWith("api.")) return host.slice(WEB_HOST_API_PREFIX.length);
|
|
1494
|
-
return host;
|
|
1495
|
-
};
|
|
1496
|
-
//#endregion
|
|
1497
|
-
//#region src/auth/project/pick-remote-host.ts
|
|
1498
|
-
var toHostname = (domain) => (domain.split("/")[0] ?? domain).split(":")[0]?.toLowerCase();
|
|
1499
|
-
/** The known host a git remote host points at: `github.com` picks `api.github.com`, a self-managed host picks itself. */
|
|
1500
|
-
var pickRemoteHost = (knownHosts, remoteHost) => knownHosts.find((host) => toHostname(host) === remoteHost || toHostname(toWebHost(host)) === remoteHost);
|
|
1501
|
-
//#endregion
|
|
1502
|
-
//#region src/auth/credentials/resolve/resolve-domain.ts
|
|
1503
|
-
/**
|
|
1504
|
-
* The host of a call, in this order: its env var; the host this project was bound to; the known host the project's
|
|
1505
|
-
* git remote points at (when the manifest asks for it); the only host in use, or the manifest default. With several
|
|
1506
|
-
* hosts and no way to tell, it is undefined so the form asks.
|
|
1507
|
-
*/
|
|
1508
|
-
var resolveDomain = async (manifest, context) => {
|
|
1509
|
-
const { domain } = manifest;
|
|
1510
|
-
if (!domain) return;
|
|
1511
|
-
const fromEnv = domain.env ? context.env[domain.env] : void 0;
|
|
1512
|
-
const saved = fromEnv ? void 0 : await resolveSavedDomain(manifest, context);
|
|
1513
|
-
if (saved === null) return;
|
|
1514
|
-
const value = fromEnv || saved || domain.default;
|
|
1515
|
-
if (value !== void 0 && !isDomainValue(value)) throw new AuthError(`${manifest.name}: domain "${value}" must look like host[:port][/path]`);
|
|
1516
|
-
return value;
|
|
1517
|
-
};
|
|
1518
|
-
/** Null when several hosts are known and nothing says which one this project uses; undefined when none is known. */
|
|
1519
|
-
var resolveSavedDomain = async (manifest, context) => {
|
|
1520
|
-
const server = readServerConfig(await loadConfig(context.env), manifest);
|
|
1521
|
-
const knownHosts = listKnownHosts(server);
|
|
1522
|
-
if (knownHosts.length === 0) return;
|
|
1523
|
-
if (context.projectDir === void 0) return knownHosts.length === 1 ? knownHosts[0] : null;
|
|
1524
|
-
const project = await resolveProject(context.projectDir);
|
|
1525
|
-
const bound = server?.projects?.[project.key];
|
|
1526
|
-
if (bound) return bound;
|
|
1527
|
-
const remote = manifest.domain?.matchGitRemote && project.remoteHost ? pickRemoteHost(knownHosts, project.remoteHost) : void 0;
|
|
1528
|
-
if (remote) return remote;
|
|
1529
|
-
return knownHosts.length === 1 ? knownHosts[0] : null;
|
|
1530
|
-
};
|
|
1531
|
-
//#endregion
|
|
1532
|
-
//#region src/auth/credentials/response/is-valid-credential-response.ts
|
|
1533
|
-
var isValidCredentialResponse = (request, response) => validateCredentialResponse(request, response).length === 0;
|
|
1534
|
-
//#endregion
|
|
1535
|
-
//#region src/auth/credentials/resolve/read-fallback-values.ts
|
|
1536
|
-
/** Each credential from its env var, else from the secret store. */
|
|
1537
|
-
var readFallbackValues = async (auth, owner, context) => {
|
|
1538
|
-
const entries = await Promise.all(listAuthEnvNames(auth).map(async (name) => {
|
|
1539
|
-
return [name, context.env[name] || await context.secretStore?.get(owner, name)];
|
|
1540
|
-
}));
|
|
1541
|
-
return Object.fromEntries(entries);
|
|
1542
|
-
};
|
|
1543
|
-
//#endregion
|
|
1544
|
-
//#region src/auth/resolve/resolve-fallback-auth.ts
|
|
1545
|
-
var resolveFallbackAuth = async (auth, manifest, domain, context) => resolveStaticAuth(auth, manifest.name, await readFallbackValues(auth, {
|
|
1546
|
-
name: manifest.name,
|
|
1547
|
-
category: manifest.category,
|
|
1548
|
-
domain
|
|
1549
|
-
}, context));
|
|
1550
|
-
//#endregion
|
|
1551
|
-
//#region src/auth/oauth/refresh/is-token-expired.ts
|
|
1552
|
-
var isTokenExpired = (token, now) => token.expiresAt !== void 0 && token.expiresAt - 6e4 <= now;
|
|
1553
|
-
//#endregion
|
|
1554
|
-
//#region src/auth/oauth/refresh/pending-refreshes.ts
|
|
1555
|
-
/** Refresh tokens can rotate, so concurrent tool calls for one server must share a single refresh. */
|
|
1556
|
-
var pendingRefreshes = /* @__PURE__ */ new Map();
|
|
1557
|
-
//#endregion
|
|
1558
|
-
//#region src/auth/oauth/refresh/refresh-stored-token.ts
|
|
1559
|
-
/** Providers may omit refresh_token on refresh; the previous one then stays valid. */
|
|
1560
|
-
var refreshStoredToken = async (serverName, auth, token, context) => {
|
|
1561
|
-
if (!token.refreshToken) throw new AuthError(`${serverName}: the stored session expired and has no refresh token`);
|
|
1562
|
-
const fresh = await requestToken(auth, {
|
|
1563
|
-
grant_type: "refresh_token",
|
|
1564
|
-
refresh_token: token.refreshToken
|
|
1565
|
-
}, serverName, context);
|
|
1566
|
-
const refreshed = {
|
|
1567
|
-
...fresh,
|
|
1568
|
-
refreshToken: fresh.refreshToken ?? token.refreshToken,
|
|
1569
|
-
authKey: token.authKey
|
|
1570
|
-
};
|
|
1571
|
-
await saveToken(context.env, serverName, refreshed);
|
|
1572
|
-
return refreshed;
|
|
1573
|
-
};
|
|
1574
|
-
//#endregion
|
|
1575
|
-
//#region src/auth/oauth/refresh/refresh-once.ts
|
|
1576
|
-
var refreshOnce = (serverName, auth, token, context) => {
|
|
1577
|
-
const pending = pendingRefreshes.get(serverName);
|
|
1578
|
-
if (pending) return pending;
|
|
1579
|
-
const refresh = refreshStoredToken(serverName, auth, token, context).finally(() => {
|
|
1580
|
-
pendingRefreshes.delete(serverName);
|
|
1581
|
-
});
|
|
1582
|
-
pendingRefreshes.set(serverName, refresh);
|
|
1583
|
-
return refresh;
|
|
1584
|
-
};
|
|
1585
|
-
//#endregion
|
|
1586
|
-
//#region src/auth/oauth/refresh/read-fresh-access-token.ts
|
|
1587
|
-
var readFreshAccessToken = async (serverName, auth, stored, context) => {
|
|
1588
|
-
if (!isTokenExpired(stored, Date.now())) return stored.accessToken;
|
|
1589
|
-
return (await refreshOnce(serverName, auth, stored, context)).accessToken;
|
|
1590
|
-
};
|
|
1591
|
-
//#endregion
|
|
1592
|
-
//#region src/auth/token-store/read-stored-token.ts
|
|
1593
|
-
var readStoredToken = async (env, serverName) => {
|
|
1594
|
-
return (await readTokens(resolveTokensFile(env)))[serverName];
|
|
1595
|
-
};
|
|
1596
|
-
//#endregion
|
|
1597
|
-
//#region src/auth/resolve/find-token-auth.ts
|
|
1598
|
-
/** Tokens saved before `authKey` existed belong to the first OAuth2 entry. */
|
|
1599
|
-
var findTokenAuth = (entries, token) => {
|
|
1600
|
-
if (token.authKey === void 0) return entries[0];
|
|
1601
|
-
return entries.find((entry) => toAuthKey(entry) === token.authKey);
|
|
1602
|
-
};
|
|
1603
|
-
//#endregion
|
|
1604
|
-
//#region src/auth/resolve/resolve-stored-auth.ts
|
|
1605
|
-
/** The server's token from `tokens.json`, refreshed against the OAuth2 entry that issued it. */
|
|
1606
|
-
var resolveStoredAuth = async (serverName, auth, context) => {
|
|
1607
|
-
const stored = await readStoredToken(context.env, serverName);
|
|
1608
|
-
if (!stored) throw new AuthError(`${serverName}: not signed in yet`);
|
|
1609
|
-
const issuer = findTokenAuth(auth.filter(isInteractiveAuth), stored);
|
|
1610
|
-
if (!issuer) throw new AuthError(`${serverName}: the stored token comes from an auth entry that is no longer in the manifest`);
|
|
1611
|
-
return createResolvedAuth({ Authorization: `Bearer ${await readFreshAccessToken(serverName, issuer, stored, context)}` });
|
|
1612
|
-
};
|
|
1613
|
-
//#endregion
|
|
1614
|
-
//#region src/auth/secret-file/create-file-secret-store.ts
|
|
1615
|
-
var toHostKey = (owner) => owner.domain ?? "default";
|
|
1616
|
-
/** Plain text in the 0600 config file under the mcpkit home, by server and host, read on every call so all running servers see each other's saves. */
|
|
1617
|
-
var createFileSecretStore = (env = process.env) => {
|
|
1618
|
-
return {
|
|
1619
|
-
get: async (owner, key) => readServerConfig(await loadConfig(env), owner)?.hosts?.[toHostKey(owner)]?.secrets?.[key],
|
|
1620
|
-
set: async (owner, key, value) => {
|
|
1621
|
-
const host = toHostKey(owner);
|
|
1622
|
-
await updateServerConfig(env, owner, (current) => ({
|
|
1623
|
-
...current,
|
|
1624
|
-
hosts: {
|
|
1625
|
-
...current.hosts,
|
|
1626
|
-
[host]: {
|
|
1627
|
-
...current.hosts?.[host],
|
|
1628
|
-
secrets: {
|
|
1629
|
-
...current.hosts?.[host]?.secrets,
|
|
1630
|
-
[key]: value
|
|
1631
|
-
}
|
|
1632
|
-
}
|
|
1633
|
-
}
|
|
1634
|
-
}));
|
|
1635
|
-
}
|
|
1636
|
-
};
|
|
1637
|
-
};
|
|
1638
|
-
//#endregion
|
|
1639
|
-
//#region src/auth/ui/resolve-cli-command.ts
|
|
1640
|
-
var resolveCliCommand = (action, domain) => {
|
|
1641
|
-
const args = action.args.map((arg) => {
|
|
1642
|
-
const filled = fillTemplate(arg, {
|
|
1643
|
-
domain: domain ?? "",
|
|
1644
|
-
webHost: domain ? toWebHost(domain) : ""
|
|
1645
|
-
});
|
|
1646
|
-
if (filled !== arg && !domain) throw new AuthError(`"${action.command}" needs a domain`);
|
|
1647
|
-
return filled;
|
|
1648
|
-
});
|
|
1649
|
-
return {
|
|
1650
|
-
command: action.command,
|
|
1651
|
-
args
|
|
1652
|
-
};
|
|
1653
|
-
};
|
|
1654
|
-
//#endregion
|
|
1655
|
-
//#region src/auth/ui/resolve-link-url.ts
|
|
1656
|
-
/** Undefined while the link needs a domain and there is none yet. */
|
|
1657
|
-
var resolveLinkUrl = (url, domain) => {
|
|
1658
|
-
if (readPlaceholders(url).some((name) => UI_DOMAIN_PLACEHOLDERS.includes(name)) && !domain) return;
|
|
1659
|
-
return fillTemplate(url, {
|
|
1660
|
-
domain: domain ?? "",
|
|
1661
|
-
webHost: domain ? toWebHost(domain) : ""
|
|
1662
|
-
});
|
|
1663
|
-
};
|
|
1664
|
-
//#endregion
|
|
1665
|
-
//#region src/auth/unauthorized-error.ts
|
|
1666
|
-
/** An upstream answered 401: the auth option that produced the credentials is rejected and the next one is tried. */
|
|
1667
|
-
var UnauthorizedError = class extends Error {};
|
|
1668
|
-
//#endregion
|
|
1669
|
-
//#region src/mapping/read-property.ts
|
|
1670
|
-
var readProperty = (source, key) => isJsonObject(source) ? source[key] : void 0;
|
|
1671
|
-
//#endregion
|
|
1672
|
-
//#region src/mapping/get-path.ts
|
|
1673
|
-
/**
|
|
1674
|
-
* Resolves `a.b.c` paths; a `name[]` segment maps the rest of the path over an array.
|
|
1675
|
-
* The return type is declared because TypeScript cannot infer it for this recursive function.
|
|
1676
|
-
*/
|
|
1677
|
-
var getPath = (source, path) => {
|
|
1678
|
-
const [head = "", ...rest] = path.split(".");
|
|
1679
|
-
const restPath = rest.join(".");
|
|
1680
|
-
if (!head.endsWith("[]")) {
|
|
1681
|
-
const value = readProperty(source, head);
|
|
1682
|
-
return restPath ? getPath(value, restPath) : value;
|
|
1683
|
-
}
|
|
1684
|
-
const list = readProperty(source, head.slice(0, -2));
|
|
1685
|
-
if (!Array.isArray(list)) return;
|
|
1686
|
-
return restPath ? list.map((item) => getPath(item, restPath)) : list;
|
|
1687
|
-
};
|
|
1688
|
-
//#endregion
|
|
1689
|
-
//#region src/mapping/pick-fields.ts
|
|
1690
|
-
var pickFields = (item, fieldMapping) => Object.fromEntries(Object.entries(fieldMapping).map(([outputName, path]) => [outputName, getPath(item, path) ?? null]));
|
|
1691
|
-
//#endregion
|
|
1692
|
-
//#region src/mapping/map-response.ts
|
|
1693
|
-
var mapResponse = (data, response = {}) => {
|
|
1694
|
-
const root = response.root ? getPath(data, response.root) : data;
|
|
1695
|
-
if (!response.fields) return root;
|
|
1696
|
-
const fieldMapping = toNameMapping(response.fields);
|
|
1697
|
-
return Array.isArray(root) ? root.map((item) => pickFields(item, fieldMapping)) : pickFields(root, fieldMapping);
|
|
1698
|
-
};
|
|
1699
|
-
//#endregion
|
|
1700
|
-
//#region src/execution/const.ts
|
|
1701
|
-
var DEFAULT_TIMEOUT_MS = 3e4;
|
|
1702
|
-
var NO_AUTH = {
|
|
1703
|
-
headers: {},
|
|
1704
|
-
query: {}
|
|
1705
|
-
};
|
|
1706
|
-
//#endregion
|
|
1707
|
-
//#region src/execution/json/set-json-path.ts
|
|
1708
|
-
/**
|
|
1709
|
-
* A copy of `target` with `value` at `segments`; numeric segments index arrays.
|
|
1710
|
-
* The return type is declared because TypeScript cannot infer it for this recursive function.
|
|
1711
|
-
*/
|
|
1712
|
-
var setJsonPath = (target, segments, value) => {
|
|
1713
|
-
const [head, ...rest] = segments;
|
|
1714
|
-
if (head === void 0) return value;
|
|
1715
|
-
if (/^\d+$/.test(head)) {
|
|
1716
|
-
const index = Number(head);
|
|
1717
|
-
const list = Array.isArray(target) ? [...target] : [];
|
|
1718
|
-
list[index] = setJsonPath(list[index], rest, value);
|
|
1719
|
-
return list;
|
|
1720
|
-
}
|
|
1721
|
-
const record = isJsonObject(target) ? target : {};
|
|
1722
|
-
return {
|
|
1723
|
-
...record,
|
|
1724
|
-
[head]: setJsonPath(record[head], rest, value)
|
|
1725
|
-
};
|
|
1726
|
-
};
|
|
1727
|
-
//#endregion
|
|
1728
|
-
//#region src/execution/json/expand-json-paths.ts
|
|
1729
|
-
/** `{ 'fields.summary': 'x' }` → `{ fields: { summary: 'x' } }`. */
|
|
1730
|
-
var expandJsonPaths = (values) => Object.entries(values).reduce((body, [path, value]) => setJsonPath(body, path.split("."), value), {});
|
|
1731
|
-
//#endregion
|
|
1732
|
-
//#region src/execution/request/collect-args.ts
|
|
1733
|
-
var collectArgs = (spec, args) => {
|
|
1734
|
-
if (!spec) return {};
|
|
1735
|
-
const entries = Object.entries(toNameMapping(spec)).filter(([, argName]) => args[argName] !== void 0).map(([outgoingKey, argName]) => [outgoingKey, args[argName]]);
|
|
1736
|
-
return Object.fromEntries(entries);
|
|
1737
|
-
};
|
|
1738
|
-
//#endregion
|
|
1739
|
-
//#region src/execution/request/build-body-payload.ts
|
|
1740
|
-
var buildBodyPayload = ({ body, bodyArg, fixedBody }, args) => {
|
|
1741
|
-
if (bodyArg !== void 0) return args[bodyArg];
|
|
1742
|
-
const values = {
|
|
1743
|
-
...fixedBody,
|
|
1744
|
-
...collectArgs(body, args)
|
|
1745
|
-
};
|
|
1746
|
-
return Object.keys(values).length > 0 ? expandJsonPaths(values) : void 0;
|
|
1747
|
-
};
|
|
1748
|
-
//#endregion
|
|
1749
|
-
//#region src/execution/request/is-uploaded-file.ts
|
|
1750
|
-
var isUploadedFile = (value) => typeof value === "object" && value !== null && "name" in value && "data" in value && value.data instanceof Uint8Array;
|
|
1751
|
-
//#endregion
|
|
1752
|
-
//#region src/execution/request/build-form-data.ts
|
|
1753
|
-
var toFieldValue = (value) => typeof value === "object" ? JSON.stringify(value) : String(value);
|
|
1754
|
-
var buildFormData = ({ body, fixedBody }, args) => {
|
|
1755
|
-
const form = new FormData();
|
|
1756
|
-
for (const [key, value] of Object.entries({
|
|
1757
|
-
...fixedBody,
|
|
1758
|
-
...collectArgs(body, args)
|
|
1759
|
-
})) {
|
|
1760
|
-
const files = [value].flat().filter(isUploadedFile);
|
|
1761
|
-
if (files.length > 0) {
|
|
1762
|
-
for (const file of files) form.append(key, new Blob([file.data]), file.name);
|
|
1763
|
-
continue;
|
|
1764
|
-
}
|
|
1765
|
-
form.append(key, toFieldValue(value));
|
|
1766
|
-
}
|
|
1767
|
-
return form;
|
|
1768
|
-
};
|
|
1769
|
-
//#endregion
|
|
1770
|
-
//#region src/execution/request/const.ts
|
|
1771
|
-
var JSON_CONTENT_TYPE = "application/json";
|
|
1772
|
-
var NO_HEADERS = {};
|
|
1773
|
-
//#endregion
|
|
1774
|
-
//#region src/execution/request/serialize-body.ts
|
|
1775
|
-
var serializeBody = (payload, contentType) => contentType.startsWith("text/") ? String(payload) : JSON.stringify(payload);
|
|
1776
|
-
//#endregion
|
|
1777
|
-
//#region src/execution/request/build-request-body.ts
|
|
1778
|
-
var buildRequestBody = (spec, args, contentType) => {
|
|
1779
|
-
if (contentType === "multipart/form-data") {
|
|
1780
|
-
const form = buildFormData(spec, args);
|
|
1781
|
-
return [...form.keys()].length > 0 ? {
|
|
1782
|
-
body: form,
|
|
1783
|
-
headers: NO_HEADERS
|
|
1784
|
-
} : void 0;
|
|
1785
|
-
}
|
|
1786
|
-
const payload = buildBodyPayload(spec, args);
|
|
1787
|
-
if (payload === void 0) return;
|
|
1788
|
-
if (isUploadedFile(payload)) return {
|
|
1789
|
-
body: new Blob([payload.data]),
|
|
1790
|
-
headers: { "Content-Type": contentType }
|
|
1791
|
-
};
|
|
1792
|
-
return {
|
|
1793
|
-
body: serializeBody(payload, contentType),
|
|
1794
|
-
headers: { "Content-Type": contentType }
|
|
1795
|
-
};
|
|
1796
|
-
};
|
|
1797
|
-
//#endregion
|
|
1798
|
-
//#region src/execution/request/build-request-url.ts
|
|
1799
|
-
var buildRequestUrl = (baseUrl, path, params, commaKeys = []) => {
|
|
1800
|
-
const url = new URL(baseUrl.replace(/\/$/, "") + path);
|
|
1801
|
-
for (const [key, value] of Object.entries(params)) {
|
|
1802
|
-
if (!Array.isArray(value) || commaKeys.includes(key)) {
|
|
1803
|
-
url.searchParams.set(key, String(value));
|
|
1804
|
-
continue;
|
|
1805
|
-
}
|
|
1806
|
-
for (const item of value) url.searchParams.append(key, String(item));
|
|
1807
|
-
}
|
|
1808
|
-
return url.toString();
|
|
1809
|
-
};
|
|
1810
|
-
//#endregion
|
|
1811
|
-
//#region src/execution/tool-error.ts
|
|
1812
|
-
var ToolError = class extends Error {};
|
|
1813
|
-
//#endregion
|
|
1814
|
-
//#region src/execution/request/fill-path.ts
|
|
1815
|
-
var fillPath = (template, args) => template.replace(/\{(\w+)\}/g, (_placeholder, name) => {
|
|
1816
|
-
const value = args[name];
|
|
1817
|
-
if (value === void 0) throw new ToolError(`path parameter "${name}" not provided`);
|
|
1818
|
-
return encodeURIComponent(String(value));
|
|
1819
|
-
});
|
|
1820
|
-
//#endregion
|
|
1821
|
-
//#region src/execution/request/build-request.ts
|
|
1822
|
-
/** Expects args already passed through prepareToolArgs and loadFileArgs. */
|
|
1823
|
-
var buildRequest = (manifest, tool, args, auth) => {
|
|
1824
|
-
const { method, path, query, fixedQuery, fixedHeaders, commaQuery, contentType = JSON_CONTENT_TYPE } = tool.request;
|
|
1825
|
-
const content = method === "GET" ? void 0 : buildRequestBody(tool.request, args, contentType);
|
|
1826
|
-
const params = {
|
|
1827
|
-
...fixedQuery,
|
|
1828
|
-
...collectArgs(query, args),
|
|
1829
|
-
...auth.query
|
|
1830
|
-
};
|
|
1831
|
-
return {
|
|
1832
|
-
url: buildRequestUrl(manifest.baseUrl, fillPath(path, args), params, commaQuery),
|
|
1833
|
-
method,
|
|
1834
|
-
headers: {
|
|
1835
|
-
...manifest.headers,
|
|
1836
|
-
...fixedHeaders,
|
|
1837
|
-
...auth.headers,
|
|
1838
|
-
...content?.headers
|
|
1839
|
-
},
|
|
1840
|
-
...content ? { body: content.body } : {}
|
|
1841
|
-
};
|
|
1842
|
-
};
|
|
1843
|
-
//#endregion
|
|
1844
|
-
//#region src/execution/response/read-api-error-message.ts
|
|
1845
|
-
var readApiErrorMessage = (body) => {
|
|
1846
|
-
if (isJsonObject(body) && "message" in body) return String(body.message);
|
|
1847
|
-
return body == null ? "" : String(body);
|
|
1848
|
-
};
|
|
1849
|
-
//#endregion
|
|
1850
|
-
//#region src/execution/response/read-response-body.ts
|
|
1851
|
-
var readResponseBody = async (response) => {
|
|
1852
|
-
const text = await response.text();
|
|
1853
|
-
if (!text) return null;
|
|
1854
|
-
if (!(response.headers.get("content-type")?.includes("json") ?? false)) return text;
|
|
1855
|
-
return JSON.parse(text);
|
|
1856
|
-
};
|
|
1857
|
-
//#endregion
|
|
1858
|
-
//#region src/execution/response/send-request.ts
|
|
1859
|
-
var sendRequest = (request, { fetchImpl, timeoutMs }) => fetchImpl(request.url, {
|
|
1860
|
-
method: request.method,
|
|
1861
|
-
headers: request.headers,
|
|
1862
|
-
body: request.body,
|
|
1863
|
-
signal: AbortSignal.timeout(timeoutMs)
|
|
1864
|
-
});
|
|
1865
|
-
//#endregion
|
|
1866
|
-
//#region src/execution/auth-fallback/reject-auth-attempt.ts
|
|
1867
|
-
var rejectAuthAttempt = (reason) => {
|
|
1868
|
-
return {
|
|
1869
|
-
accepted: false,
|
|
1870
|
-
reason
|
|
1871
|
-
};
|
|
1872
|
-
};
|
|
1873
|
-
//#endregion
|
|
1874
|
-
//#region src/execution/auth-fallback/attempt-auth.ts
|
|
1875
|
-
/** A candidate fails when its credentials are unavailable (unset env var, no stored token) or the API answers 401. */
|
|
1876
|
-
var attemptAuth = async (candidate, tool, args, context) => {
|
|
1877
|
-
let resolution;
|
|
1878
|
-
try {
|
|
1879
|
-
resolution = await candidate.resolve();
|
|
1880
|
-
} catch (error) {
|
|
1881
|
-
return rejectAuthAttempt(describeError(error));
|
|
1882
|
-
}
|
|
1883
|
-
const sentTool = resolution.manifest.tools.find((candidate) => candidate.name === tool.name) ?? tool;
|
|
1884
|
-
const response = await sendRequest(buildRequest(resolution.manifest, sentTool, args, resolution.auth), context);
|
|
1885
|
-
if (response.status === 401) return rejectAuthAttempt([`API answered 401`, readApiErrorMessage(await readResponseBody(response))].filter(Boolean).join(": "));
|
|
1886
|
-
await resolution.commit?.();
|
|
1887
|
-
return {
|
|
1888
|
-
accepted: true,
|
|
1889
|
-
response,
|
|
1890
|
-
tool: sentTool
|
|
1891
|
-
};
|
|
1892
|
-
};
|
|
1893
|
-
//#endregion
|
|
1894
|
-
//#region src/execution/auth-fallback/candidates/create-credential-form-candidate.ts
|
|
1895
|
-
var createCredentialFormCandidate = (manifest, domain, context) => {
|
|
1896
|
-
return {
|
|
1897
|
-
label: "credentials form",
|
|
1898
|
-
kind: "interactive",
|
|
1899
|
-
resolve: () => resolveCredentialForm(manifest, domain, context)
|
|
1900
|
-
};
|
|
1901
|
-
};
|
|
1902
|
-
//#endregion
|
|
1903
|
-
//#region src/execution/auth-fallback/candidates/create-missing-domain-candidate.ts
|
|
1904
|
-
var createMissingDomainCandidate = (manifest) => {
|
|
1905
|
-
const envHint = manifest.domain?.env ? `, set the ${manifest.domain.env} environment variable` : "";
|
|
1906
|
-
return {
|
|
1907
|
-
label: "domain",
|
|
1908
|
-
kind: "interactive",
|
|
1909
|
-
resolve: async () => {
|
|
1910
|
-
throw new AuthError(`no domain is set${envHint}`);
|
|
1911
|
-
}
|
|
1912
|
-
};
|
|
1913
|
-
};
|
|
1914
|
-
//#endregion
|
|
1915
|
-
//#region src/execution/auth-fallback/candidates/offers-credential-form.ts
|
|
1916
|
-
/** The form is shown when the user can enter a credential, or choose a domain to sign in to. */
|
|
1917
|
-
var offersCredentialForm = (manifest, context) => {
|
|
1918
|
-
const auth = manifest.auth ?? [];
|
|
1919
|
-
const takesCredentials = auth.some((entry) => !isInteractiveAuth(entry) && entry.type !== "none");
|
|
1920
|
-
const choosesSignInDomain = manifest.domain !== void 0 && auth.some(isInteractiveAuth);
|
|
1921
|
-
return context.requestCredentials !== void 0 && (takesCredentials || choosesSignInDomain);
|
|
1922
|
-
};
|
|
1923
|
-
//#endregion
|
|
1924
|
-
//#region src/execution/auth-fallback/candidates/to-sign-in-candidate.ts
|
|
1925
|
-
var toSignInCandidate = (auth, index, manifest, context) => {
|
|
1926
|
-
return {
|
|
1927
|
-
label: `auth[${index}] ${describeAuthSpec(auth)} sign-in`,
|
|
1928
|
-
kind: "interactive",
|
|
1929
|
-
resolve: async () => ({
|
|
1930
|
-
auth: await resolveSignedInAuth(manifest.name, auth, context),
|
|
1931
|
-
manifest
|
|
1932
|
-
})
|
|
1933
|
-
};
|
|
1934
|
-
};
|
|
1935
|
-
//#endregion
|
|
1936
|
-
//#region src/execution/auth-fallback/candidates/list-interactive-candidates.ts
|
|
1937
|
-
/** The credentials form when there is one to show, else the OAuth2 browser sign-ins. */
|
|
1938
|
-
var listInteractiveCandidates = (manifest, target, domain, context) => {
|
|
1939
|
-
if (offersCredentialForm(manifest, context)) return [createCredentialFormCandidate(manifest, domain, context)];
|
|
1940
|
-
if (!target) return [createMissingDomainCandidate(manifest)];
|
|
1941
|
-
return (target.auth ?? []).flatMap((auth, index) => isInteractiveAuth(auth) ? [toSignInCandidate(auth, index, target, context)] : []);
|
|
1942
|
-
};
|
|
1943
|
-
//#endregion
|
|
1944
|
-
//#region src/execution/auth-fallback/candidates/create-no-auth-candidate.ts
|
|
1945
|
-
var createNoAuthCandidate = (manifest) => {
|
|
1946
|
-
const resolution = {
|
|
1947
|
-
auth: NO_AUTH,
|
|
1948
|
-
manifest
|
|
1949
|
-
};
|
|
1950
|
-
return {
|
|
1951
|
-
label: "no auth",
|
|
1952
|
-
kind: "provided",
|
|
1953
|
-
resolve: async () => resolution
|
|
1954
|
-
};
|
|
1955
|
-
};
|
|
1956
|
-
//#endregion
|
|
1957
|
-
//#region src/execution/auth-fallback/candidates/create-stored-candidate.ts
|
|
1958
|
-
var createStoredCandidate = (manifest, context) => {
|
|
1959
|
-
return {
|
|
1960
|
-
label: "tokens.json",
|
|
1961
|
-
kind: "stored",
|
|
1962
|
-
resolve: async () => ({
|
|
1963
|
-
auth: await resolveStoredAuth(manifest.name, manifest.auth ?? [], context),
|
|
1964
|
-
manifest
|
|
1965
|
-
})
|
|
1966
|
-
};
|
|
1967
|
-
};
|
|
1968
|
-
//#endregion
|
|
1969
|
-
//#region src/execution/auth-fallback/candidates/to-fallback-candidate.ts
|
|
1970
|
-
var toFallbackCandidate = (auth, index, manifest, domain, context) => {
|
|
1971
|
-
return {
|
|
1972
|
-
label: `auth[${index}] ${describeAuthSpec(auth)}`,
|
|
1973
|
-
kind: "provided",
|
|
1974
|
-
resolve: async () => ({
|
|
1975
|
-
auth: await resolveFallbackAuth(auth, manifest, domain, context),
|
|
1976
|
-
manifest
|
|
1977
|
-
})
|
|
1978
|
-
};
|
|
1979
|
-
};
|
|
1980
|
-
//#endregion
|
|
1981
|
-
//#region src/execution/auth-fallback/candidates/list-provided-candidates.ts
|
|
1982
|
-
/** Auth that needs nothing from the user: the `tokens.json` token and fallbacks whose credentials are set or saved. */
|
|
1983
|
-
var listProvidedCandidates = (manifest, domain, context) => {
|
|
1984
|
-
const auth = manifest.auth ?? [];
|
|
1985
|
-
if (auth.length === 0) return [createNoAuthCandidate(manifest)];
|
|
1986
|
-
const stored = auth.some(isInteractiveAuth) ? [createStoredCandidate(manifest, context)] : [];
|
|
1987
|
-
const fallbacks = auth.flatMap((entry, index) => isInteractiveAuth(entry) ? [] : [toFallbackCandidate(entry, index, manifest, domain, context)]);
|
|
1988
|
-
return [...stored, ...fallbacks];
|
|
1989
|
-
};
|
|
1990
|
-
//#endregion
|
|
1991
|
-
//#region src/execution/auth-fallback/candidates/build-auth-candidates.ts
|
|
1992
|
-
/**
|
|
1993
|
-
* The `tokens.json` token first, then fallbacks whose credentials are set or saved,
|
|
1994
|
-
* and only when nothing else works the credentials form or the OAuth2 browser sign-in.
|
|
1995
|
-
*/
|
|
1996
|
-
var buildAuthCandidates = (manifest, domain, context) => {
|
|
1997
|
-
const target = manifest.domain && domain === void 0 ? void 0 : applyDomain(manifest, domain);
|
|
1998
|
-
return [...target ? listProvidedCandidates(target, domain, context) : [], ...listInteractiveCandidates(manifest, target, domain, context)];
|
|
1999
|
-
};
|
|
2000
|
-
//#endregion
|
|
2001
|
-
//#region src/execution/auth-fallback/candidates/preferred-auth-labels.ts
|
|
2002
|
-
/** Per server: the provided auth that last worked, tried right after `tokens.json` so rejected entries are not re-sent. */
|
|
2003
|
-
var preferredAuthLabels = /* @__PURE__ */ new Map();
|
|
2004
|
-
//#endregion
|
|
2005
|
-
//#region src/execution/auth-fallback/candidates/order-auth-candidates.ts
|
|
2006
|
-
/** `tokens.json` always goes first so a fresh sign-in wins; the last working provided auth comes right after it. */
|
|
2007
|
-
var orderAuthCandidates = (serverName, candidates) => {
|
|
2008
|
-
const preferredLabel = preferredAuthLabels.get(serverName);
|
|
2009
|
-
const isPreferred = (candidate) => candidate.kind === "provided" && candidate.label === preferredLabel;
|
|
2010
|
-
return [
|
|
2011
|
-
...candidates.filter((candidate) => candidate.kind === "stored"),
|
|
2012
|
-
...candidates.filter(isPreferred),
|
|
2013
|
-
...candidates.filter((candidate) => candidate.kind !== "stored" && !isPreferred(candidate))
|
|
2014
|
-
];
|
|
2015
|
-
};
|
|
2016
|
-
//#endregion
|
|
2017
|
-
//#region src/execution/auth-fallback/send-with-auth-fallback.ts
|
|
2018
|
-
/** Tries the server's auth candidates in order and keeps the one the API accepts. */
|
|
2019
|
-
var sendWithAuthFallback = async (manifest, tool, args, context) => {
|
|
2020
|
-
const domain = await resolveDomain(manifest, context);
|
|
2021
|
-
const candidates = orderAuthCandidates(manifest.name, buildAuthCandidates(manifest, domain, context));
|
|
2022
|
-
const failures = [];
|
|
2023
|
-
for (const candidate of candidates) {
|
|
2024
|
-
const attempt = await attemptAuth(candidate, tool, args, context);
|
|
2025
|
-
if (attempt.accepted) {
|
|
2026
|
-
if (candidate.kind === "provided") preferredAuthLabels.set(manifest.name, candidate.label);
|
|
2027
|
-
return attempt;
|
|
2028
|
-
}
|
|
2029
|
-
failures.push(`${candidate.label}: ${attempt.reason}`);
|
|
2030
|
-
}
|
|
2031
|
-
preferredAuthLabels.delete(manifest.name);
|
|
2032
|
-
throw new AuthError(`${manifest.name}: no auth option worked\n ${failures.join("\n ")}`);
|
|
2033
|
-
};
|
|
2034
|
-
//#endregion
|
|
2035
|
-
//#region src/execution/request/read-uploaded-files.ts
|
|
2036
|
-
var readUploadedFile = async (argName, path) => {
|
|
2037
|
-
if (typeof path !== "string") throw new ToolError(`Argument "${argName}" must be the path of a local file`);
|
|
2038
|
-
try {
|
|
2039
|
-
return {
|
|
2040
|
-
name: basename(path),
|
|
2041
|
-
data: new Uint8Array(await readFile(path))
|
|
2042
|
-
};
|
|
2043
|
-
} catch (error) {
|
|
2044
|
-
throw new ToolError(`Cannot read the file for "${argName}": ${error instanceof Error ? error.message : String(error)}`);
|
|
2045
|
-
}
|
|
2046
|
-
};
|
|
2047
|
-
var readUploadedFiles = (argName, value) => Array.isArray(value) ? Promise.all(value.map((path) => readUploadedFile(argName, path))) : readUploadedFile(argName, value);
|
|
2048
|
-
//#endregion
|
|
2049
|
-
//#region src/execution/request/load-file-args.ts
|
|
2050
|
-
/** An argument may hold one path or an array of paths. */
|
|
2051
|
-
var loadFileArgs = async ({ request }, args) => {
|
|
2052
|
-
const present = (request.fileArgs ?? []).filter((argName) => args[argName] !== void 0);
|
|
2053
|
-
const files = await Promise.all(present.map(async (argName) => [argName, await readUploadedFiles(argName, args[argName])]));
|
|
2054
|
-
return {
|
|
2055
|
-
...args,
|
|
2056
|
-
...Object.fromEntries(files)
|
|
2057
|
-
};
|
|
2058
|
-
};
|
|
2059
|
-
//#endregion
|
|
2060
|
-
//#region src/execution/request/apply-input-defaults.ts
|
|
2061
|
-
var applyInputDefaults = (input, args) => {
|
|
2062
|
-
const defaults = Object.entries(input.properties ?? {}).filter(([, schema]) => schema.default !== void 0).map(([name, schema]) => [name, schema.default]);
|
|
2063
|
-
return {
|
|
2064
|
-
...Object.fromEntries(defaults),
|
|
2065
|
-
...args
|
|
2066
|
-
};
|
|
2067
|
-
};
|
|
2068
|
-
//#endregion
|
|
2069
|
-
//#region src/execution/request/assert-required-args.ts
|
|
2070
|
-
var assertRequiredArgs = (input, args) => {
|
|
2071
|
-
const missing = (input.required ?? []).filter((name) => args[name] === void 0);
|
|
2072
|
-
if (missing.length) throw new ToolError(`missing required argument(s): ${missing.join(", ")}`);
|
|
2073
|
-
};
|
|
2074
|
-
//#endregion
|
|
2075
|
-
//#region src/execution/request/prepare-tool-args.ts
|
|
2076
|
-
var prepareToolArgs = (tool, rawArgs = {}) => {
|
|
2077
|
-
const args = applyInputDefaults(tool.input, rawArgs);
|
|
2078
|
-
assertRequiredArgs(tool.input, args);
|
|
2079
|
-
return args;
|
|
2080
|
-
};
|
|
2081
|
-
//#endregion
|
|
2082
|
-
//#region src/execution/response/save-response-file.ts
|
|
2083
|
-
var saveResponseFile = async (response, path) => {
|
|
2084
|
-
if (typeof path !== "string" || path === "") throw new ToolError("The save path must be a non-empty string");
|
|
2085
|
-
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
2086
|
-
try {
|
|
2087
|
-
await mkdir(dirname(path), { recursive: true });
|
|
2088
|
-
await writeFile(path, bytes);
|
|
2089
|
-
} catch (error) {
|
|
2090
|
-
throw new ToolError(`Cannot save the response to ${path}: ${error instanceof Error ? error.message : String(error)}`);
|
|
2091
|
-
}
|
|
2092
|
-
return {
|
|
2093
|
-
savedTo: path,
|
|
2094
|
-
bytes: bytes.byteLength,
|
|
2095
|
-
contentType: response.headers.get("content-type")
|
|
2096
|
-
};
|
|
2097
|
-
};
|
|
2098
|
-
//#endregion
|
|
2099
|
-
//#region src/execution/execute-tool.ts
|
|
2100
|
-
var executeTool = async (manifest, tool, rawArgs, { fetchImpl = fetch, timeoutMs = DEFAULT_TIMEOUT_MS, env = process.env, ...hooks } = {}) => {
|
|
2101
|
-
const args = await loadFileArgs(tool, prepareToolArgs(tool, rawArgs));
|
|
2102
|
-
const { response, tool: sentTool } = await sendWithAuthFallback(manifest, tool, args, {
|
|
2103
|
-
env,
|
|
2104
|
-
fetchImpl,
|
|
2105
|
-
timeoutMs,
|
|
2106
|
-
...hooks
|
|
2107
|
-
});
|
|
2108
|
-
const { saveToArg } = sentTool.request;
|
|
2109
|
-
if (saveToArg !== void 0 && response.ok) return saveResponseFile(response, args[saveToArg]);
|
|
2110
|
-
const body = await readResponseBody(response);
|
|
2111
|
-
if (!response.ok) throw new ToolError(`${manifest.name} API ${response.status}: ${readApiErrorMessage(body)}`.trim());
|
|
2112
|
-
return mapResponse(body, sentTool.response);
|
|
2113
|
-
};
|
|
2114
|
-
//#endregion
|
|
2115
|
-
//#region src/execution/upstream/name-upstream-tool.ts
|
|
2116
|
-
var CATALOG_NAME_PATTERN = /^[a-z][a-z0-9_]*(:[a-z][a-z0-9_]*){2,}$/;
|
|
2117
|
-
/**
|
|
2118
|
-
* The catalog name `rules` give an upstream tool, from the first rule whose `match` finds the tool name, or undefined
|
|
2119
|
-
* when none does. A name that is not `<group>:<resource>:<action>` in lowercase snake case is an error in the
|
|
2120
|
-
* manifest, never silently replaced.
|
|
2121
|
-
*/
|
|
2122
|
-
var nameUpstreamTool = (rules, upstreamName) => {
|
|
2123
|
-
for (const rule of rules ?? []) {
|
|
2124
|
-
const pattern = new RegExp(rule.match);
|
|
2125
|
-
if (!pattern.test(upstreamName)) continue;
|
|
2126
|
-
const name = upstreamName.replace(pattern, rule.name);
|
|
2127
|
-
if (!CATALOG_NAME_PATTERN.test(name)) throw new Error(`naming rule "${rule.match}" turned "${upstreamName}" into "${name}", which is not <group>:<resource>:<action>`);
|
|
2128
|
-
return name;
|
|
2129
|
-
}
|
|
2130
|
-
};
|
|
2131
|
-
//#endregion
|
|
2132
|
-
//#region src/execution/upstream/request-forwarded-credentials.ts
|
|
2133
|
-
var FORWARDED_OPTION_INDEX = 0;
|
|
2134
|
-
/** Asks the user in the credentials form for `names`, the credentials of a stdio upstream that nothing provided. */
|
|
2135
|
-
var requestForwardedCredentials = async (manifest, upstream, names, requestCredentials) => {
|
|
2136
|
-
const texts = buildUiTexts(manifest);
|
|
2137
|
-
const { request, response } = await requestCredentialsOnce(manifest.name, async () => {
|
|
2138
|
-
const fields = names.map((name) => toCredentialField(name, name, true, texts, upstream.ui?.inputs?.[name]));
|
|
2139
|
-
const option = {
|
|
2140
|
-
index: FORWARDED_OPTION_INDEX,
|
|
2141
|
-
label: texts.credentialLegend,
|
|
2142
|
-
fields,
|
|
2143
|
-
actions: toOptionActions(upstream.ui, manifest.name, fields.length)
|
|
2144
|
-
};
|
|
2145
|
-
return {
|
|
2146
|
-
serverName: manifest.name,
|
|
2147
|
-
texts,
|
|
2148
|
-
options: [option],
|
|
2149
|
-
signIn: false
|
|
2150
|
-
};
|
|
2151
|
-
}, requestCredentials);
|
|
2152
|
-
const errors = validateCredentialResponse(request, response);
|
|
2153
|
-
if (errors.length > 0 || response.method !== "token") throw new AuthError(`${manifest.name}: invalid credentials form answer: ${errors.join("; ")}`);
|
|
2154
|
-
return trimValues(response.values);
|
|
2155
|
-
};
|
|
2156
|
-
//#endregion
|
|
2157
|
-
//#region src/execution/upstream/ask-for-missing-credentials.ts
|
|
2158
|
-
/** The values the user enters for `missing`; without a form to ask in, the missing names are the error. */
|
|
2159
|
-
var askForMissingCredentials = (manifest, upstream, missing, requestCredentials) => {
|
|
2160
|
-
if (!requestCredentials) throw new AuthError(`${manifest.name}: missing credential, set ${missing.join(", ")} in the client's env for mcpkit`);
|
|
2161
|
-
return requestForwardedCredentials(manifest, upstream, missing, requestCredentials);
|
|
2162
|
-
};
|
|
2163
|
-
//#endregion
|
|
2164
|
-
//#region src/execution/upstream/read-forwarded-env.ts
|
|
2165
|
-
/**
|
|
2166
|
-
* Each forwarded credential from its env var, else from the secret store; an optional one is left out when unset.
|
|
2167
|
-
* A required one found nowhere is asked for in the credentials form when the caller has one, and `commit` saves
|
|
2168
|
-
* what was entered once the upstream has started with it.
|
|
2169
|
-
*/
|
|
2170
|
-
var readForwardedEnv = async (manifest, upstream, domain, context) => {
|
|
2171
|
-
const { forwardEnv = [], optionalEnv = [] } = upstream;
|
|
2172
|
-
const owner = {
|
|
2173
|
-
name: manifest.name,
|
|
2174
|
-
category: manifest.category,
|
|
2175
|
-
domain
|
|
2176
|
-
};
|
|
2177
|
-
const read = async (name) => [name, context.env[name] || await context.secretStore?.get(owner, name)];
|
|
2178
|
-
const required = await Promise.all(forwardEnv.map(read));
|
|
2179
|
-
const missing = required.filter(([, value]) => !value).map(([name]) => name);
|
|
2180
|
-
const entered = missing.length === 0 ? {} : await askForMissingCredentials(manifest, upstream, missing, context.requestCredentials);
|
|
2181
|
-
const optional = (await Promise.all(optionalEnv.map(read))).filter(([, value]) => value);
|
|
2182
|
-
const found = [...required, ...optional].filter(([, value]) => value);
|
|
2183
|
-
const env = {
|
|
2184
|
-
...Object.fromEntries(found.map(([name, value]) => [name, value ?? ""])),
|
|
2185
|
-
...entered
|
|
2186
|
-
};
|
|
2187
|
-
const commit = () => saveCredentials(owner, entered, context.secretStore);
|
|
2188
|
-
return {
|
|
2189
|
-
env,
|
|
2190
|
-
commit
|
|
2191
|
-
};
|
|
2192
|
-
};
|
|
2193
|
-
//#endregion
|
|
2194
|
-
//#region src/execution/upstream/with-upstream-access.ts
|
|
2195
|
-
/**
|
|
2196
|
-
* Runs `run` with the access of an `upstream` manifest. A stdio upstream gets its forwarded credentials, asked for in the credentials form when missing and saved once `run` succeeded; an HTTP one
|
|
2197
|
-
* tries the manifest's auth options in order like an API call does, moving on when `run` throws UnauthorizedError.
|
|
2198
|
-
*/
|
|
2199
|
-
var withUpstreamAccess = async (manifest, run, { fetchImpl = fetch, timeoutMs = DEFAULT_TIMEOUT_MS, env = process.env, ...hooks } = {}) => {
|
|
2200
|
-
const context = {
|
|
2201
|
-
env,
|
|
2202
|
-
fetchImpl,
|
|
2203
|
-
timeoutMs,
|
|
2204
|
-
...hooks
|
|
2205
|
-
};
|
|
2206
|
-
const domain = await resolveDomain(manifest, context);
|
|
2207
|
-
const upstream = applyDomain(manifest, domain).upstream;
|
|
2208
|
-
if (!upstream) throw new AuthError(`${manifest.name} has no upstream`);
|
|
2209
|
-
if (upstream.type === "stdio") {
|
|
2210
|
-
const forwarded = await readForwardedEnv(manifest, upstream, domain, context);
|
|
2211
|
-
const result = await run({
|
|
2212
|
-
upstream,
|
|
2213
|
-
headers: {},
|
|
2214
|
-
env: forwarded.env
|
|
2215
|
-
});
|
|
2216
|
-
await forwarded.commit();
|
|
2217
|
-
return result;
|
|
2218
|
-
}
|
|
2219
|
-
const failures = [];
|
|
2220
|
-
for (const candidate of orderAuthCandidates(manifest.name, buildAuthCandidates(manifest, domain, context))) try {
|
|
2221
|
-
const resolution = await candidate.resolve();
|
|
2222
|
-
const result = await run({
|
|
2223
|
-
upstream,
|
|
2224
|
-
headers: resolution.auth.headers,
|
|
2225
|
-
env: {}
|
|
2226
|
-
});
|
|
2227
|
-
await resolution.commit?.();
|
|
2228
|
-
if (candidate.kind === "provided") preferredAuthLabels.set(manifest.name, candidate.label);
|
|
2229
|
-
return result;
|
|
2230
|
-
} catch (error) {
|
|
2231
|
-
if (!(error instanceof AuthError || error instanceof UnauthorizedError)) throw error;
|
|
2232
|
-
failures.push(`${candidate.label}: ${describeError(error)}`);
|
|
2233
|
-
}
|
|
2234
|
-
preferredAuthLabels.delete(manifest.name);
|
|
2235
|
-
throw new AuthError(`${manifest.name}: no auth option worked\n ${failures.join("\n ")}`);
|
|
2236
|
-
};
|
|
2237
|
-
//#endregion
|
|
2238
|
-
//#region src/sdk/define-server.ts
|
|
2239
|
-
var defineServer = (manifest) => manifest;
|
|
2240
|
-
//#endregion
|
|
2241
|
-
//#region src/sdk/define-tool.ts
|
|
2242
|
-
var defineTool = (tool) => tool;
|
|
2243
|
-
//#endregion
|
|
2244
|
-
//#region src/sdk/define-ui.ts
|
|
2245
|
-
var defineUI = (ui) => ui;
|
|
2246
|
-
//#endregion
|
|
2247
|
-
//#region src/sdk/const.ts
|
|
2248
|
-
/** Symbol keys are dropped by JSON.stringify, so the marker never reaches a manifest. */
|
|
2249
|
-
var OPTIONAL_MARKER = Symbol("optional");
|
|
2250
|
-
//#endregion
|
|
2251
|
-
//#region src/sdk/is-required-param.ts
|
|
2252
|
-
var isRequiredParam = (param) => !param[OPTIONAL_MARKER] && param.default === void 0;
|
|
2253
|
-
//#endregion
|
|
2254
|
-
//#region src/sdk/strip-optional-marker.ts
|
|
2255
|
-
var stripOptionalMarker = (param) => {
|
|
2256
|
-
const { [OPTIONAL_MARKER]: _marker, ...rest } = param;
|
|
2257
|
-
return rest;
|
|
2258
|
-
};
|
|
2259
|
-
//#endregion
|
|
2260
|
-
//#region src/sdk/input.ts
|
|
2261
|
-
/** Builds an object input schema; `required` is derived from the params. */
|
|
2262
|
-
var input = (params = {}) => {
|
|
2263
|
-
const entries = Object.entries(params);
|
|
2264
|
-
const required = entries.filter(([, param]) => isRequiredParam(param)).map(([name]) => name);
|
|
2265
|
-
return {
|
|
2266
|
-
type: "object",
|
|
2267
|
-
properties: Object.fromEntries(entries.map(([name, param]) => [name, stripOptionalMarker(param)])),
|
|
2268
|
-
...required.length > 0 ? { required } : {}
|
|
2269
|
-
};
|
|
2270
|
-
};
|
|
2271
|
-
//#endregion
|
|
2272
|
-
//#region src/sdk/optional.ts
|
|
2273
|
-
/** Marks a param as not required. Params with a default are optional implicitly. */
|
|
2274
|
-
var optional = (param) => {
|
|
2275
|
-
return {
|
|
2276
|
-
...param,
|
|
2277
|
-
[OPTIONAL_MARKER]: true
|
|
2278
|
-
};
|
|
2279
|
-
};
|
|
2280
|
-
//#endregion
|
|
2281
|
-
//#region src/sdk/with-description.ts
|
|
2282
|
-
var withDescription = (description) => description ? { description } : {};
|
|
2283
|
-
//#endregion
|
|
2284
|
-
//#region src/sdk/params/array.ts
|
|
2285
|
-
var array = (items, description) => {
|
|
2286
|
-
return {
|
|
2287
|
-
type: "array",
|
|
2288
|
-
items,
|
|
2289
|
-
...withDescription(description)
|
|
2290
|
-
};
|
|
2291
|
-
};
|
|
2292
|
-
//#endregion
|
|
2293
|
-
//#region src/sdk/params/boolean.ts
|
|
2294
|
-
var boolean = (description, options = {}) => {
|
|
2295
|
-
return {
|
|
2296
|
-
type: "boolean",
|
|
2297
|
-
...withDescription(description),
|
|
2298
|
-
...options
|
|
2299
|
-
};
|
|
2300
|
-
};
|
|
2301
|
-
//#endregion
|
|
2302
|
-
//#region src/sdk/params/number.ts
|
|
2303
|
-
var number = (description, options = {}) => {
|
|
2304
|
-
return {
|
|
2305
|
-
type: "number",
|
|
2306
|
-
...withDescription(description),
|
|
2307
|
-
...options
|
|
2308
|
-
};
|
|
2309
|
-
};
|
|
2310
|
-
//#endregion
|
|
2311
|
-
//#region src/sdk/params/string.ts
|
|
2312
|
-
var string = (description, options = {}) => {
|
|
2313
|
-
return {
|
|
2314
|
-
type: "string",
|
|
2315
|
-
...withDescription(description),
|
|
2316
|
-
...options
|
|
2317
|
-
};
|
|
2318
|
-
};
|
|
2319
|
-
//#endregion
|
|
2320
|
-
//#region src/sdk/params/one-of.ts
|
|
2321
|
-
var oneOf = (values, description, options = {}) => string(description, {
|
|
2322
|
-
enum: values,
|
|
2323
|
-
...options
|
|
2324
|
-
});
|
|
2325
|
-
//#endregion
|
|
2326
|
-
//#region src/versions/parse-version.ts
|
|
2327
|
-
var parseVersion = (version) => version.split(".").map((part) => Number.parseInt(part, 10) || 0);
|
|
2328
|
-
//#endregion
|
|
2329
|
-
//#region src/versions/compare-versions.ts
|
|
2330
|
-
var compareVersions = (left, right) => {
|
|
2331
|
-
const leftParts = parseVersion(left);
|
|
2332
|
-
const rightParts = parseVersion(right);
|
|
2333
|
-
const length = Math.max(leftParts.length, rightParts.length);
|
|
2334
|
-
for (let index = 0; index < length; index++) {
|
|
2335
|
-
const difference = (leftParts[index] ?? 0) - (rightParts[index] ?? 0);
|
|
2336
|
-
if (difference !== 0) return difference;
|
|
2337
|
-
}
|
|
2338
|
-
return 0;
|
|
2339
|
-
};
|
|
2340
|
-
//#endregion
|
|
2341
|
-
export { AuthError, CREDENTIALS_FORM_API, CREDENTIALS_FORM_SESSION_HEADER, CREDENTIALS_REQUEST_ELEMENT_ID, DEFAULT_UI_TEXTS, FORM_WINDOW_BINDINGS, SERVER_NAME_PATTERN, TOOL_NAME_PATTERN, ToolError, UnauthorizedError, applyDomain, array, boolean, buildRequest, compareVersions, createFileSecretStore, defineServer, defineTool, defineUI, describeAuth, describeAuthSpec, describeError, executeTool, fillTemplate, getPath, input, isDomainValue, isInteractiveAuth, isJsonObject, isMissingFileError, isValidCredentialResponse, isValidManifest, listAuthEnvNames, mapResponse, nameUpstreamTool, number, oneOf, optional, prepareToolArgs, resolveCliCommand, resolveHomeDir, resolveLinkUrl, resolveStaticAuth, signIn, string, toNameMapping, validateCredentialResponse, validateManifest, withUpstreamAccess };
|