hmcp-gateway 0.0.2 → 0.2.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.
Files changed (114) hide show
  1. package/LICENSE +77 -0
  2. package/README.md +135 -9
  3. package/bin/hmcp-gateway.js +20 -0
  4. package/catalog/atlassian.yaml +41 -0
  5. package/catalog/brave-search.yaml +57 -0
  6. package/catalog/context7.yaml +42 -0
  7. package/catalog/fetch.yaml +37 -0
  8. package/catalog/figma.yaml +48 -0
  9. package/catalog/filesystem.yaml +48 -0
  10. package/catalog/git.yaml +48 -0
  11. package/catalog/github.yaml +103 -0
  12. package/catalog/huggingface.yaml +59 -0
  13. package/catalog/linear.yaml +47 -0
  14. package/catalog/memory.yaml +47 -0
  15. package/catalog/notion.yaml +41 -0
  16. package/catalog/playwright.yaml +38 -0
  17. package/catalog/postgres.yaml +66 -0
  18. package/catalog/sentry.yaml +39 -0
  19. package/catalog/sequential-thinking.yaml +29 -0
  20. package/catalog/stripe.yaml +41 -0
  21. package/catalog/supabase.yaml +45 -0
  22. package/catalog/time.yaml +49 -0
  23. package/dist/adopt-cli.d.ts +355 -0
  24. package/dist/adopt-cli.js +1885 -0
  25. package/dist/adopt-emit.d.ts +64 -0
  26. package/dist/adopt-emit.js +248 -0
  27. package/dist/adopt-plan.d.ts +108 -0
  28. package/dist/adopt-plan.js +501 -0
  29. package/dist/catalog.d.ts +140 -0
  30. package/dist/catalog.js +250 -0
  31. package/dist/classify.d.ts +23 -0
  32. package/dist/classify.js +47 -0
  33. package/dist/cli.d.ts +2 -0
  34. package/dist/cli.js +656 -0
  35. package/dist/client-allow.d.ts +42 -0
  36. package/dist/client-allow.js +95 -0
  37. package/dist/client-config.d.ts +263 -0
  38. package/dist/client-config.js +995 -0
  39. package/dist/config-source.d.ts +106 -0
  40. package/dist/config-source.js +156 -0
  41. package/dist/config.d.ts +159 -0
  42. package/dist/config.js +330 -0
  43. package/dist/connect-client.d.ts +51 -0
  44. package/dist/connect-client.js +299 -0
  45. package/dist/contracts.d.ts +251 -0
  46. package/dist/contracts.js +9 -0
  47. package/dist/credential.d.ts +63 -0
  48. package/dist/credential.js +136 -0
  49. package/dist/desktop-extensions.d.ts +53 -0
  50. package/dist/desktop-extensions.js +126 -0
  51. package/dist/draft.d.ts +71 -0
  52. package/dist/draft.js +596 -0
  53. package/dist/exposure-cli.d.ts +28 -0
  54. package/dist/exposure-cli.js +119 -0
  55. package/dist/gateway.d.ts +766 -0
  56. package/dist/gateway.js +2122 -0
  57. package/dist/github-doors.d.ts +162 -0
  58. package/dist/github-doors.js +780 -0
  59. package/dist/guard-install.d.ts +109 -0
  60. package/dist/guard-install.js +396 -0
  61. package/dist/guard.d.ts +265 -0
  62. package/dist/guard.js +975 -0
  63. package/dist/import-client.d.ts +184 -0
  64. package/dist/import-client.js +578 -0
  65. package/dist/index.d.ts +31 -0
  66. package/dist/index.js +31 -0
  67. package/dist/notify.d.ts +44 -0
  68. package/dist/notify.js +93 -0
  69. package/dist/oauth.d.ts +139 -0
  70. package/dist/oauth.js +641 -0
  71. package/dist/observe.d.ts +10 -0
  72. package/dist/observe.js +26 -0
  73. package/dist/open.d.ts +24 -0
  74. package/dist/open.js +31 -0
  75. package/dist/packs.d.ts +119 -0
  76. package/dist/packs.js +131 -0
  77. package/dist/pin-cli.d.ts +28 -0
  78. package/dist/pin-cli.js +103 -0
  79. package/dist/probe-upstream.d.ts +31 -0
  80. package/dist/probe-upstream.js +377 -0
  81. package/dist/registry-map.d.ts +39 -0
  82. package/dist/registry-map.js +390 -0
  83. package/dist/rule-cli.d.ts +51 -0
  84. package/dist/rule-cli.js +412 -0
  85. package/dist/serve-http.d.ts +67 -0
  86. package/dist/serve-http.js +478 -0
  87. package/dist/snippet.d.ts +20 -0
  88. package/dist/snippet.js +826 -0
  89. package/dist/status-cli.d.ts +61 -0
  90. package/dist/status-cli.js +195 -0
  91. package/dist/suggest-cli.d.ts +43 -0
  92. package/dist/suggest-cli.js +279 -0
  93. package/dist/toml-edit.d.ts +43 -0
  94. package/dist/toml-edit.js +363 -0
  95. package/dist/toolname.d.ts +47 -0
  96. package/dist/toolname.js +149 -0
  97. package/dist/upstream-errors.d.ts +54 -0
  98. package/dist/upstream-errors.js +330 -0
  99. package/dist/upstream.d.ts +128 -0
  100. package/dist/upstream.js +413 -0
  101. package/dist/version.d.ts +10 -0
  102. package/dist/version.js +11 -0
  103. package/package.json +51 -6
  104. package/packs/brave-search.yaml +20 -0
  105. package/packs/context7.yaml +13 -0
  106. package/packs/fetch.yaml +14 -0
  107. package/packs/filesystem.yaml +79 -0
  108. package/packs/git.yaml +29 -0
  109. package/packs/github.yaml +47 -0
  110. package/packs/huggingface.yaml +16 -0
  111. package/packs/memory.yaml +23 -0
  112. package/packs/playwright.yaml +41 -0
  113. package/packs/sequential-thinking.yaml +13 -0
  114. package/packs/time.yaml +14 -0
@@ -0,0 +1,71 @@
1
+ import type { CatalogEntry, CatalogField, DraftServer, FieldValues, MaterializedDraft } from "./contracts.js";
2
+ /** The value key a sign-in's locked-key name travels under (set by the UI). */
3
+ export declare const SIGN_IN_VALUE = "__signin";
4
+ /**
5
+ * The value key that says "use this saved locked key for this field":
6
+ * `__saved.<field id>` set to the key's name. The person picks it; it is
7
+ * never inferred for a server from the public list, a paste or the form.
8
+ */
9
+ export declare const SAVED_KEY_PREFIX = "__saved.";
10
+ /**
11
+ * The value key that says "this address is on my own computer or network,
12
+ * test it": needed before a server from the public list or a paste is
13
+ * tested at a private or loopback address, because testing lifts the
14
+ * private-address protection for that one host.
15
+ */
16
+ export declare const LOCAL_OK_VALUE = "__local_ok";
17
+ /** Words for a stranger's draft that points at this computer or the local network. */
18
+ export declare function localAddressWarning(kind: AddressKind): string | null;
19
+ /** A catalog entry's variant as a draft the UI can render. */
20
+ export declare function draftFromCatalog(entry: CatalogEntry, variantId?: string): DraftServer;
21
+ export interface MaterializeOptions {
22
+ /** Upstream names already in the gateway, to pick a free one. */
23
+ takenNames?: string[];
24
+ /** Override the suggested upstream name. */
25
+ name?: string;
26
+ /** Secret names that exist already (so a reused key is not re-created). */
27
+ existingSecrets?: string[];
28
+ /**
29
+ * The label each existing key was saved with. When given, a catalog
30
+ * server only reuses a saved key whose label is the field's own.
31
+ */
32
+ existingSecretLabels?: Record<string, string | undefined>;
33
+ /** Absolute paths for runtimes, from the machine check ("npx" -> "/usr/local/bin/npx"). */
34
+ commandPaths?: Record<string, string>;
35
+ /**
36
+ * Where a field's format check comes from. A draft sent by a browser is
37
+ * not trusted to carry a regular expression (one built to backtrack would
38
+ * freeze the console), so the console passes the catalog's own checks
39
+ * here. Without it, only a catalog draft's own `validate` is used.
40
+ */
41
+ validateFor?: (fieldId: string) => CatalogField["validate"] | undefined;
42
+ }
43
+ export declare function materializeDraft(draft: DraftServer, values: FieldValues, options?: MaterializeOptions): MaterializedDraft;
44
+ /** The address with any name, password or key-named query value taken out, for messages. */
45
+ export declare function withoutKeys(url: string): string;
46
+ /**
47
+ * Whether an address carries a key where it can't be locked: a name and
48
+ * password before the host, or a query parameter named like a key.
49
+ */
50
+ export declare function addressHoldsKey(url: string): "userinfo" | "query" | "path" | null;
51
+ /** Lower-case, digits and underscores: what gateway.yaml accepts as an upstream name. */
52
+ export declare function safeName(raw: string): string;
53
+ /** The locked-key name a field's value is stored under: "github.token". */
54
+ export declare function secretNameFor(upstreamName: string, field: CatalogField): string;
55
+ /** The locked-key name a sign-in is stored under; the UI derives the same one. */
56
+ export declare function signInSecretName(upstreamName: string): string;
57
+ /** Why a file can't be kept at this place, in plain words, or null when it can. */
58
+ export declare function filePlaceProblem(path: string): string | null;
59
+ /**
60
+ * Whether the egress guard refuses this host without its private-address
61
+ * protection loosened. The same test as adopt-plan.ts `isLocalAddress`, which
62
+ * is not exported: `localhost` counts because it resolves to loopback.
63
+ */
64
+ export declare function isLocalAddress(hostname: string): boolean;
65
+ /**
66
+ * Where an address points, in the words the add flow needs: this computer,
67
+ * the local network, the link-local range that holds cloud metadata services
68
+ * (refused outright for a server we didn't vet), or anywhere else.
69
+ */
70
+ export type AddressKind = "loopback" | "private" | "link-local" | "public";
71
+ export declare function addressKind(hostname: string): AddressKind;
package/dist/draft.js ADDED
@@ -0,0 +1,596 @@
1
+ /**
2
+ * Turning a draft plus what the user typed into a gateway.yaml upstream.
3
+ *
4
+ * The catalog, the public list, pasted instructions and the hand-written form
5
+ * all end here, so the rules that keep a key out of gateway.yaml are applied
6
+ * once:
7
+ *
8
+ * - a secret field only ever becomes `{ secret: <name> }`; its value goes to
9
+ * `secretsToCreate`, to be written to the locked-keys file;
10
+ * - a secret field inlined into a string is refused, not substituted;
11
+ * - a sign-in (`oauth: true`) refers to a locked key that sign-in creates, so
12
+ * it is listed in `secretsReferenced` and never created here.
13
+ */
14
+ import { accessSync, constants, statSync } from "node:fs";
15
+ import { homedir } from "node:os";
16
+ import { dirname, join } from "node:path";
17
+ import { classifyAddress, embeddedIPv4, isIpLiteral, SECRET_NAME, SECRET_VALUE_PATTERNS } from "hmcp-core";
18
+ import { UpstreamSchema } from "./config.js";
19
+ /** The value key a sign-in's locked-key name travels under (set by the UI). */
20
+ export const SIGN_IN_VALUE = "__signin";
21
+ /**
22
+ * The value key that says "use this saved locked key for this field":
23
+ * `__saved.<field id>` set to the key's name. The person picks it; it is
24
+ * never inferred for a server from the public list, a paste or the form.
25
+ */
26
+ export const SAVED_KEY_PREFIX = "__saved.";
27
+ /**
28
+ * The value key that says "this address is on my own computer or network,
29
+ * test it": needed before a server from the public list or a paste is
30
+ * tested at a private or loopback address, because testing lifts the
31
+ * private-address protection for that one host.
32
+ */
33
+ export const LOCAL_OK_VALUE = "__local_ok";
34
+ /** Words for a stranger's draft that points at this computer or the local network. */
35
+ export function localAddressWarning(kind) {
36
+ if (kind === "loopback") {
37
+ return "This connects to a program on this computer, not to a website. Only go on if you started that program yourself.";
38
+ }
39
+ if (kind === "private") {
40
+ return "This connects to a device on your own network, such as a router or another computer, not to a website. Only go on if you know what is there.";
41
+ }
42
+ if (kind === "link-local") {
43
+ return "This address is reserved for this computer's own network settings and for cloud services' private data, so it can't be used for a server.";
44
+ }
45
+ return null;
46
+ }
47
+ /** A catalog entry's variant as a draft the UI can render. */
48
+ export function draftFromCatalog(entry, variantId) {
49
+ const variant = variantId === undefined ? entry.variants[0] : entry.variants.find((v) => v.id === variantId);
50
+ if (!variant) {
51
+ throw new Error(`"${entry.name}" has no option called "${variantId}"`);
52
+ }
53
+ const used = new Set(variant.fields ?? []);
54
+ const fields = entry.fields.filter((f) => used.has(f.id));
55
+ const warnings = [];
56
+ if (!entry.publisher.official) {
57
+ warnings.push(`This server is made by ${entry.publisher.name}, not by the service it connects to.`);
58
+ }
59
+ if (variant.launch.transport === "http") {
60
+ const host = hostOf(variant.launch.url.replace(/\{\{[^}]*\}\}/g, ""));
61
+ if (host && isLocalAddress(host.hostname)) {
62
+ warnings.push("This connects to a program on this computer. Saving it will ask you to allow connections to this computer's own addresses.");
63
+ }
64
+ }
65
+ // A path-bounded pack is only meaningful when the variant has the folders it is bounded to.
66
+ const packFits = !entry.pack_within_field || used.has(entry.pack_within_field);
67
+ return {
68
+ source: { kind: "catalog", id: entry.id, variant: variant.id },
69
+ name: safeName(entry.id),
70
+ displayName: entry.name,
71
+ launch: variant.launch,
72
+ fields,
73
+ guide: entry.guide,
74
+ requires: variant.requires ?? entry.requires ?? [],
75
+ ...(entry.pack && packFits ? { pack: entry.pack } : {}),
76
+ ...(entry.pack && packFits && entry.pack_within_field ? { pack_within_field: entry.pack_within_field } : {}),
77
+ warnings
78
+ };
79
+ }
80
+ /** Longest pattern and value a format check runs on: keys and ids are short. */
81
+ const MAX_PATTERN = 300;
82
+ const MAX_CHECKED_VALUE = 4_000;
83
+ const isBlank = (v) => v === undefined || (typeof v === "string" && v.trim() === "") || (Array.isArray(v) && v.length === 0);
84
+ export function materializeDraft(draft, values, options = {}) {
85
+ const problems = {};
86
+ const fields = new Map(draft.fields.map((f) => [f.id, f]));
87
+ const taken = new Set(options.takenNames ?? []);
88
+ /* ------------------------------------------------------------ the name */
89
+ let name;
90
+ if (options.name !== undefined) {
91
+ name = options.name.trim();
92
+ if (!/^[a-z0-9_]+$/.test(name))
93
+ problems["name"] = "Use lower-case letters, digits and underscores.";
94
+ else if (taken.has(name))
95
+ problems["name"] = `Another server is already called “${name}”.`;
96
+ }
97
+ else {
98
+ name = uniqueName(safeName(draft.name), taken);
99
+ }
100
+ /* ------------------------------------------------------------ the values */
101
+ const valueOf = (f) => {
102
+ const typed = values[f.id];
103
+ if (typed !== undefined)
104
+ return typed;
105
+ return f.default;
106
+ };
107
+ /*
108
+ * Signing in, either because the template says so or because the person
109
+ * switched an http draft to sign-in (the UI sends `__signin`). A sign-in
110
+ * replaces any Authorization header: a request carries one credential, and
111
+ * a key field that only fed that header is no longer asked for.
112
+ */
113
+ const signIn = draft.launch.transport === "http" && (draft.launch.oauth === true || typeof values[SIGN_IN_VALUE] === "string");
114
+ const isAuthHeader = (h) => h.toLowerCase() === "authorization";
115
+ const launchHeaders = draft.launch.transport === "http" && signIn
116
+ ? Object.fromEntries(Object.entries(draft.launch.headers ?? {}).filter(([h]) => !isAuthHeader(h)))
117
+ : draft.launch.transport === "http"
118
+ ? draft.launch.headers
119
+ : undefined;
120
+ const dropped = new Set();
121
+ if (draft.launch.transport === "http" && signIn) {
122
+ for (const [h, v] of Object.entries(draft.launch.headers ?? {}))
123
+ if (isAuthHeader(h) && typeof v !== "string")
124
+ dropped.add(v.field);
125
+ for (const v of Object.values(launchHeaders ?? {}))
126
+ if (typeof v !== "string")
127
+ dropped.delete(v.field);
128
+ }
129
+ /* ------------------------------------------------------------ saved keys */
130
+ const existing = new Set(options.existingSecrets ?? []);
131
+ /*
132
+ * Which saved key a secret field left empty may use. Only one the person
133
+ * chose (`__saved.<field>`), or -- for a server from our own catalog -- the
134
+ * key saved before for that same entry and field. A server from the public
135
+ * list, a paste or the form never gets a saved key on its own: its name
136
+ * and field ids come from a stranger, and a match by name would hand them
137
+ * another server's key.
138
+ */
139
+ const savedKeyFor = (f) => {
140
+ const chosen = values[`${SAVED_KEY_PREFIX}${f.id}`];
141
+ if (typeof chosen === "string" && chosen !== "")
142
+ return existing.has(chosen) ? chosen : undefined;
143
+ if (draft.source.kind !== "catalog")
144
+ return undefined;
145
+ const stable = secretNameFor(name, f);
146
+ if (stable !== secretNameFor(safeName(draft.source.id), f))
147
+ return undefined;
148
+ if (!existing.has(stable))
149
+ return undefined;
150
+ const label = options.existingSecretLabels?.[stable];
151
+ if (options.existingSecretLabels && label !== undefined && label !== f.label)
152
+ return undefined;
153
+ return stable;
154
+ };
155
+ for (const f of draft.fields) {
156
+ if (dropped.has(f.id))
157
+ continue;
158
+ const check = options.validateFor ? options.validateFor(f.id) : draft.source.kind === "catalog" ? f.validate : undefined;
159
+ const p = fieldProblem(f, valueOf(f), f.kind === "secret" ? savedKeyFor(f) !== undefined : false, check);
160
+ if (p)
161
+ problems[f.id] = p;
162
+ else if (isFilePathField(draft, f)) {
163
+ const v = valueOf(f);
164
+ const fp = typeof v === "string" && v.trim() !== "" ? filePlaceProblem(expandHome(v.trim())) : null;
165
+ if (fp)
166
+ problems[f.id] = fp;
167
+ }
168
+ }
169
+ /* ------------------------------------------------------------ secrets */
170
+ const secretsToCreate = [];
171
+ const secretsReferenced = [];
172
+ const claimed = new Set();
173
+ /** The `{ secret }` for a field, or undefined when an optional key was left empty. */
174
+ const secretRef = (id, prefix) => {
175
+ const f = fields.get(id);
176
+ if (!f) {
177
+ problems[id] = "This server's setup refers to a field that is missing.";
178
+ return undefined;
179
+ }
180
+ const v = values[id];
181
+ const stable = secretNameFor(name, f);
182
+ const ref = (secret) => ({ secret, ...(prefix ? { prefix } : {}) });
183
+ if (isBlank(v)) {
184
+ // Left empty: a saved key only when the person chose it, or our own catalog saved it for this field.
185
+ const saved = savedKeyFor(f);
186
+ if (saved) {
187
+ if (!secretsReferenced.includes(saved))
188
+ secretsReferenced.push(saved);
189
+ return ref(saved);
190
+ }
191
+ return undefined;
192
+ }
193
+ const already = secretsToCreate.find((s) => s.label === f.label && s.value === String(v));
194
+ if (already)
195
+ return ref(already.name);
196
+ let secret = stable;
197
+ for (let i = 2; existing.has(secret) || claimed.has(secret); i++)
198
+ secret = `${stable.slice(0, 60)}_${i}`;
199
+ claimed.add(secret);
200
+ secretsToCreate.push({ name: secret, label: f.label, value: stripPrefix(String(v).trim(), prefix) });
201
+ return ref(secret);
202
+ };
203
+ /* ------------------------------------------------------------ strings */
204
+ const fill = (text) => text.replace(/\{\{\s*fields\.([a-z0-9_]+)\s*\}\}/gi, (_m, id) => {
205
+ const f = fields.get(id);
206
+ if (!f) {
207
+ problems[id] = "This server's setup refers to a field that is missing.";
208
+ return "";
209
+ }
210
+ if (f.kind === "secret") {
211
+ // Never substituted: the key would land in gateway.yaml as text.
212
+ problems[id] = "This key cannot be used here: it would be written into the settings file as plain text.";
213
+ return "";
214
+ }
215
+ const v = valueOf(f);
216
+ if (v === undefined)
217
+ return "";
218
+ if (Array.isArray(v))
219
+ return v.map((s) => pathValue(f, s)).join(",");
220
+ if (typeof v === "string" && isFilePathField(draft, f))
221
+ return expandHome(v.trim());
222
+ return typeof v === "boolean" ? String(v) : pathValue(f, v);
223
+ });
224
+ const mapValues = (record) => {
225
+ const out = {};
226
+ for (const [k, v] of Object.entries(record ?? {})) {
227
+ if (typeof v === "string") {
228
+ /*
229
+ * An optional setting left empty is left out, not set to "": an
230
+ * empty variable or header is not the same as an absent one, and
231
+ * would override the server's own default.
232
+ */
233
+ const whole = /^\{\{\s*fields\.([a-z0-9_]+)\s*\}\}$/i.exec(v);
234
+ const f = whole ? fields.get(whole[1]) : undefined;
235
+ if (f && f.kind !== "secret" && f.kind !== "toggle" && isBlank(valueOf(f)))
236
+ continue;
237
+ out[k] = fill(v);
238
+ continue;
239
+ }
240
+ const ref = secretRef(v.field, v.prefix);
241
+ if (ref)
242
+ out[k] = ref;
243
+ }
244
+ return out;
245
+ };
246
+ /* ------------------------------------------------------------ the upstream */
247
+ const launch = draft.launch;
248
+ let upstream;
249
+ const egressHosts = [];
250
+ let localNetwork = false;
251
+ if (launch.transport === "stdio") {
252
+ const args = [];
253
+ for (const a of launch.args ?? []) {
254
+ const spread = /^\{\{\s*\.\.\.fields\.([a-z0-9_]+)\s*\}\}$/i.exec(a);
255
+ if (spread) {
256
+ const f = fields.get(spread[1]);
257
+ if (!f) {
258
+ problems[spread[1]] = "This server's setup refers to a field that is missing.";
259
+ continue;
260
+ }
261
+ const v = valueOf(f);
262
+ const list = Array.isArray(v) ? v : isBlank(v) ? [] : [String(v)];
263
+ args.push(...list.map((s) => pathValue(f, s)));
264
+ continue;
265
+ }
266
+ args.push(fill(a));
267
+ }
268
+ let command = fill(launch.command);
269
+ // A bare runtime name fails when an AI app starts the gateway with a short PATH.
270
+ if (!/[\\/]/.test(command) && options.commandPaths?.[command])
271
+ command = options.commandPaths[command];
272
+ upstream = { name, transport: "stdio", command, args, env: mapValues(launch.env) };
273
+ }
274
+ else {
275
+ const url = fill(launch.url);
276
+ const headers = mapValues(launchHeaders);
277
+ upstream = { name, transport: "http", url, headers };
278
+ const host = hostOf(url);
279
+ const keyIn = addressHoldsKey(url);
280
+ if (!host || (host.protocol !== "https:" && host.protocol !== "http:")) {
281
+ problems["url"] ??= "Enter the full address, starting with https://.";
282
+ }
283
+ else if (keyIn) {
284
+ // Never saved, never echoed: the address with the key in it stays out of every message.
285
+ problems["url"] ??=
286
+ keyIn === "userinfo"
287
+ ? "This address has a name and password inside it, which would be saved as plain text. Take them out of the address and give the key as a header instead."
288
+ : keyIn === "path"
289
+ ? "This address has a key inside it, which would be saved as plain text. Use the address without the key and give the key as a header, if the service allows one."
290
+ : "This address has a key inside it (after the “?”), which would be saved as plain text. Take it out of the address and give the key as a header instead.";
291
+ upstream["url"] = withoutKeys(url);
292
+ }
293
+ else {
294
+ const kind = addressKind(host.hostname);
295
+ const stranger = draft.source.kind === "registry" || draft.source.kind === "paste";
296
+ if (kind === "link-local" && draft.source.kind !== "catalog") {
297
+ // Cloud metadata lives here (169.254.169.254); nothing we didn't vet may be tested against it.
298
+ problems["url"] ??= localAddressWarning(kind);
299
+ }
300
+ else if (stranger && (kind === "loopback" || kind === "private") && values[LOCAL_OK_VALUE] !== true) {
301
+ problems[LOCAL_OK_VALUE] ??= `${localAddressWarning(kind)} Tick “This is on my own computer or network” to test it.`;
302
+ }
303
+ egressHosts.push(host.host);
304
+ localNetwork = isLocalAddress(host.hostname);
305
+ }
306
+ if (signIn) {
307
+ const typed = values[SIGN_IN_VALUE];
308
+ const secret = typeof typed === "string" && SECRET_NAME.test(typed) ? typed : signInSecretName(name);
309
+ upstream["oauth"] = { secret };
310
+ if (!secretsReferenced.includes(secret))
311
+ secretsReferenced.push(secret);
312
+ }
313
+ }
314
+ const parsed = UpstreamSchema.safeParse(upstream);
315
+ if (!parsed.success && Object.keys(problems).length === 0) {
316
+ problems["launch"] = `This server's settings are not valid: ${parsed.error.issues
317
+ .map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`)
318
+ .join("; ")}`;
319
+ }
320
+ /* ------------------------------------------------------------ the pack bound */
321
+ let within;
322
+ if (draft.pack && draft.pack_within_field) {
323
+ const f = fields.get(draft.pack_within_field);
324
+ const v = f ? valueOf(f) : undefined;
325
+ const list = Array.isArray(v) ? v : isBlank(v) ? [] : [String(v)];
326
+ within = f ? list.map((s) => pathValue(f, s)) : [];
327
+ }
328
+ return {
329
+ upstream: (parsed.success ? parsed.data : upstream),
330
+ secretsToCreate,
331
+ secretsReferenced,
332
+ egressHosts,
333
+ localNetwork,
334
+ ...(draft.pack ? { packId: draft.pack } : {}),
335
+ ...(within ? { within } : {}),
336
+ problems
337
+ };
338
+ }
339
+ /* ------------------------------------------------------------------ helpers */
340
+ /** The address with any name, password or key-named query value taken out, for messages. */
341
+ export function withoutKeys(url) {
342
+ try {
343
+ const u = new URL(url);
344
+ u.username = "";
345
+ u.password = "";
346
+ for (const k of [...u.searchParams.keys()])
347
+ if (SECRET_QUERY.test(k))
348
+ u.searchParams.set(k, "removed");
349
+ u.pathname = u.pathname
350
+ .split("/")
351
+ .map((seg) => (keyShaped(seg) ? "removed" : seg))
352
+ .join("/");
353
+ return u.toString();
354
+ }
355
+ catch {
356
+ return url.replace(/\/\/[^/@\s]*@/, "//");
357
+ }
358
+ }
359
+ /** Query parameters that carry a key: `?api_key=…`, `&token=…`. */
360
+ const SECRET_QUERY = /^(api[_-]?key|apikey|key|token|access[_-]?token|auth[_-]?token|auth|secret|client[_-]?secret|password|pass|pwd|sig|signature)$|(token|secret|password|api[_-]?key)$/i;
361
+ /**
362
+ * Whether an address carries a key where it can't be locked: a name and
363
+ * password before the host, or a query parameter named like a key.
364
+ */
365
+ export function addressHoldsKey(url) {
366
+ let u;
367
+ try {
368
+ u = new URL(url);
369
+ }
370
+ catch {
371
+ return null;
372
+ }
373
+ if (u.username || u.password)
374
+ return "userinfo";
375
+ for (const [k, v] of u.searchParams)
376
+ if (v !== "" && SECRET_QUERY.test(k))
377
+ return "query";
378
+ // Some services put the key in the address itself (`/mcp/<key>/…`, R2 N5).
379
+ if (u.pathname.split("/").some(keyShaped))
380
+ return "path";
381
+ return null;
382
+ }
383
+ /** A piece of an address that has the shape of a key (a GitHub token, a Stripe key, a long hex string...). */
384
+ function keyShaped(segment) {
385
+ let s = segment;
386
+ try {
387
+ s = decodeURIComponent(segment);
388
+ }
389
+ catch {
390
+ /* as written */
391
+ }
392
+ return s !== "" && SECRET_VALUE_PATTERNS.some((p) => p.regex.test(s));
393
+ }
394
+ /** Lower-case, digits and underscores: what gateway.yaml accepts as an upstream name. */
395
+ export function safeName(raw) {
396
+ const cleaned = raw
397
+ .toLowerCase()
398
+ .replace(/[^a-z0-9_]+/g, "_")
399
+ .replace(/_+/g, "_")
400
+ .replace(/^_+|_+$/g, "")
401
+ .slice(0, 48);
402
+ return cleaned || "server";
403
+ }
404
+ function uniqueName(base, taken) {
405
+ if (!taken.has(base))
406
+ return base;
407
+ for (let i = 2;; i++)
408
+ if (!taken.has(`${base}_${i}`))
409
+ return `${base}_${i}`;
410
+ }
411
+ /** The locked-key name a field's value is stored under: "github.token". */
412
+ export function secretNameFor(upstreamName, field) {
413
+ return cleanSecretName(`${upstreamName}.${field.id}`);
414
+ }
415
+ /** The locked-key name a sign-in is stored under; the UI derives the same one. */
416
+ export function signInSecretName(upstreamName) {
417
+ const base = cleanSecretName(upstreamName);
418
+ return `${base.slice(0, 56)}.signin`;
419
+ }
420
+ function cleanSecretName(raw) {
421
+ const base = raw.toLowerCase().replace(/[^a-z0-9_.-]+/g, "_").replace(/^[^a-z0-9]+/, "") || "server";
422
+ return base.slice(0, 64);
423
+ }
424
+ /** A pasted "Bearer abc" for a field whose template adds "Bearer " already. */
425
+ function stripPrefix(value, prefix) {
426
+ if (!prefix)
427
+ return value;
428
+ return value.toLowerCase().startsWith(prefix.toLowerCase()) ? value.slice(prefix.length).trim() : value;
429
+ }
430
+ function expandHome(v) {
431
+ if (v === "~")
432
+ return homedir();
433
+ if (v.startsWith("~/"))
434
+ return join(homedir(), v.slice(2));
435
+ return v;
436
+ }
437
+ /**
438
+ * A catalog text field that holds a file's place on this computer (its
439
+ * default is a path, like Memory's notebook). A server given an unusable
440
+ * place still starts and lists its tools, and only fails the first time the
441
+ * AI writes, long after the person has gone; so the place is checked here.
442
+ */
443
+ function isFilePathField(draft, f) {
444
+ return draft.source.kind === "catalog" && f.kind === "text" && typeof f.default === "string" && /^(~\/|\/|[A-Za-z]:[\\/])/.test(f.default);
445
+ }
446
+ /** Why a file can't be kept at this place, in plain words, or null when it can. */
447
+ export function filePlaceProblem(path) {
448
+ if (!(path.startsWith("/") || /^[A-Za-z]:[\\/]/.test(path)))
449
+ return "Give the full place, starting with / or ~/.";
450
+ const writable = (p) => {
451
+ try {
452
+ accessSync(p, constants.W_OK);
453
+ return true;
454
+ }
455
+ catch {
456
+ return false;
457
+ }
458
+ };
459
+ try {
460
+ const st = statSync(path);
461
+ if (st.isDirectory())
462
+ return `${path} is a folder. Add a file name at the end, such as ${join(path, "notes.jsonl")}.`;
463
+ if (!st.isFile())
464
+ return `${path} isn't an ordinary file, so it can't be used here.`;
465
+ return writable(path) ? null : `This computer won't let ${path} be changed. Choose another place.`;
466
+ }
467
+ catch (err) {
468
+ if (err.code !== "ENOENT") {
469
+ return `${path} can't be used: one of the folders on the way to it isn't a folder. Choose another place.`;
470
+ }
471
+ }
472
+ const parent = dirname(path);
473
+ try {
474
+ const st = statSync(parent);
475
+ if (!st.isDirectory())
476
+ return `${parent} isn't a folder, so a file can't be kept inside it. Choose another place.`;
477
+ }
478
+ catch (err) {
479
+ return err.code === "ENOENT"
480
+ ? `The folder ${parent} doesn't exist. Choose a place inside a folder that exists.`
481
+ : `${path} can't be used: one of the folders on the way to it isn't a folder. Choose another place.`;
482
+ }
483
+ return writable(parent) ? null : `This computer won't let a file be made in ${parent}. Choose another place.`;
484
+ }
485
+ /** Folders as absolute paths: a leading ~ means the home folder. */
486
+ function pathValue(f, value) {
487
+ if (f.kind !== "folder" && f.kind !== "folders")
488
+ return value;
489
+ const v = value.trim();
490
+ if (v === "~")
491
+ return homedir();
492
+ if (v.startsWith("~/"))
493
+ return `${homedir()}/${v.slice(2)}`;
494
+ return v;
495
+ }
496
+ function fieldProblem(f, value, hasSavedKey, validate) {
497
+ if (f.kind === "toggle")
498
+ return null;
499
+ if (isBlank(value)) {
500
+ if (!f.required)
501
+ return null;
502
+ if (f.kind === "secret")
503
+ return hasSavedKey ? null : "Paste the key here.";
504
+ if (f.kind === "folder")
505
+ return "Choose a folder.";
506
+ if (f.kind === "folders")
507
+ return "Choose at least one folder.";
508
+ if (f.kind === "choice")
509
+ return f.choices?.some((c) => c.value === "") ? null : "Pick one.";
510
+ return "Fill this in.";
511
+ }
512
+ const items = Array.isArray(value) ? value : [String(value)];
513
+ if (f.kind === "url") {
514
+ for (const item of items) {
515
+ const h = hostOf(item.trim());
516
+ if (!h || (h.protocol !== "https:" && h.protocol !== "http:"))
517
+ return "Enter the full address, starting with https://.";
518
+ }
519
+ }
520
+ if (f.kind === "folder" || f.kind === "folders") {
521
+ for (const item of items) {
522
+ const p = pathValue(f, item);
523
+ if (!(p.startsWith("/") || /^[A-Za-z]:[\\/]/.test(p)))
524
+ return "Choose a folder with the folder picker (a full path).";
525
+ }
526
+ }
527
+ if (f.kind === "choice" && f.choices && !f.choices.some((c) => c.value === value))
528
+ return "Pick one of the choices.";
529
+ if (validate && validate.pattern.length <= MAX_PATTERN) {
530
+ let re = null;
531
+ try {
532
+ re = new RegExp(validate.pattern);
533
+ }
534
+ catch {
535
+ re = null;
536
+ }
537
+ if (re)
538
+ for (const item of items) {
539
+ const v = item.trim();
540
+ if (v.length > MAX_CHECKED_VALUE || !re.test(v))
541
+ return validate.message;
542
+ }
543
+ }
544
+ return null;
545
+ }
546
+ function hostOf(url) {
547
+ try {
548
+ const u = new URL(url);
549
+ return { hostname: u.hostname, host: u.host, protocol: u.protocol };
550
+ }
551
+ catch {
552
+ return undefined;
553
+ }
554
+ }
555
+ /**
556
+ * Whether the egress guard refuses this host without its private-address
557
+ * protection loosened. The same test as adopt-plan.ts `isLocalAddress`, which
558
+ * is not exported: `localhost` counts because it resolves to loopback.
559
+ */
560
+ export function isLocalAddress(hostname) {
561
+ const bare = hostname.replace(/^\[|\]$/g, "");
562
+ if (bare === "localhost" || bare.endsWith(".localhost"))
563
+ return true;
564
+ if (!isIpLiteral(bare))
565
+ return false;
566
+ return classifyAddress(bare).blocked;
567
+ }
568
+ export function addressKind(hostname) {
569
+ const bare = hostname.replace(/^\[|\]$/g, "").toLowerCase();
570
+ if (bare === "localhost" || bare.endsWith(".localhost"))
571
+ return "loopback";
572
+ if (bare === "metadata.google.internal" || bare === "metadata" || bare === "instance-data")
573
+ return "link-local";
574
+ if (!isIpLiteral(bare))
575
+ return bare.endsWith(".local") || bare.endsWith(".internal") || bare.endsWith(".lan") ? "private" : "public";
576
+ // An IPv6 form of an IPv4 address is that address: `[::ffff:a9fe:a9fe]` is the metadata service (R2 N3).
577
+ const v4 = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(embeddedIPv4(bare) ?? bare);
578
+ if (v4) {
579
+ const [a, b] = [Number(v4[1]), Number(v4[2])];
580
+ if (a === 127)
581
+ return "loopback";
582
+ if (a === 169 && b === 254)
583
+ return "link-local";
584
+ if (a === 100 && b === 100 && v4[3] === "100" && v4[4] === "200")
585
+ return "link-local"; // a cloud metadata address
586
+ }
587
+ else {
588
+ if (bare === "::1")
589
+ return "loopback";
590
+ if (/^fe[89ab]/.test(bare))
591
+ return "link-local";
592
+ if (bare.startsWith("fd00:ec2:"))
593
+ return "link-local";
594
+ }
595
+ return classifyAddress(bare).blocked ? "private" : "public";
596
+ }