@cyanmycelium/mcp-broker 1.6.0 → 1.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bin.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
- import { loadBrokerConfig, loadSecurityConfig, BrokerConfigError, loadMcpbBundle, resolveOpenTarget } from './chunk-364F4ET6.js';
3
- import { PACKAGE_NAME, VERSION, WsTunnelBuilder, BROKER_AGGREGATE_NAME, BROKER_PROVIDER_NAME } from './chunk-PC4TLZGY.js';
2
+ import { loadBrokerConfig, loadSecurityConfig, BrokerConfigError, loadMcpbBundle, resolveOpenTarget } from './chunk-2GDTE7BA.js';
3
+ import { PACKAGE_NAME, VERSION, WsTunnelBuilder, BROKER_AGGREGATE_NAME, BROKER_PROVIDER_NAME } from './chunk-JVXOJUWT.js';
4
4
  import * as fs from 'fs';
5
5
  import * as path from 'path';
6
6
  import open from 'open';
@@ -1,4 +1,4 @@
1
- import { validateLimitsConfig } from './chunk-PC4TLZGY.js';
1
+ import { validateLimitsConfig } from './chunk-JVXOJUWT.js';
2
2
  import { createHash, X509Certificate, createPublicKey, verify } from 'crypto';
3
3
  import { readFileSync, mkdirSync, writeFileSync, existsSync, rmSync } from 'fs';
4
4
  import { homedir } from 'os';
@@ -382,5 +382,5 @@ function resolveOpenTarget(raw, baseUrl) {
382
382
  }
383
383
 
384
384
  export { BrokerConfigError, DEFAULT_CONFIG_FILENAME, loadBrokerConfig, loadMcpbBundle, loadSecurityConfig, resolveOpenTarget, unzipMcpb };
385
- //# sourceMappingURL=chunk-364F4ET6.js.map
386
- //# sourceMappingURL=chunk-364F4ET6.js.map
385
+ //# sourceMappingURL=chunk-2GDTE7BA.js.map
386
+ //# sourceMappingURL=chunk-2GDTE7BA.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/mcpb/mcpb.unzip.ts","../src/mcpb/mcpb.loader.ts","../src/config.ts"],"names":["dirname","resolve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,sEAAA,CAAwE,CAAA;AAAA,EACpH;AAEA,EAAA,IAAI,QAAA;AACJ,EAAA,IAAI;AACA,IAAA,QAAA,GAAW,IAAI,GAAA,CAAI,KAAA,EAAO,OAAO,CAAA;AAAA,EACrC,CAAA,CAAA,MAAQ;AACJ,IAAA,OAAO,MAAA,CAAO,CAAA,kBAAA,EAAqB,KAAK,CAAA,iCAAA,CAAmC,CAAA;AAAA,EAC/E;AAEA,EAAA,IAAI,SAAA,EAAW;AAGX,IAAA,IAAI,QAAA,CAAS,QAAA,KAAa,OAAA,IAAW,QAAA,CAAS,aAAa,QAAA,EAAU;AACjE,MAAA,OAAO,OAAO,CAAA,kBAAA,EAAqB,KAAK,CAAA,6CAAA,EAAgD,QAAA,CAAS,QAAQ,CAAA,aAAA,CAAe,CAAA;AAAA,IAC5H;AACA,IAAA,MAAM,IAAA,GAAO,IAAI,GAAA,CAAI,OAAO,CAAA;AAC5B,IAAA,IAAI,QAAA,CAAS,MAAA,KAAW,IAAA,CAAK,MAAA,EAAQ;AACjC,MAAA,OAAO,MAAA,CAAO,qBAAqB,KAAK,CAAA,gBAAA,EAAmB,SAAS,MAAM,CAAA,4BAAA,EAA+B,IAAA,CAAK,MAAM,CAAA,EAAA,CAAI,CAAA;AAAA,IAC5H;AAAA,EACJ;AAEA,EAAA,OAAO,EAAE,GAAA,EAAK,QAAA,CAAS,UAAS,EAAG,IAAA,EAAM,SAAS,QAAA,EAAS;AAC/D","file":"chunk-364F4ET6.js","sourcesContent":["/**\n * Minimal ZIP extractor for `.mcpb` bundles, built on `node:zlib` only.\n *\n * A `.mcpb` bundle is an ordinary ZIP archive. The broker deliberately avoids\n * the `@anthropic-ai/mcpb` package so it stays compatible with the format\n * without being coupled to Anthropic's tooling, hence this small reader.\n *\n * Supports the two compression methods used in practice: stored (0) and\n * deflate (8). ZIP64 archives are rejected with a clear error (`.mcpb` bundles\n * are small and never need it). Any trailing bytes after the End Of Central\n * Directory record (e.g. a native PKCS#7 signature block) are ignored, since\n * extraction is driven entirely by the central directory.\n */\nimport { mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, isAbsolute, relative, resolve } from \"node:path\";\nimport { inflateRawSync } from \"node:zlib\";\n\nconst EOCD_SIGNATURE = 0x06054b50;\nconst CENTRAL_HEADER_SIGNATURE = 0x02014b50;\nconst LOCAL_HEADER_SIGNATURE = 0x04034b50;\n\n/** Locates the End Of Central Directory record by scanning backwards. */\nfunction findEocd(buf: Buffer): number {\n // The EOCD is 22 bytes plus a comment of up to 65535 bytes.\n const minPos = Math.max(0, buf.length - 22 - 0xffff);\n for (let pos = buf.length - 22; pos >= minPos; pos--) {\n if (buf.readUInt32LE(pos) === EOCD_SIGNATURE) return pos;\n }\n throw new Error(\"not a ZIP archive (no End Of Central Directory record found)\");\n}\n\n/**\n * Extracts every entry of the `.mcpb` archive at `mcpbPath` into `destDir`.\n * `destDir` is created if missing. Entries whose resolved path would escape\n * `destDir` (zip-slip) are rejected.\n */\nexport function unzipMcpb(mcpbPath: string, destDir: string): void {\n const buf = readFileSync(mcpbPath);\n const eocd = findEocd(buf);\n\n const totalEntries = buf.readUInt16LE(eocd + 10);\n const centralDirOffset = buf.readUInt32LE(eocd + 16);\n if (centralDirOffset === 0xffffffff || totalEntries === 0xffff) {\n throw new Error(\"ZIP64 archives are not supported\");\n }\n\n const absDest = resolve(destDir);\n mkdirSync(absDest, { recursive: true });\n\n let pos = centralDirOffset;\n for (let i = 0; i < totalEntries; i++) {\n if (buf.readUInt32LE(pos) !== CENTRAL_HEADER_SIGNATURE) {\n throw new Error(`corrupt ZIP: bad central directory header at offset ${pos}`);\n }\n const method = buf.readUInt16LE(pos + 10);\n const compressedSize = buf.readUInt32LE(pos + 20);\n const uncompressedSize = buf.readUInt32LE(pos + 24);\n const nameLen = buf.readUInt16LE(pos + 28);\n const extraLen = buf.readUInt16LE(pos + 30);\n const commentLen = buf.readUInt16LE(pos + 32);\n const localHeaderOffset = buf.readUInt32LE(pos + 42);\n const name = buf.toString(\"utf8\", pos + 46, pos + 46 + nameLen);\n pos += 46 + nameLen + extraLen + commentLen;\n\n if (compressedSize === 0xffffffff || uncompressedSize === 0xffffffff || localHeaderOffset === 0xffffffff) {\n throw new Error(\"ZIP64 archives are not supported\");\n }\n\n // Resolve the destination path and reject zip-slip escapes.\n const target = resolve(absDest, name);\n const rel = relative(absDest, target);\n if (rel.startsWith(\"..\") || isAbsolute(rel)) {\n throw new Error(`unsafe ZIP entry path (zip-slip): ${name}`);\n }\n\n // Directory entry.\n if (name.endsWith(\"/\")) {\n mkdirSync(target, { recursive: true });\n continue;\n }\n\n // Parse the local header to locate the entry's data.\n if (buf.readUInt32LE(localHeaderOffset) !== LOCAL_HEADER_SIGNATURE) {\n throw new Error(`corrupt ZIP: bad local header for \"${name}\"`);\n }\n const localNameLen = buf.readUInt16LE(localHeaderOffset + 26);\n const localExtraLen = buf.readUInt16LE(localHeaderOffset + 28);\n const dataStart = localHeaderOffset + 30 + localNameLen + localExtraLen;\n const compressed = buf.subarray(dataStart, dataStart + compressedSize);\n\n let data: Buffer;\n if (method === 0) {\n data = compressed;\n } else if (method === 8) {\n data = inflateRawSync(compressed);\n } else {\n throw new Error(`unsupported ZIP compression method ${method} for \"${name}\"`);\n }\n\n mkdirSync(dirname(target), { recursive: true });\n writeFileSync(target, data);\n }\n}\n","/**\n * Loads a local `.mcpb` bundle into an {@link IStdioUpstreamConfig}.\n *\n * A `.mcpb` bundle is a ZIP holding a `manifest.json` whose `server.mcp_config`\n * describes a stdio MCP server process. The broker:\n *\n * 1. verifies a **detached signature** of the `.mcpb` file against a trusted\n * public key (PEM), integrity *and* provenance, using `node:crypto` only;\n * 2. unpacks the archive;\n * 3. reads the manifest, expands the `mcp_config` placeholders, and produces a\n * `IStdioUpstreamConfig` that the existing upstream wiring spawns.\n *\n * The broker stays compatible with the `.mcpb` format without depending on the\n * `@anthropic-ai/mcpb` package: the bundle's *own* (native PKCS#7) signature is\n * never parsed: the detached signature layer is the broker's trust anchor.\n *\n * Any failure (missing files, bad signature, malformed manifest, missing\n * `user_config` value) is logged and yields `null`: the bundle is refused and\n * no process is ever spawned. Never auto-runs an unverified bundle.\n */\nimport { createPublicKey, verify, X509Certificate, type KeyObject } from \"node:crypto\";\nimport { existsSync, readFileSync, rmSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join, resolve, sep } from \"node:path\";\nimport { unzipMcpb } from \"./mcpb.unzip\";\nimport type { IStdioUpstreamConfig } from \"../stdio.upstream\";\n\n/** A `.mcpb` bundle entry from the broker config file. */\nexport interface IMcpbBundleConfig {\n /** Provider slot name the bundle is bound to. */\n name: string;\n /** Path to the `.mcpb` file. */\n path: string;\n /** Path to the trusted public key (PEM) verifying the detached signature. */\n publicKey: string;\n /** Path to the detached signature file. Defaults to `<path>.sig`. */\n signature?: string;\n /** Values substituted into the manifest's `${user_config.*}` placeholders. */\n userConfig?: Record<string, string | number | boolean | Array<string | number>>;\n /** When `false`, the bundle stays out of the `_all` aggregate slot. Defaults to `true`. */\n aggregate?: boolean;\n}\n\ninterface IMcpConfig {\n command?: string;\n args?: string[];\n env?: Record<string, string>;\n platform_overrides?: Record<string, { command?: string; args?: string[]; env?: Record<string, string> }>;\n}\n\n/** Loads a PEM that holds either an X.509 certificate or a bare public key. */\nfunction loadPublicKey(pem: string): KeyObject {\n if (pem.includes(\"BEGIN CERTIFICATE\")) {\n return new X509Certificate(pem).publicKey;\n }\n return createPublicKey(pem);\n}\n\n/** Verifies the detached `signature` of `data` against `publicKey`. */\nfunction verifyDetachedSignature(data: Buffer, signature: Buffer, publicKey: KeyObject): boolean {\n // Ed25519/Ed448 are used without a separate hash algorithm; RSA/EC need one.\n const keyType = publicKey.asymmetricKeyType;\n const algorithm = keyType === \"ed25519\" || keyType === \"ed448\" ? null : \"sha256\";\n return verify(algorithm, data, publicKey, signature);\n}\n\n/** Resolves a single `${...}` placeholder key, or `undefined` when unknown. */\nfunction resolvePlaceholder(key: string, dirname: string, userConfig: IMcpbBundleConfig[\"userConfig\"]): string | number | boolean | Array<string | number> | undefined {\n if (key === \"__dirname\") return dirname;\n if (key === \"HOME\") return homedir();\n if (key === \"DESKTOP\") return join(homedir(), \"Desktop\");\n if (key === \"DOCUMENTS\") return join(homedir(), \"Documents\");\n if (key === \"DOWNLOADS\") return join(homedir(), \"Downloads\");\n if (key === \"pathSeparator\" || key === \"/\") return sep;\n if (key.startsWith(\"user_config.\")) {\n const name = key.slice(\"user_config.\".length);\n const value = userConfig?.[name];\n if (value === undefined) throw new Error(`missing user_config value: \"${name}\"`);\n return value;\n }\n return undefined;\n}\n\n/** Expands placeholders in a scalar string (command, env value). */\nfunction expandScalar(input: string, dirname: string, userConfig: IMcpbBundleConfig[\"userConfig\"]): string {\n return input.replace(/\\$\\{([^}]+)\\}/g, (match, key: string) => {\n const value = resolvePlaceholder(key, dirname, userConfig);\n if (value === undefined) return match; // unknown placeholder, leave verbatim\n if (Array.isArray(value)) throw new Error(`placeholder \"\\${${key}}\" is multi-valued and cannot be used here`);\n return String(value);\n });\n}\n\n/** Expands one manifest argument; a standalone multi-valued placeholder spreads. */\nfunction expandArg(arg: string, dirname: string, userConfig: IMcpbBundleConfig[\"userConfig\"]): string[] {\n const standalone = /^\\$\\{(user_config\\.[^}]+)\\}$/.exec(arg);\n if (standalone) {\n const value = resolvePlaceholder(standalone[1], dirname, userConfig);\n if (Array.isArray(value)) return value.map(String);\n return [String(value)];\n }\n return [expandScalar(arg, dirname, userConfig)];\n}\n\n/**\n * Verifies, unpacks and resolves a `.mcpb` bundle into an `IStdioUpstreamConfig`.\n *\n * @param cfg The bundle entry from the broker config.\n * @param baseDir Directory the bundle paths are resolved against.\n * @returns A ready upstream config, or `null` when the bundle is refused.\n */\nexport async function loadMcpbBundle(cfg: IMcpbBundleConfig, baseDir: string): Promise<IStdioUpstreamConfig | null> {\n const tag = `[mcp-broker] mcpb bundle \"${cfg.name}\"`;\n try {\n const mcpbPath = resolve(baseDir, cfg.path);\n const publicKeyPath = resolve(baseDir, cfg.publicKey);\n const signaturePath = cfg.signature ? resolve(baseDir, cfg.signature) : `${mcpbPath}.sig`;\n\n for (const [label, file] of [\n [\"bundle\", mcpbPath],\n [\"public key\", publicKeyPath],\n [\"signature\", signaturePath],\n ] as const) {\n if (!existsSync(file)) {\n console.error(`${tag}: ${label} file not found at ${file}, bundle refused.`);\n return null;\n }\n }\n\n // ── Signature verification (mandatory) ──────────────────────────────\n const bundleBytes = readFileSync(mcpbPath);\n const signatureBytes = readFileSync(signaturePath);\n const publicKey = loadPublicKey(readFileSync(publicKeyPath, \"utf8\"));\n if (!verifyDetachedSignature(bundleBytes, signatureBytes, publicKey)) {\n console.error(`${tag}: detached signature is invalid for the configured public key, bundle refused.`);\n return null;\n }\n\n // ── Unpack ──────────────────────────────────────────────────────────\n const outputDir = resolve(baseDir, \".cache\", \"mcpb\", cfg.name);\n rmSync(outputDir, { recursive: true, force: true });\n unzipMcpb(mcpbPath, outputDir);\n\n // ── Manifest → mcp_config ───────────────────────────────────────────\n const manifestPath = join(outputDir, \"manifest.json\");\n if (!existsSync(manifestPath)) {\n console.error(`${tag}: manifest.json missing inside the bundle, bundle refused.`);\n return null;\n }\n const manifest = JSON.parse(readFileSync(manifestPath, \"utf8\")) as { server?: { mcp_config?: IMcpConfig } };\n const mcpConfig = manifest.server?.mcp_config;\n if (!mcpConfig) {\n console.error(`${tag}: manifest has no server.mcp_config, bundle refused.`);\n return null;\n }\n\n // Platform-specific overrides replace the base fields when present.\n const override = mcpConfig.platform_overrides?.[process.platform];\n const command = override?.command ?? mcpConfig.command;\n const rawArgs = override?.args ?? mcpConfig.args ?? [];\n const rawEnv = { ...mcpConfig.env, ...override?.env };\n if (!command) {\n console.error(`${tag}: manifest mcp_config has no command, bundle refused.`);\n return null;\n }\n\n // ── Placeholder expansion ───────────────────────────────────────────\n const expandedCommand = expandScalar(command, outputDir, cfg.userConfig);\n const expandedArgs = rawArgs.flatMap((arg) => expandArg(arg, outputDir, cfg.userConfig));\n const expandedEnv: Record<string, string> = {};\n for (const [key, value] of Object.entries(rawEnv)) {\n expandedEnv[key] = expandScalar(value, outputDir, cfg.userConfig);\n }\n\n return {\n name: cfg.name,\n command: expandedCommand,\n args: expandedArgs,\n env: Object.keys(expandedEnv).length > 0 ? expandedEnv : undefined,\n aggregate: cfg.aggregate ?? true,\n };\n } catch (err) {\n console.error(`${tag}: ${(err as Error).message}, bundle refused.`);\n return null;\n }\n}\n\n/** @deprecated Use {@link IMcpbBundleConfig}. */\nexport type McpbBundleConfig = IMcpbBundleConfig;\n","import { validateLimitsConfig, type ILimitsConfig } from \"./limits/controller\";\nimport { createHash } from \"node:crypto\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport type { IAuthorizationPolicyConfig } from \"./authorization/index\";\nimport type { IProviderCredential } from \"./auth/provider.auth\";\nimport type { IProtectedSlot } from \"./authority/declaration\";\n\nexport interface IBrokerAuthConfig extends IAuthorizationPolicyConfig {\n /** Master switch. Absent/`false` keeps the broker unauthenticated. */\n enabled?: boolean;\n /** Public origin the broker is reached at (e.g. `https://mcp.example.com`). */\n publicBaseUrl?: string;\n /** Authorization server issuer URL(s) advertised in the metadata. */\n authorizationServers?: string[];\n /** URL of the authorization server's JWKS document. */\n jwks?: string;\n /** Expected token issuer. Defaults to the sole `authorizationServers` entry. */\n issuer?: string;\n /** Scopes advertised in the metadata `scopes_supported`. */\n scopesSupported?: string[];\n /** Baseline scope(s) required to reach any slot. */\n requiredScopes?: string[];\n /** Per-slot required-scope overrides (e.g. an admin scope for `_broker`). */\n perSlotScopes?: Record<string, string[]>;\n /**\n * Per-provider scope requirements for the `_all` aggregate. Deprecated in\n * favor of hierarchical policy assignments.\n */\n providerScopes?: Record<string, string[]>;\n /**\n * Shared secret every provider must present to occupy a slot. Independent\n * of client authorization.\n */\n providerSecret?: string;\n}\n\n/**\n * Shape of the optional JSON config file consumed by `bin.ts` at startup.\n * Every field is optional. Environment variables (`MCP_BROKER_*`) always win\n * over file values, and file values win over the built-in defaults.\n *\n * @example\n * ```json\n * {\n * \"port\": 3001,\n * \"locale\": \"fr\",\n * \"tls\": { \"cert\": \"certs/cert.pem\", \"key\": \"certs/key.pem\" },\n * \"stdioUpstreams\": [\n * { \"name\": \"fs\", \"command\": \"npx\", \"args\": [\"-y\", \"@modelcontextprotocol/server-filesystem\", \"/data\"] }\n * ]\n * }\n * ```\n */\nexport interface IBrokerConfig {\n /** TCP port. Maps to `MCP_BROKER_PORT`. */\n port?: number;\n\n /** Bind host. Maps to `MCP_BROKER_HOST`. */\n host?: string;\n\n /** Force protocol (`http`/`https`) regardless of cert presence. Maps to `MCP_BROKER_PROTOCOL`. */\n protocol?: \"http\" | \"https\";\n\n /** Locale fed to the broker grammar resolver. Maps to `MCP_BROKER_LOCALE`. */\n locale?: string;\n\n /** Bridge stdin/stdout for a Claude-Desktop-style client. Maps to `MCP_BROKER_STDIO_PROVIDER`. */\n stdioProvider?: string;\n\n /**\n * Logical broker name reported by `broker_info`.\n *\n * **Library-only today.** `WsTunnel` honors it\n * (`IWsTunnelOptions.brokerName`), but `WsTunnelBuilder` has no\n * `withBrokerName()`, so the CLI cannot forward it and setting it in\n * `config.json` has no effect. Set it through the programmatic API until\n * the setter exists.\n */\n brokerName?: string;\n\n /**\n * How often (ms) the broker pings each connected provider socket to check\n * it is still there. `0` disables the heartbeat. Maps to\n * `MCP_BROKER_PROVIDER_HEARTBEAT_MS`.\n *\n * A provider that misses a full interval is terminated and its slot freed,\n * which is what stops a half-open socket (a killed browser tab, a slept\n * laptop, a dropped VPN) from holding a slot for the ~2 hours the OS takes\n * to give up on the TCP connection, refusing every reconnect meanwhile.\n *\n * @default 30000\n */\n providerHeartbeatIntervalMs?: number;\n\n /**\n * How long (ms) the broker waits for a provider to answer one request\n * before failing it with a JSON-RPC error naming the slot. `0` disables the\n * deadline. Maps to `MCP_BROKER_PROVIDER_REQUEST_TIMEOUT_MS`.\n *\n * Raise it if you host genuinely long-running tools; without it a provider\n * that stays connected and never answers (a throttled background browser\n * tab is the ordinary case) leaves the caller waiting forever.\n *\n * @default 60000\n */\n providerRequestTimeoutMs?: number;\n\n /**\n * Bounds on `resources/subscribe` bookkeeping. Each field maps to an env\n * var: `MCP_BROKER_MAX_SUBSCRIPTIONS_PER_CLIENT` (default 64),\n * `MCP_BROKER_MAX_SUBSCRIPTIONS_PER_SLOT` (default 1024),\n * `MCP_BROKER_MAX_RESOURCE_URI_LENGTH` (default 2048).\n */\n resourceSubscriptions?: {\n maxSubscriptionsPerClient?: number;\n maxSubscriptionsPerSlot?: number;\n maxResourceUriLength?: number;\n };\n\n /** Optional OTLP/HTTP trace export for provider telemetry notifications. */\n telemetry?: {\n /** Full traces endpoint, usually http://collector:4318/v1/traces. */\n otlpHttpEndpoint: string;\n headers?: Record<string, string>;\n timeoutMs?: number;\n serviceNamespace?: string;\n maxFrameBytes?: number;\n queueCapacity?: number;\n batchSize?: number;\n maxAttributes?: number;\n maxEvents?: number;\n };\n\n /**\n * What happens when a provider connects to a slot another socket already\n * holds. Maps to `MCP_BROKER_PROVIDER_TAKEOVER`.\n *\n * - `\"reject\"`: the incumbent always keeps the slot.\n * - `\"liveness\"` (default): the incumbent keeps it only while it answers\n * the heartbeat.\n * - `\"always\"`: the newcomer wins, but only when provider authentication is\n * configured and it authenticated as the same principal as the incumbent.\n * Without provider auth the broker falls back to `\"liveness\"` and says so,\n * because unconditional takeover would let anyone who can reach the URL\n * evict the real provider.\n *\n * @default \"liveness\"\n */\n providerTakeover?: \"reject\" | \"liveness\" | \"always\";\n\n /**\n * Browser origins allowed to reach `/<slot>/mcp`.\n *\n * Absent means no browser origin is accepted: a request carrying an\n * `Origin` header gets `403`, one carrying none (Claude Desktop, MCP\n * Inspector, any server-side SDK) always passes. The MCP specification asks\n * for this check, since without it any web page loaded in a browser that\n * can reach the broker could drive it.\n *\n * An array lists origins matched **exactly**. An object supplies a regular\n * expression tested against the whole `Origin` header. Also maps to\n * `MCP_BROKER_ALLOWED_ORIGINS` (comma-separated list form only; a pattern\n * needs the config file).\n *\n * @example\n * ```json\n * { \"allowedOrigins\": [\"https://app.example.com\", \"http://localhost:5173\"] }\n * { \"allowedOrigins\": { \"pattern\": \"^https://[a-z0-9-]+\\\\.example\\\\.com$\" } }\n * ```\n */\n allowedOrigins?: string[] | { pattern: string; flags?: string };\n\n /**\n * OAuth 2.1 resource-server authorization. When `enabled` is `true`, every\n * HTTP client request to a slot must carry a valid `Authorization: Bearer`\n * token issued for that slot, and the broker publishes Protected Resource\n * Metadata (RFC 9728). Absent/`false` ⇒ no authentication (trusted-network\n * mode, the historical behavior).\n *\n * Scalars also map to env vars (which win): `MCP_BROKER_AUTH_ENABLED`,\n * `MCP_BROKER_PUBLIC_BASE_URL`, `MCP_BROKER_JWKS`, `MCP_BROKER_ISSUER`.\n *\n * Deprecated here: put it in the security file ({@link securityFile}).\n * The broker refuses to start when both carry one.\n */\n auth?: IBrokerAuthConfig;\n\n /**\n * Path to the security file, resolved against this file's directory. It\n * holds `auth`, the `providers` table and `authorization.protectedSlots`,\n * so topology and security are written, read and protected separately.\n * Maps to `MCP_BROKER_SECURITY_FILE` (resolved against the cwd), which wins.\n */\n securityFile?: string;\n\n /**\n * URL paths (override the defaults). Every key is also settable through an\n * environment variable, which wins.\n *\n * Changing one moves an endpoint for **every** peer: a provider SDK, a\n * client, and the startup banner all have to agree. The two provider paths\n * are not interchangeable, they carry different framing:\n * `provider` is a prefix (`<provider>/<slot>`) speaking plain JSON-RPC\n * frames (`DirectTransport`), `providers` is matched exactly and speaks\n * multiplex envelopes (`MultiplexTransport`).\n */\n paths?: {\n /** Prefix for one-slot-per-socket provider connections. Maps to `MCP_BROKER_PROVIDER_PATH`. @default \"/provider\" */\n provider?: string;\n /** Exact path for multiplexed provider connections. Maps to `MCP_BROKER_PROVIDERS_PATH`. @default \"/providers\" */\n providers?: string;\n /** Prefix raw-WebSocket clients connect to. Maps to `MCP_BROKER_CLIENT_PATH`. @default \"/\" */\n client?: string;\n /** Per-slot suffix for the Streamable HTTP transport. Maps to `MCP_BROKER_MCP_PATH`. @default \"/mcp\" */\n mcp?: string;\n /** Per-slot suffix for the legacy SSE stream (GET). Maps to `MCP_BROKER_SSE_PATH`. @default \"/sse\" */\n sse?: string;\n /** Per-slot suffix for legacy SSE JSON-RPC posts. Maps to `MCP_BROKER_MESSAGES_PATH`. @default \"/messages\" */\n messages?: string;\n };\n\n /** TLS material as paths on disk. Resolved against the config file's directory. */\n tls?: {\n cert: string;\n key: string;\n };\n\n /**\n * Static-file serving alongside the JSON-RPC endpoints. JSON-RPC routes\n * always take precedence.\n */\n www?: {\n /**\n * Auto-launch the default browser on startup. Maps to `MCP_BROKER_OPEN`.\n *\n * - `false` / absent / `\"\"` / `\"0\"`: do not open anything.\n * - `true` / `\"1\"`: open the broker root, `<scheme>://localhost:<port>/`.\n * - a path (`\"/app/index.html\"`): open that page on this broker.\n * - an absolute URL on this broker's own origin: opened as given.\n *\n * A URL on any other origin is refused with a message, and so is any\n * other string. See {@link resolveOpenTarget} for why.\n *\n * The browser opens only when a static mount actually covers the\n * resolved path; otherwise the broker says which mounts exist instead of\n * launching a browser onto a 404.\n */\n open?: boolean | string;\n /** URL-prefix → directory mappings. Longest-prefix match wins. */\n mounts?: Array<{\n urlPrefix: string;\n dir: string;\n }>;\n };\n\n /** Stdio upstream providers spawned by the broker at startup. */\n stdioUpstreams?: Array<{\n name: string;\n command: string;\n args?: string[];\n env?: Record<string, string>;\n /** When `true`, the upstream joins the `_all` aggregate slot once connected. */\n aggregate?: boolean;\n }>;\n\n /**\n * Remote MCP servers the broker connects out to and exposes as provider\n * slots. Each entry is reached by URL (Streamable HTTP / SSE / WebSocket);\n * local servers should be shipped as `.mcpb` bundles instead.\n */\n mcpServers?: Array<{\n name: string;\n url: string;\n transport?: \"streamable-http\" | \"sse\" | \"websocket\";\n headers?: Record<string, string>;\n /** Defaults to `true`; set to `false` to exclude this upstream from the `_all` aggregate slot. */\n aggregate?: boolean;\n }>;\n\n /**\n * Local `.mcpb` bundles the broker loads at startup and runs as stdio\n * provider slots. A bundle is a ZIP with a `manifest.json`; the broker\n * verifies a detached signature against a trusted public key before\n * unpacking and spawning it.\n */\n mcpbBundles?: Array<{\n /** Provider slot name the bundle is bound to. */\n name: string;\n /** Path to the `.mcpb` file (resolved against the config file's directory). */\n path: string;\n /** Path to the trusted public key (PEM) used to verify the detached signature. */\n publicKey: string;\n /** Path to the detached signature file. Defaults to `<path>.sig`. */\n signature?: string;\n /** Values substituted into the manifest's `${user_config.*}` placeholders. */\n userConfig?: Record<string, string | number | boolean | Array<string | number>>;\n /** Defaults to `true`; set to `false` to exclude this bundle from the `_all` aggregate slot. */\n aggregate?: boolean;\n }>;\n}\n\n/**\n * Returned by {@link loadBrokerConfig}. The {@link config} is the parsed JSON;\n * {@link baseDir} is the directory used to resolve relative paths inside it\n * (the directory containing the config file when one was found, otherwise\n * `process.cwd()`).\n */\nexport interface ILoadedBrokerConfig {\n config: IBrokerConfig;\n baseDir: string;\n /** Absolute path of the config file that was loaded, or `null` if none. */\n sourcePath: string | null;\n}\n\n/** Default folder name (relative to `process.cwd()`) holding broker-local files. */\nexport const DEFAULT_CONFIG_DIR = \".mcp-broker\";\n\n/** Default config filename inside {@link DEFAULT_CONFIG_DIR}. */\nexport const DEFAULT_CONFIG_FILENAME = \"config.json\";\n\n/** Legacy flat config filename at the cwd root (pre-`.mcp-broker/` layout). */\nexport const LEGACY_CONFIG_FILENAME = \"mcp-broker.config.json\";\n\n/** One entry of the security file's `providers` table: the secret is named, never written. */\nexport interface ISecurityProviderEntry {\n /** Provider principal id. */\n id: string;\n /** Name of the environment variable holding this provider's secret. */\n secretEnv: string;\n /** Subjects this provider holds when it calls the broker as a client. */\n subjects?: string[];\n /** Resource patterns this provider may publish into; absent means all. */\n allowedResources?: string[];\n}\n\n/**\n * Shape of the security file: everything that decides who may do what, kept\n * apart from the topology in `config.json`.\n */\nexport interface ISecurityConfig {\n limits?: ILimitsConfig;\n /** The same block as `config.json`'s `auth`, minus `providerSecret` (use `MCP_BROKER_PROVIDER_SECRET`). */\n auth?: IBrokerAuthConfig;\n /** One identity per provider. */\n providers?: ISecurityProviderEntry[];\n authorization?: {\n /** Slots only one provider may call and one may publish, keyed by slot name. */\n protectedSlots?: Record<string, IProtectedSlot>;\n };\n}\n\n/** A loaded security file, with the secrets it names resolved from the environment. */\nexport interface ILoadedSecurityConfig {\n readonly security: ISecurityConfig;\n /** Absolute path of the file. */\n readonly sourcePath: string;\n /** First 12 hex digits of the file's SHA-256: what `policyVersion` starts with. */\n readonly version: string;\n /** The `providers` table, secrets resolved. */\n readonly credentials: readonly IProviderCredential[];\n}\n\nconst SECURITY_KEYS = new Set([\"$schema\", \"description\", \"auth\", \"providers\", \"authorization\", \"limits\"]);\n\n/**\n * Loads the security file named by `MCP_BROKER_SECURITY_FILE` or by\n * `config.securityFile`, or returns `null` when neither names one.\n *\n * Fails closed, like {@link loadBrokerConfig}: a designated file that is\n * missing, unreadable, not a JSON object, or inconsistent throws a\n * {@link BrokerConfigError}, and so does a provider whose secret variable is\n * unset. So does a `config.json` that still carries `auth` next to a security\n * file: picking one of the two silently would leave the operator guessing\n * which rules are in force.\n */\nexport function loadSecurityConfig(loaded: ILoadedBrokerConfig, env: NodeJS.ProcessEnv = process.env): ILoadedSecurityConfig | null {\n // Keys that only the security file may carry, refused in config.json\n // whether or not a security file exists: left there, they would be\n // ignored, and a protection the operator wrote would silently not exist.\n const misplaced = [\"providers\", \"authorization\", \"limits\"].filter((key) => Object.prototype.hasOwnProperty.call(loaded.config, key));\n if (misplaced.length > 0 && loaded.sourcePath) {\n throw new BrokerConfigError(\n loaded.sourcePath,\n `${misplaced.map((k) => `\"${k}\"`).join(\" and \")} belong in the security file (securityFile / MCP_BROKER_SECURITY_FILE), not in the config file`\n );\n }\n\n const envPath = env[\"MCP_BROKER_SECURITY_FILE\"];\n const sourcePath = envPath ? resolve(process.cwd(), envPath) : loaded.config.securityFile ? resolve(loaded.baseDir, loaded.config.securityFile) : null;\n if (!sourcePath) return null;\n\n if (!existsSync(sourcePath)) {\n throw new BrokerConfigError(sourcePath, `the security file designated by ${envPath ? \"MCP_BROKER_SECURITY_FILE\" : \"securityFile in the config file\"} does not exist`);\n }\n let raw: Buffer;\n let parsed: unknown;\n try {\n raw = readFileSync(sourcePath);\n parsed = JSON.parse(raw.toString(\"utf-8\")) as unknown;\n } catch (err) {\n throw new BrokerConfigError(sourcePath, (err as Error).message);\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new BrokerConfigError(sourcePath, \"the top-level value must be a JSON object\");\n }\n const security = parsed as ISecurityConfig;\n\n const problems: string[] = [];\n for (const key of Object.keys(security)) if (!SECURITY_KEYS.has(key)) problems.push(`unknown key \"${key}\"`);\n if (loaded.config.auth !== undefined) {\n problems.push(\n `the config file${loaded.sourcePath ? ` (${loaded.sourcePath})` : \"\"} also carries \"auth\"; move it into the security file, so there is one source of security settings`\n );\n }\n if (security.auth?.providerSecret !== undefined) {\n problems.push('\"auth.providerSecret\" would put a secret in clear in the file; set MCP_BROKER_PROVIDER_SECRET instead, or give each provider an entry in \"providers\"');\n }\n\n const credentials: IProviderCredential[] = [];\n if (security.providers !== undefined) {\n if (!Array.isArray(security.providers)) problems.push('\"providers\" must be an array');\n else {\n for (const [index, entry] of security.providers.entries()) {\n const label = `providers[${index}]`;\n if (typeof entry !== \"object\" || entry === null) {\n problems.push(`${label} must be an object`);\n continue;\n }\n for (const key of Object.keys(entry)) {\n if (key === \"secret\") problems.push(`${label}: \"secret\" would put a secret in clear in the file; name the environment variable that holds it in \"secretEnv\"`);\n else if (![\"id\", \"secretEnv\", \"subjects\", \"allowedResources\"].includes(key)) problems.push(`${label}: unknown key \"${key}\"`);\n }\n if (typeof entry.id !== \"string\" || entry.id.length === 0) problems.push(`${label}: \"id\" must be a non-empty string`);\n if (entry.subjects !== undefined && (!Array.isArray(entry.subjects) || entry.subjects.some((v) => typeof v !== \"string\")))\n problems.push(`${label}: \"subjects\" must be an array of strings`);\n if (entry.allowedResources !== undefined && (!Array.isArray(entry.allowedResources) || entry.allowedResources.some((v) => typeof v !== \"string\"))) {\n problems.push(`${label}: \"allowedResources\" must be an array of strings`);\n }\n if (typeof entry.secretEnv !== \"string\" || entry.secretEnv.length === 0) {\n problems.push(`${label}: \"secretEnv\" must name the environment variable holding this provider's secret`);\n continue;\n }\n const secret = env[entry.secretEnv];\n if (!secret) {\n problems.push(`${label} (\"${String(entry.id)}\"): the environment variable ${entry.secretEnv} is not set`);\n continue;\n }\n credentials.push({\n id: entry.id,\n secret,\n ...(entry.subjects !== undefined ? { subjects: entry.subjects } : {}),\n ...(entry.allowedResources !== undefined ? { allowedResources: entry.allowedResources } : {}),\n });\n }\n }\n }\n\n if (security.limits !== undefined) {\n try {\n validateLimitsConfig(security.limits);\n if (security.limits.storeFile) security.limits = { ...security.limits, storeFile: resolve(dirname(sourcePath), security.limits.storeFile) };\n } catch (error) {\n problems.push((error as Error).message);\n }\n }\n const authorization = security.authorization;\n if (authorization !== undefined) {\n if (typeof authorization !== \"object\" || authorization === null || Array.isArray(authorization)) problems.push('\"authorization\" must be an object');\n else {\n for (const key of Object.keys(authorization)) if (key !== \"protectedSlots\") problems.push(`authorization: unknown key \"${key}\"`);\n const slots = authorization.protectedSlots;\n if (slots !== undefined && (typeof slots !== \"object\" || slots === null || Array.isArray(slots)))\n problems.push('\"authorization.protectedSlots\" must be an object keyed by slot name');\n else if (slots) {\n for (const [slot, entry] of Object.entries(slots)) {\n if (typeof entry !== \"object\" || entry === null || Array.isArray(entry)) {\n problems.push(`authorization.protectedSlots[\"${slot}\"] must be { \"declaredBy\": \"<id>\", \"publishedBy\": \"<id>\" }`);\n continue;\n }\n for (const key of Object.keys(entry))\n if (key !== \"declaredBy\" && key !== \"publishedBy\") problems.push(`authorization.protectedSlots[\"${slot}\"]: unknown key \"${key}\"`);\n }\n }\n }\n }\n\n if (problems.length > 0) throw new BrokerConfigError(sourcePath, problems.join(\"; \"));\n\n return {\n security,\n sourcePath,\n version: createHash(\"sha256\").update(raw!).digest(\"hex\").slice(0, 12),\n credentials,\n };\n}\n\n/**\n * A config file was designated or found, and could not be used.\n *\n * Thrown rather than logged: starting with an empty config instead would start\n * a broker with no authentication and no authorization at all.\n */\nexport class BrokerConfigError extends Error {\n constructor(\n public readonly sourcePath: string,\n public readonly detail: string\n ) {\n super(\n `[mcp-broker] Cannot use the config file at ${sourcePath}: ${detail}. ` +\n `The broker refuses to start rather than run without the security settings that file may hold. ` +\n `Fix the file, or point MCP_BROKER_CONFIG at a valid one.`\n );\n this.name = \"BrokerConfigError\";\n }\n}\n\n/**\n * Loads the broker config from a JSON file.\n *\n * Discovery order:\n * 1. The `path` argument when provided (explicit override).\n * 2. The `MCP_BROKER_CONFIG` env var.\n * 3. `./.mcp-broker/config.json` relative to `process.cwd()`.\n * 4. `./mcp-broker.config.json` relative to `process.cwd()` (legacy layout ,\n * a deprecation warning is written to stderr).\n *\n * When no file is found by discovery (steps 3 and 4), returns the built-in\n * empty config with `baseDir = process.cwd()`.\n *\n * Fails closed otherwise: throws a {@link BrokerConfigError} when a file was\n * designated (steps 1 and 2) but does not exist, or when the file that was\n * found cannot be read, is not valid JSON, or is not a JSON object. This used\n * to log a warning and return the empty config, and the empty config is a\n * broker with no authentication and no authorization: one stray comma in a\n * secured deployment's config opened every slot to everyone.\n *\n * Paths inside the config file are intended to be resolved against\n * {@link ILoadedBrokerConfig.baseDir} by the consumer.\n */\nexport function loadBrokerConfig(path?: string): ILoadedBrokerConfig {\n const cwd = process.cwd();\n const envPath = process.env[\"MCP_BROKER_CONFIG\"];\n\n let sourcePath: string | null = null;\n\n if (path) {\n sourcePath = resolve(cwd, path);\n } else if (envPath) {\n sourcePath = resolve(cwd, envPath);\n } else {\n const modern = resolve(cwd, DEFAULT_CONFIG_DIR, DEFAULT_CONFIG_FILENAME);\n const legacy = resolve(cwd, LEGACY_CONFIG_FILENAME);\n if (existsSync(modern)) {\n sourcePath = modern;\n } else if (existsSync(legacy)) {\n sourcePath = legacy;\n process.stderr.write(\n `[mcp-broker] Using legacy config at ${legacy}. ` + `Move it to ${resolve(cwd, DEFAULT_CONFIG_DIR, DEFAULT_CONFIG_FILENAME)} ` + `to silence this warning.\\n`\n );\n }\n }\n\n if (!sourcePath) {\n return { config: {}, baseDir: cwd, sourcePath: null };\n }\n if (!existsSync(sourcePath)) {\n const origin = path ? \"the path given to loadBrokerConfig()\" : \"MCP_BROKER_CONFIG\";\n throw new BrokerConfigError(sourcePath, `the file designated by ${origin} does not exist`);\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(readFileSync(sourcePath, \"utf-8\")) as unknown;\n } catch (err) {\n throw new BrokerConfigError(sourcePath, (err as Error).message);\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new BrokerConfigError(sourcePath, \"the top-level value must be a JSON object\");\n }\n return { config: parsed as IBrokerConfig, baseDir: dirname(sourcePath), sourcePath };\n}\n\n/**\n * Outcome of {@link resolveOpenTarget}. Exactly one of the three states holds:\n *\n * - `{ url: null, path: null }` and no `error`: nothing should be opened.\n * - `{ url, path }`: open `url`; `path` is what a static mount has to cover.\n * - `{ url: null, path: null, error }`: the value was refused, `error` is a\n * sentence to print verbatim that names both the fault and the fix.\n */\nexport interface IOpenTargetResolution {\n /** Absolute URL to hand to the platform opener, or `null` to open nothing. */\n url: string | null;\n /** Path portion of {@link url} (always starts with `/`), or `null`. */\n path: string | null;\n /** Set when the raw value was refused. Human-readable, names the fix. */\n error?: string;\n}\n\n/**\n * Resolves `www.open` / `MCP_BROKER_OPEN` into an absolute URL to launch.\n *\n * Lives here rather than in `bin.ts` because `bin.ts` starts a server the\n * moment it is imported, so nothing in it can be unit-tested.\n *\n * Accepted forms (leading/trailing whitespace is trimmed):\n *\n * | `raw` | result |\n * |----------------------------|-------------------------------------------|\n * | `undefined`, `false`, `\"\"`, `\"0\"`, `\"false\"` | open nothing |\n * | `true`, `\"1\"`, `\"true\"` | `<baseUrl>/` |\n * | `\"/app/\"`, `\"/index.html\"` | resolved against `baseUrl` |\n * | `\"http://localhost:3000/x\"`| passed through when the origin is `baseUrl`'s |\n * | anything else | refused, with `error` explaining why |\n *\n * Two refusals are security-load-bearing rather than pedantic:\n *\n * - **A foreign origin is refused.** Auto-opening is a startup convenience, and\n * a config file (or an env var inherited from a parent process) that can make\n * the broker launch a browser at an arbitrary site is a phishing primitive\n * with no upside: nothing about starting a broker requires visiting another\n * host. Open it yourself, or point `open` at a page this broker serves.\n * - **`//host/path` is refused** even though it starts with `/`: it is a\n * protocol-relative URL, so `new URL(\"//evil.example/x\", base)` resolves to\n * `evil.example` and a naive \"starts with a slash so it is local\" test lets\n * it through.\n *\n * Anything that is neither is refused rather than forwarded, because the\n * platform opener performs no validation of its own: a typo'd relative path is\n * handed to the shell and can launch a local file or a registered application.\n *\n * @param raw The configured value (`config.www.open`) or the raw env string.\n * @param baseUrl Origin this broker is reachable at, e.g. `http://localhost:3000`.\n */\nexport function resolveOpenTarget(raw: boolean | string | undefined | null, baseUrl: string): IOpenTargetResolution {\n const nothing: IOpenTargetResolution = { url: null, path: null };\n\n if (raw === undefined || raw === null || raw === false) return nothing;\n if (raw === true) return resolveOpenTarget(\"/\", baseUrl);\n\n const value = String(raw).trim();\n if (value === \"\" || value === \"0\" || value === \"false\") return nothing;\n if (value === \"1\" || value === \"true\") return resolveOpenTarget(\"/\", baseUrl);\n\n const refuse = (why: string): IOpenTargetResolution => ({\n url: null,\n path: null,\n error:\n `${why} Set it to true (or \"1\") for the broker root, to a path on this broker such as \"/app/index.html\", ` +\n `or to an absolute URL on ${baseUrl}. Leave it out to open nothing.`,\n });\n\n // Protocol-relative: starts with a slash but resolves off-origin.\n if (value.startsWith(\"//\")) {\n return refuse(`Refusing to open \"${value}\": a value starting with \"//\" is a protocol-relative URL and points at another host, not at this broker.`);\n }\n\n // Only two spellings are accepted, so that a bare word (almost always a\n // typo) is reported rather than silently resolved onto the broker root.\n const isAbsolutePath = value.startsWith(\"/\");\n const hasScheme = /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(value);\n if (!isAbsolutePath && !hasScheme) {\n return refuse(`Refusing to open \"${value}\": it is neither a path starting with \"/\" nor an absolute http(s) URL.`);\n }\n\n let resolved: URL;\n try {\n resolved = new URL(value, baseUrl);\n } catch {\n return refuse(`Refusing to open \"${value}\": it is not a valid path or URL.`);\n }\n\n if (hasScheme) {\n // Decide on the parsed form, not on the raw string: `localhost:3000/x`\n // looks like a host but parses with the scheme `localhost:`.\n if (resolved.protocol !== \"http:\" && resolved.protocol !== \"https:\") {\n return refuse(`Refusing to open \"${value}\": only http and https URLs are opened, and \"${resolved.protocol}\" is neither.`);\n }\n const base = new URL(baseUrl);\n if (resolved.origin !== base.origin) {\n return refuse(`Refusing to open \"${value}\": it points at ${resolved.origin}, which is not this broker (${base.origin}).`);\n }\n }\n\n return { url: resolved.toString(), path: resolved.pathname };\n}\n\n/** @deprecated Use {@link IBrokerAuthConfig}. */\nexport type BrokerAuthConfig = IBrokerAuthConfig;\n\n/** @deprecated Use {@link IBrokerConfig}. */\nexport type BrokerConfig = IBrokerConfig;\n\n/** @deprecated Use {@link ILoadedBrokerConfig}. */\nexport type LoadedBrokerConfig = ILoadedBrokerConfig;\n"]}
1
+ {"version":3,"sources":["../src/mcpb/mcpb.unzip.ts","../src/mcpb/mcpb.loader.ts","../src/config.ts"],"names":["dirname","resolve","readFileSync","existsSync"],"mappings":";;;;;;;AAiBA,IAAM,cAAA,GAAiB,SAAA;AACvB,IAAM,wBAAA,GAA2B,QAAA;AACjC,IAAM,sBAAA,GAAyB,QAAA;AAG/B,SAAS,SAAS,GAAA,EAAqB;AAEnC,EAAA,MAAM,SAAS,IAAA,CAAK,GAAA,CAAI,GAAG,GAAA,CAAI,MAAA,GAAS,KAAK,KAAM,CAAA;AACnD,EAAA,KAAA,IAAS,MAAM,GAAA,CAAI,MAAA,GAAS,EAAA,EAAI,GAAA,IAAO,QAAQ,GAAA,E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W,QAAA,CAAS,aAAa,QAAA,EAAU;AACjE,MAAA,OAAO,OAAO,CAAA,kBAAA,EAAqB,KAAK,CAAA,6CAAA,EAAgD,QAAA,CAAS,QAAQ,CAAA,aAAA,CAAe,CAAA;AAAA,IAC5H;AACA,IAAA,MAAM,IAAA,GAAO,IAAI,GAAA,CAAI,OAAO,CAAA;AAC5B,IAAA,IAAI,QAAA,CAAS,MAAA,KAAW,IAAA,CAAK,MAAA,EAAQ;AACjC,MAAA,OAAO,MAAA,CAAO,qBAAqB,KAAK,CAAA,gBAAA,EAAmB,SAAS,MAAM,CAAA,4BAAA,EAA+B,IAAA,CAAK,MAAM,CAAA,EAAA,CAAI,CAAA;AAAA,IAC5H;AAAA,EACJ;AAEA,EAAA,OAAO,EAAE,GAAA,EAAK,QAAA,CAAS,UAAS,EAAG,IAAA,EAAM,SAAS,QAAA,EAAS;AAC/D","file":"chunk-2GDTE7BA.js","sourcesContent":["/**\n * Minimal ZIP extractor for `.mcpb` bundles, built on `node:zlib` only.\n *\n * A `.mcpb` bundle is an ordinary ZIP archive. The broker deliberately avoids\n * the `@anthropic-ai/mcpb` package so it stays compatible with the format\n * without being coupled to Anthropic's tooling, hence this small reader.\n *\n * Supports the two compression methods used in practice: stored (0) and\n * deflate (8). ZIP64 archives are rejected with a clear error (`.mcpb` bundles\n * are small and never need it). Any trailing bytes after the End Of Central\n * Directory record (e.g. a native PKCS#7 signature block) are ignored, since\n * extraction is driven entirely by the central directory.\n */\nimport { mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, isAbsolute, relative, resolve } from \"node:path\";\nimport { inflateRawSync } from \"node:zlib\";\n\nconst EOCD_SIGNATURE = 0x06054b50;\nconst CENTRAL_HEADER_SIGNATURE = 0x02014b50;\nconst LOCAL_HEADER_SIGNATURE = 0x04034b50;\n\n/** Locates the End Of Central Directory record by scanning backwards. */\nfunction findEocd(buf: Buffer): number {\n // The EOCD is 22 bytes plus a comment of up to 65535 bytes.\n const minPos = Math.max(0, buf.length - 22 - 0xffff);\n for (let pos = buf.length - 22; pos >= minPos; pos--) {\n if (buf.readUInt32LE(pos) === EOCD_SIGNATURE) return pos;\n }\n throw new Error(\"not a ZIP archive (no End Of Central Directory record found)\");\n}\n\n/**\n * Extracts every entry of the `.mcpb` archive at `mcpbPath` into `destDir`.\n * `destDir` is created if missing. Entries whose resolved path would escape\n * `destDir` (zip-slip) are rejected.\n */\nexport function unzipMcpb(mcpbPath: string, destDir: string): void {\n const buf = readFileSync(mcpbPath);\n const eocd = findEocd(buf);\n\n const totalEntries = buf.readUInt16LE(eocd + 10);\n const centralDirOffset = buf.readUInt32LE(eocd + 16);\n if (centralDirOffset === 0xffffffff || totalEntries === 0xffff) {\n throw new Error(\"ZIP64 archives are not supported\");\n }\n\n const absDest = resolve(destDir);\n mkdirSync(absDest, { recursive: true });\n\n let pos = centralDirOffset;\n for (let i = 0; i < totalEntries; i++) {\n if (buf.readUInt32LE(pos) !== CENTRAL_HEADER_SIGNATURE) {\n throw new Error(`corrupt ZIP: bad central directory header at offset ${pos}`);\n }\n const method = buf.readUInt16LE(pos + 10);\n const compressedSize = buf.readUInt32LE(pos + 20);\n const uncompressedSize = buf.readUInt32LE(pos + 24);\n const nameLen = buf.readUInt16LE(pos + 28);\n const extraLen = buf.readUInt16LE(pos + 30);\n const commentLen = buf.readUInt16LE(pos + 32);\n const localHeaderOffset = buf.readUInt32LE(pos + 42);\n const name = buf.toString(\"utf8\", pos + 46, pos + 46 + nameLen);\n pos += 46 + nameLen + extraLen + commentLen;\n\n if (compressedSize === 0xffffffff || uncompressedSize === 0xffffffff || localHeaderOffset === 0xffffffff) {\n throw new Error(\"ZIP64 archives are not supported\");\n }\n\n // Resolve the destination path and reject zip-slip escapes.\n const target = resolve(absDest, name);\n const rel = relative(absDest, target);\n if (rel.startsWith(\"..\") || isAbsolute(rel)) {\n throw new Error(`unsafe ZIP entry path (zip-slip): ${name}`);\n }\n\n // Directory entry.\n if (name.endsWith(\"/\")) {\n mkdirSync(target, { recursive: true });\n continue;\n }\n\n // Parse the local header to locate the entry's data.\n if (buf.readUInt32LE(localHeaderOffset) !== LOCAL_HEADER_SIGNATURE) {\n throw new Error(`corrupt ZIP: bad local header for \"${name}\"`);\n }\n const localNameLen = buf.readUInt16LE(localHeaderOffset + 26);\n const localExtraLen = buf.readUInt16LE(localHeaderOffset + 28);\n const dataStart = localHeaderOffset + 30 + localNameLen + localExtraLen;\n const compressed = buf.subarray(dataStart, dataStart + compressedSize);\n\n let data: Buffer;\n if (method === 0) {\n data = compressed;\n } else if (method === 8) {\n data = inflateRawSync(compressed);\n } else {\n throw new Error(`unsupported ZIP compression method ${method} for \"${name}\"`);\n }\n\n mkdirSync(dirname(target), { recursive: true });\n writeFileSync(target, data);\n }\n}\n","/**\n * Loads a local `.mcpb` bundle into an {@link IStdioUpstreamConfig}.\n *\n * A `.mcpb` bundle is a ZIP holding a `manifest.json` whose `server.mcp_config`\n * describes a stdio MCP server process. The broker:\n *\n * 1. verifies a **detached signature** of the `.mcpb` file against a trusted\n * public key (PEM), integrity *and* provenance, using `node:crypto` only;\n * 2. unpacks the archive;\n * 3. reads the manifest, expands the `mcp_config` placeholders, and produces a\n * `IStdioUpstreamConfig` that the existing upstream wiring spawns.\n *\n * The broker stays compatible with the `.mcpb` format without depending on the\n * `@anthropic-ai/mcpb` package: the bundle's *own* (native PKCS#7) signature is\n * never parsed: the detached signature layer is the broker's trust anchor.\n *\n * Any failure (missing files, bad signature, malformed manifest, missing\n * `user_config` value) is logged and yields `null`: the bundle is refused and\n * no process is ever spawned. Never auto-runs an unverified bundle.\n */\nimport { createPublicKey, verify, X509Certificate, type KeyObject } from \"node:crypto\";\nimport { existsSync, readFileSync, rmSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join, resolve, sep } from \"node:path\";\nimport { unzipMcpb } from \"./mcpb.unzip\";\nimport type { IStdioUpstreamConfig } from \"../stdio.upstream\";\n\n/** A `.mcpb` bundle entry from the broker config file. */\nexport interface IMcpbBundleConfig {\n /** Provider slot name the bundle is bound to. */\n name: string;\n /** Path to the `.mcpb` file. */\n path: string;\n /** Path to the trusted public key (PEM) verifying the detached signature. */\n publicKey: string;\n /** Path to the detached signature file. Defaults to `<path>.sig`. */\n signature?: string;\n /** Values substituted into the manifest's `${user_config.*}` placeholders. */\n userConfig?: Record<string, string | number | boolean | Array<string | number>>;\n /** When `false`, the bundle stays out of the `_all` aggregate slot. Defaults to `true`. */\n aggregate?: boolean;\n}\n\ninterface IMcpConfig {\n command?: string;\n args?: string[];\n env?: Record<string, string>;\n platform_overrides?: Record<string, { command?: string; args?: string[]; env?: Record<string, string> }>;\n}\n\n/** Loads a PEM that holds either an X.509 certificate or a bare public key. */\nfunction loadPublicKey(pem: string): KeyObject {\n if (pem.includes(\"BEGIN CERTIFICATE\")) {\n return new X509Certificate(pem).publicKey;\n }\n return createPublicKey(pem);\n}\n\n/** Verifies the detached `signature` of `data` against `publicKey`. */\nfunction verifyDetachedSignature(data: Buffer, signature: Buffer, publicKey: KeyObject): boolean {\n // Ed25519/Ed448 are used without a separate hash algorithm; RSA/EC need one.\n const keyType = publicKey.asymmetricKeyType;\n const algorithm = keyType === \"ed25519\" || keyType === \"ed448\" ? null : \"sha256\";\n return verify(algorithm, data, publicKey, signature);\n}\n\n/** Resolves a single `${...}` placeholder key, or `undefined` when unknown. */\nfunction resolvePlaceholder(key: string, dirname: string, userConfig: IMcpbBundleConfig[\"userConfig\"]): string | number | boolean | Array<string | number> | undefined {\n if (key === \"__dirname\") return dirname;\n if (key === \"HOME\") return homedir();\n if (key === \"DESKTOP\") return join(homedir(), \"Desktop\");\n if (key === \"DOCUMENTS\") return join(homedir(), \"Documents\");\n if (key === \"DOWNLOADS\") return join(homedir(), \"Downloads\");\n if (key === \"pathSeparator\" || key === \"/\") return sep;\n if (key.startsWith(\"user_config.\")) {\n const name = key.slice(\"user_config.\".length);\n const value = userConfig?.[name];\n if (value === undefined) throw new Error(`missing user_config value: \"${name}\"`);\n return value;\n }\n return undefined;\n}\n\n/** Expands placeholders in a scalar string (command, env value). */\nfunction expandScalar(input: string, dirname: string, userConfig: IMcpbBundleConfig[\"userConfig\"]): string {\n return input.replace(/\\$\\{([^}]+)\\}/g, (match, key: string) => {\n const value = resolvePlaceholder(key, dirname, userConfig);\n if (value === undefined) return match; // unknown placeholder, leave verbatim\n if (Array.isArray(value)) throw new Error(`placeholder \"\\${${key}}\" is multi-valued and cannot be used here`);\n return String(value);\n });\n}\n\n/** Expands one manifest argument; a standalone multi-valued placeholder spreads. */\nfunction expandArg(arg: string, dirname: string, userConfig: IMcpbBundleConfig[\"userConfig\"]): string[] {\n const standalone = /^\\$\\{(user_config\\.[^}]+)\\}$/.exec(arg);\n if (standalone) {\n const value = resolvePlaceholder(standalone[1], dirname, userConfig);\n if (Array.isArray(value)) return value.map(String);\n return [String(value)];\n }\n return [expandScalar(arg, dirname, userConfig)];\n}\n\n/**\n * Verifies, unpacks and resolves a `.mcpb` bundle into an `IStdioUpstreamConfig`.\n *\n * @param cfg The bundle entry from the broker config.\n * @param baseDir Directory the bundle paths are resolved against.\n * @returns A ready upstream config, or `null` when the bundle is refused.\n */\nexport async function loadMcpbBundle(cfg: IMcpbBundleConfig, baseDir: string): Promise<IStdioUpstreamConfig | null> {\n const tag = `[mcp-broker] mcpb bundle \"${cfg.name}\"`;\n try {\n const mcpbPath = resolve(baseDir, cfg.path);\n const publicKeyPath = resolve(baseDir, cfg.publicKey);\n const signaturePath = cfg.signature ? resolve(baseDir, cfg.signature) : `${mcpbPath}.sig`;\n\n for (const [label, file] of [\n [\"bundle\", mcpbPath],\n [\"public key\", publicKeyPath],\n [\"signature\", signaturePath],\n ] as const) {\n if (!existsSync(file)) {\n console.error(`${tag}: ${label} file not found at ${file}, bundle refused.`);\n return null;\n }\n }\n\n // ── Signature verification (mandatory) ──────────────────────────────\n const bundleBytes = readFileSync(mcpbPath);\n const signatureBytes = readFileSync(signaturePath);\n const publicKey = loadPublicKey(readFileSync(publicKeyPath, \"utf8\"));\n if (!verifyDetachedSignature(bundleBytes, signatureBytes, publicKey)) {\n console.error(`${tag}: detached signature is invalid for the configured public key, bundle refused.`);\n return null;\n }\n\n // ── Unpack ──────────────────────────────────────────────────────────\n const outputDir = resolve(baseDir, \".cache\", \"mcpb\", cfg.name);\n rmSync(outputDir, { recursive: true, force: true });\n unzipMcpb(mcpbPath, outputDir);\n\n // ── Manifest → mcp_config ───────────────────────────────────────────\n const manifestPath = join(outputDir, \"manifest.json\");\n if (!existsSync(manifestPath)) {\n console.error(`${tag}: manifest.json missing inside the bundle, bundle refused.`);\n return null;\n }\n const manifest = JSON.parse(readFileSync(manifestPath, \"utf8\")) as { server?: { mcp_config?: IMcpConfig } };\n const mcpConfig = manifest.server?.mcp_config;\n if (!mcpConfig) {\n console.error(`${tag}: manifest has no server.mcp_config, bundle refused.`);\n return null;\n }\n\n // Platform-specific overrides replace the base fields when present.\n const override = mcpConfig.platform_overrides?.[process.platform];\n const command = override?.command ?? mcpConfig.command;\n const rawArgs = override?.args ?? mcpConfig.args ?? [];\n const rawEnv = { ...mcpConfig.env, ...override?.env };\n if (!command) {\n console.error(`${tag}: manifest mcp_config has no command, bundle refused.`);\n return null;\n }\n\n // ── Placeholder expansion ───────────────────────────────────────────\n const expandedCommand = expandScalar(command, outputDir, cfg.userConfig);\n const expandedArgs = rawArgs.flatMap((arg) => expandArg(arg, outputDir, cfg.userConfig));\n const expandedEnv: Record<string, string> = {};\n for (const [key, value] of Object.entries(rawEnv)) {\n expandedEnv[key] = expandScalar(value, outputDir, cfg.userConfig);\n }\n\n return {\n name: cfg.name,\n command: expandedCommand,\n args: expandedArgs,\n env: Object.keys(expandedEnv).length > 0 ? expandedEnv : undefined,\n aggregate: cfg.aggregate ?? true,\n };\n } catch (err) {\n console.error(`${tag}: ${(err as Error).message}, bundle refused.`);\n return null;\n }\n}\n\n/** @deprecated Use {@link IMcpbBundleConfig}. */\nexport type McpbBundleConfig = IMcpbBundleConfig;\n","import { validateLimitsConfig, type ILimitsConfig } from \"./limits/controller\";\nimport { createHash } from \"node:crypto\";\nimport { existsSync, readFileSync } from \"node:fs\";\nimport { dirname, resolve } from \"node:path\";\nimport type { IAuthorizationPolicyConfig } from \"./authorization/index\";\nimport type { IProviderCredential } from \"./auth/provider.auth\";\nimport type { IProtectedSlot } from \"./authority/declaration\";\n\nexport interface IBrokerAuthConfig extends IAuthorizationPolicyConfig {\n /** Master switch. Absent/`false` keeps the broker unauthenticated. */\n enabled?: boolean;\n /** Public origin the broker is reached at (e.g. `https://mcp.example.com`). */\n publicBaseUrl?: string;\n /** Authorization server issuer URL(s) advertised in the metadata. */\n authorizationServers?: string[];\n /** URL of the authorization server's JWKS document. */\n jwks?: string;\n /** Expected token issuer. Defaults to the sole `authorizationServers` entry. */\n issuer?: string;\n /** Scopes advertised in the metadata `scopes_supported`. */\n scopesSupported?: string[];\n /** Baseline scope(s) required to reach any slot. */\n requiredScopes?: string[];\n /** Per-slot required-scope overrides (e.g. an admin scope for `_broker`). */\n perSlotScopes?: Record<string, string[]>;\n /**\n * Per-provider scope requirements for the `_all` aggregate. Deprecated in\n * favor of hierarchical policy assignments.\n */\n providerScopes?: Record<string, string[]>;\n /**\n * Shared secret every provider must present to occupy a slot. Independent\n * of client authorization.\n */\n providerSecret?: string;\n}\n\n/**\n * Shape of the optional JSON config file consumed by `bin.ts` at startup.\n * Every field is optional. Environment variables (`MCP_BROKER_*`) always win\n * over file values, and file values win over the built-in defaults.\n *\n * @example\n * ```json\n * {\n * \"port\": 3001,\n * \"locale\": \"fr\",\n * \"tls\": { \"cert\": \"certs/cert.pem\", \"key\": \"certs/key.pem\" },\n * \"stdioUpstreams\": [\n * { \"name\": \"fs\", \"command\": \"npx\", \"args\": [\"-y\", \"@modelcontextprotocol/server-filesystem\", \"/data\"] }\n * ]\n * }\n * ```\n */\nexport interface IBrokerConfig {\n /** TCP port. Maps to `MCP_BROKER_PORT`. */\n port?: number;\n\n /** Bind host. Maps to `MCP_BROKER_HOST`. */\n host?: string;\n\n /** Force protocol (`http`/`https`) regardless of cert presence. Maps to `MCP_BROKER_PROTOCOL`. */\n protocol?: \"http\" | \"https\";\n\n /** Locale fed to the broker grammar resolver. Maps to `MCP_BROKER_LOCALE`. */\n locale?: string;\n\n /** Bridge stdin/stdout for a Claude-Desktop-style client. Maps to `MCP_BROKER_STDIO_PROVIDER`. */\n stdioProvider?: string;\n\n /**\n * Logical broker name reported by `broker_info`.\n *\n * **Library-only today.** `WsTunnel` honors it\n * (`IWsTunnelOptions.brokerName`), but `WsTunnelBuilder` has no\n * `withBrokerName()`, so the CLI cannot forward it and setting it in\n * `config.json` has no effect. Set it through the programmatic API until\n * the setter exists.\n */\n brokerName?: string;\n\n /**\n * How often (ms) the broker pings each connected provider socket to check\n * it is still there. `0` disables the heartbeat. Maps to\n * `MCP_BROKER_PROVIDER_HEARTBEAT_MS`.\n *\n * A provider that misses a full interval is terminated and its slot freed,\n * which is what stops a half-open socket (a killed browser tab, a slept\n * laptop, a dropped VPN) from holding a slot for the ~2 hours the OS takes\n * to give up on the TCP connection, refusing every reconnect meanwhile.\n *\n * @default 30000\n */\n providerHeartbeatIntervalMs?: number;\n\n /**\n * How long (ms) the broker waits for a provider to answer one request\n * before failing it with a JSON-RPC error naming the slot. `0` disables the\n * deadline. Maps to `MCP_BROKER_PROVIDER_REQUEST_TIMEOUT_MS`.\n *\n * Raise it if you host genuinely long-running tools; without it a provider\n * that stays connected and never answers (a throttled background browser\n * tab is the ordinary case) leaves the caller waiting forever.\n *\n * @default 60000\n */\n providerRequestTimeoutMs?: number;\n\n /**\n * Bounds on `resources/subscribe` bookkeeping. Each field maps to an env\n * var: `MCP_BROKER_MAX_SUBSCRIPTIONS_PER_CLIENT` (default 64),\n * `MCP_BROKER_MAX_SUBSCRIPTIONS_PER_SLOT` (default 1024),\n * `MCP_BROKER_MAX_RESOURCE_URI_LENGTH` (default 2048).\n */\n resourceSubscriptions?: {\n maxSubscriptionsPerClient?: number;\n maxSubscriptionsPerSlot?: number;\n maxResourceUriLength?: number;\n };\n\n /** Optional OTLP/HTTP trace export for provider telemetry notifications. */\n telemetry?: {\n /** Full traces endpoint, usually http://collector:4318/v1/traces. */\n otlpHttpEndpoint: string;\n headers?: Record<string, string>;\n timeoutMs?: number;\n serviceNamespace?: string;\n maxFrameBytes?: number;\n queueCapacity?: number;\n batchSize?: number;\n maxAttributes?: number;\n maxEvents?: number;\n };\n\n /**\n * What happens when a provider connects to a slot another socket already\n * holds. Maps to `MCP_BROKER_PROVIDER_TAKEOVER`.\n *\n * - `\"reject\"`: the incumbent always keeps the slot.\n * - `\"liveness\"` (default): the incumbent keeps it only while it answers\n * the heartbeat.\n * - `\"always\"`: the newcomer wins, but only when provider authentication is\n * configured and it authenticated as the same principal as the incumbent.\n * Without provider auth the broker falls back to `\"liveness\"` and says so,\n * because unconditional takeover would let anyone who can reach the URL\n * evict the real provider.\n *\n * @default \"liveness\"\n */\n providerTakeover?: \"reject\" | \"liveness\" | \"always\";\n\n /**\n * Browser origins allowed to reach `/<slot>/mcp`.\n *\n * Absent means no browser origin is accepted: a request carrying an\n * `Origin` header gets `403`, one carrying none (Claude Desktop, MCP\n * Inspector, any server-side SDK) always passes. The MCP specification asks\n * for this check, since without it any web page loaded in a browser that\n * can reach the broker could drive it.\n *\n * An array lists origins matched **exactly**. An object supplies a regular\n * expression tested against the whole `Origin` header. Also maps to\n * `MCP_BROKER_ALLOWED_ORIGINS` (comma-separated list form only; a pattern\n * needs the config file).\n *\n * @example\n * ```json\n * { \"allowedOrigins\": [\"https://app.example.com\", \"http://localhost:5173\"] }\n * { \"allowedOrigins\": { \"pattern\": \"^https://[a-z0-9-]+\\\\.example\\\\.com$\" } }\n * ```\n */\n allowedOrigins?: string[] | { pattern: string; flags?: string };\n\n /**\n * OAuth 2.1 resource-server authorization. When `enabled` is `true`, every\n * HTTP client request to a slot must carry a valid `Authorization: Bearer`\n * token issued for that slot, and the broker publishes Protected Resource\n * Metadata (RFC 9728). Absent/`false` ⇒ no authentication (trusted-network\n * mode, the historical behavior).\n *\n * Scalars also map to env vars (which win): `MCP_BROKER_AUTH_ENABLED`,\n * `MCP_BROKER_PUBLIC_BASE_URL`, `MCP_BROKER_JWKS`, `MCP_BROKER_ISSUER`.\n *\n * Deprecated here: put it in the security file ({@link securityFile}).\n * The broker refuses to start when both carry one.\n */\n auth?: IBrokerAuthConfig;\n\n /**\n * Path to the security file, resolved against this file's directory. It\n * holds `auth`, the `providers` table and `authorization.protectedSlots`,\n * so topology and security are written, read and protected separately.\n * Maps to `MCP_BROKER_SECURITY_FILE` (resolved against the cwd), which wins.\n */\n securityFile?: string;\n\n /**\n * URL paths (override the defaults). Every key is also settable through an\n * environment variable, which wins.\n *\n * Changing one moves an endpoint for **every** peer: a provider SDK, a\n * client, and the startup banner all have to agree. The two provider paths\n * are not interchangeable, they carry different framing:\n * `provider` is a prefix (`<provider>/<slot>`) speaking plain JSON-RPC\n * frames (`DirectTransport`), `providers` is matched exactly and speaks\n * multiplex envelopes (`MultiplexTransport`).\n */\n paths?: {\n /** Prefix for one-slot-per-socket provider connections. Maps to `MCP_BROKER_PROVIDER_PATH`. @default \"/provider\" */\n provider?: string;\n /** Exact path for multiplexed provider connections. Maps to `MCP_BROKER_PROVIDERS_PATH`. @default \"/providers\" */\n providers?: string;\n /** Prefix raw-WebSocket clients connect to. Maps to `MCP_BROKER_CLIENT_PATH`. @default \"/\" */\n client?: string;\n /** Per-slot suffix for the Streamable HTTP transport. Maps to `MCP_BROKER_MCP_PATH`. @default \"/mcp\" */\n mcp?: string;\n /** Per-slot suffix for the legacy SSE stream (GET). Maps to `MCP_BROKER_SSE_PATH`. @default \"/sse\" */\n sse?: string;\n /** Per-slot suffix for legacy SSE JSON-RPC posts. Maps to `MCP_BROKER_MESSAGES_PATH`. @default \"/messages\" */\n messages?: string;\n };\n\n /** TLS material as paths on disk. Resolved against the config file's directory. */\n tls?: {\n cert: string;\n key: string;\n };\n\n /**\n * Static-file serving alongside the JSON-RPC endpoints. JSON-RPC routes\n * always take precedence.\n */\n www?: {\n /**\n * Auto-launch the default browser on startup. Maps to `MCP_BROKER_OPEN`.\n *\n * - `false` / absent / `\"\"` / `\"0\"`: do not open anything.\n * - `true` / `\"1\"`: open the broker root, `<scheme>://localhost:<port>/`.\n * - a path (`\"/app/index.html\"`): open that page on this broker.\n * - an absolute URL on this broker's own origin: opened as given.\n *\n * A URL on any other origin is refused with a message, and so is any\n * other string. See {@link resolveOpenTarget} for why.\n *\n * The browser opens only when a static mount actually covers the\n * resolved path; otherwise the broker says which mounts exist instead of\n * launching a browser onto a 404.\n */\n open?: boolean | string;\n /** URL-prefix → directory mappings. Longest-prefix match wins. */\n mounts?: Array<{\n urlPrefix: string;\n dir: string;\n }>;\n };\n\n /** Stdio upstream providers spawned by the broker at startup. */\n stdioUpstreams?: Array<{\n name: string;\n command: string;\n args?: string[];\n env?: Record<string, string>;\n /** When `true`, the upstream joins the `_all` aggregate slot once connected. */\n aggregate?: boolean;\n }>;\n\n /**\n * Remote MCP servers the broker connects out to and exposes as provider\n * slots. Each entry is reached by URL (Streamable HTTP / SSE / WebSocket);\n * local servers should be shipped as `.mcpb` bundles instead.\n */\n mcpServers?: Array<{\n name: string;\n url: string;\n transport?: \"streamable-http\" | \"sse\" | \"websocket\";\n headers?: Record<string, string>;\n /** Defaults to `true`; set to `false` to exclude this upstream from the `_all` aggregate slot. */\n aggregate?: boolean;\n }>;\n\n /**\n * Local `.mcpb` bundles the broker loads at startup and runs as stdio\n * provider slots. A bundle is a ZIP with a `manifest.json`; the broker\n * verifies a detached signature against a trusted public key before\n * unpacking and spawning it.\n */\n mcpbBundles?: Array<{\n /** Provider slot name the bundle is bound to. */\n name: string;\n /** Path to the `.mcpb` file (resolved against the config file's directory). */\n path: string;\n /** Path to the trusted public key (PEM) used to verify the detached signature. */\n publicKey: string;\n /** Path to the detached signature file. Defaults to `<path>.sig`. */\n signature?: string;\n /** Values substituted into the manifest's `${user_config.*}` placeholders. */\n userConfig?: Record<string, string | number | boolean | Array<string | number>>;\n /** Defaults to `true`; set to `false` to exclude this bundle from the `_all` aggregate slot. */\n aggregate?: boolean;\n }>;\n}\n\n/**\n * Returned by {@link loadBrokerConfig}. The {@link config} is the parsed JSON;\n * {@link baseDir} is the directory used to resolve relative paths inside it\n * (the directory containing the config file when one was found, otherwise\n * `process.cwd()`).\n */\nexport interface ILoadedBrokerConfig {\n config: IBrokerConfig;\n baseDir: string;\n /** Absolute path of the config file that was loaded, or `null` if none. */\n sourcePath: string | null;\n}\n\n/** Default folder name (relative to `process.cwd()`) holding broker-local files. */\nexport const DEFAULT_CONFIG_DIR = \".mcp-broker\";\n\n/** Default config filename inside {@link DEFAULT_CONFIG_DIR}. */\nexport const DEFAULT_CONFIG_FILENAME = \"config.json\";\n\n/** Legacy flat config filename at the cwd root (pre-`.mcp-broker/` layout). */\nexport const LEGACY_CONFIG_FILENAME = \"mcp-broker.config.json\";\n\n/** One entry of the security file's `providers` table: the secret is named, never written. */\nexport interface ISecurityProviderEntry {\n /** Provider principal id. */\n id: string;\n /** Name of the environment variable holding this provider's secret. */\n secretEnv: string;\n /** Subjects this provider holds when it calls the broker as a client. */\n subjects?: string[];\n /** Resource patterns this provider may publish into; absent means all. */\n allowedResources?: string[];\n}\n\n/**\n * Shape of the security file: everything that decides who may do what, kept\n * apart from the topology in `config.json`.\n */\nexport interface ISecurityConfig {\n limits?: ILimitsConfig;\n /** The same block as `config.json`'s `auth`, minus `providerSecret` (use `MCP_BROKER_PROVIDER_SECRET`). */\n auth?: IBrokerAuthConfig;\n /** One identity per provider. */\n providers?: ISecurityProviderEntry[];\n authorization?: {\n /** Slots only one provider may call and one may publish, keyed by slot name. */\n protectedSlots?: Record<string, IProtectedSlot>;\n };\n}\n\n/** A loaded security file, with the secrets it names resolved from the environment. */\nexport interface ILoadedSecurityConfig {\n readonly security: ISecurityConfig;\n /** Absolute path of the file. */\n readonly sourcePath: string;\n /** First 12 hex digits of the file's SHA-256: what `policyVersion` starts with. */\n readonly version: string;\n /** The `providers` table, secrets resolved. */\n readonly credentials: readonly IProviderCredential[];\n}\n\nconst SECURITY_KEYS = new Set([\"$schema\", \"description\", \"auth\", \"providers\", \"authorization\", \"limits\"]);\n\n/**\n * Loads the security file named by `MCP_BROKER_SECURITY_FILE` or by\n * `config.securityFile`, or returns `null` when neither names one.\n *\n * Fails closed, like {@link loadBrokerConfig}: a designated file that is\n * missing, unreadable, not a JSON object, or inconsistent throws a\n * {@link BrokerConfigError}, and so does a provider whose secret variable is\n * unset. So does a `config.json` that still carries `auth` next to a security\n * file: picking one of the two silently would leave the operator guessing\n * which rules are in force.\n */\nexport function loadSecurityConfig(loaded: ILoadedBrokerConfig, env: NodeJS.ProcessEnv = process.env): ILoadedSecurityConfig | null {\n // Keys that only the security file may carry, refused in config.json\n // whether or not a security file exists: left there, they would be\n // ignored, and a protection the operator wrote would silently not exist.\n const misplaced = [\"providers\", \"authorization\", \"limits\"].filter((key) => Object.prototype.hasOwnProperty.call(loaded.config, key));\n if (misplaced.length > 0 && loaded.sourcePath) {\n throw new BrokerConfigError(\n loaded.sourcePath,\n `${misplaced.map((k) => `\"${k}\"`).join(\" and \")} belong in the security file (securityFile / MCP_BROKER_SECURITY_FILE), not in the config file`\n );\n }\n\n const envPath = env[\"MCP_BROKER_SECURITY_FILE\"];\n const sourcePath = envPath ? resolve(process.cwd(), envPath) : loaded.config.securityFile ? resolve(loaded.baseDir, loaded.config.securityFile) : null;\n if (!sourcePath) return null;\n\n if (!existsSync(sourcePath)) {\n throw new BrokerConfigError(sourcePath, `the security file designated by ${envPath ? \"MCP_BROKER_SECURITY_FILE\" : \"securityFile in the config file\"} does not exist`);\n }\n let raw: Buffer;\n let parsed: unknown;\n try {\n raw = readFileSync(sourcePath);\n parsed = JSON.parse(raw.toString(\"utf-8\")) as unknown;\n } catch (err) {\n throw new BrokerConfigError(sourcePath, (err as Error).message);\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new BrokerConfigError(sourcePath, \"the top-level value must be a JSON object\");\n }\n const security = parsed as ISecurityConfig;\n\n const problems: string[] = [];\n for (const key of Object.keys(security)) if (!SECURITY_KEYS.has(key)) problems.push(`unknown key \"${key}\"`);\n if (loaded.config.auth !== undefined) {\n problems.push(\n `the config file${loaded.sourcePath ? ` (${loaded.sourcePath})` : \"\"} also carries \"auth\"; move it into the security file, so there is one source of security settings`\n );\n }\n if (security.auth?.providerSecret !== undefined) {\n problems.push('\"auth.providerSecret\" would put a secret in clear in the file; set MCP_BROKER_PROVIDER_SECRET instead, or give each provider an entry in \"providers\"');\n }\n\n const credentials: IProviderCredential[] = [];\n if (security.providers !== undefined) {\n if (!Array.isArray(security.providers)) problems.push('\"providers\" must be an array');\n else {\n for (const [index, entry] of security.providers.entries()) {\n const label = `providers[${index}]`;\n if (typeof entry !== \"object\" || entry === null) {\n problems.push(`${label} must be an object`);\n continue;\n }\n for (const key of Object.keys(entry)) {\n if (key === \"secret\") problems.push(`${label}: \"secret\" would put a secret in clear in the file; name the environment variable that holds it in \"secretEnv\"`);\n else if (![\"id\", \"secretEnv\", \"subjects\", \"allowedResources\"].includes(key)) problems.push(`${label}: unknown key \"${key}\"`);\n }\n if (typeof entry.id !== \"string\" || entry.id.length === 0) problems.push(`${label}: \"id\" must be a non-empty string`);\n if (entry.subjects !== undefined && (!Array.isArray(entry.subjects) || entry.subjects.some((v) => typeof v !== \"string\")))\n problems.push(`${label}: \"subjects\" must be an array of strings`);\n if (entry.allowedResources !== undefined && (!Array.isArray(entry.allowedResources) || entry.allowedResources.some((v) => typeof v !== \"string\"))) {\n problems.push(`${label}: \"allowedResources\" must be an array of strings`);\n }\n if (typeof entry.secretEnv !== \"string\" || entry.secretEnv.length === 0) {\n problems.push(`${label}: \"secretEnv\" must name the environment variable holding this provider's secret`);\n continue;\n }\n const secret = env[entry.secretEnv];\n if (!secret) {\n problems.push(`${label} (\"${String(entry.id)}\"): the environment variable ${entry.secretEnv} is not set`);\n continue;\n }\n credentials.push({\n id: entry.id,\n secret,\n ...(entry.subjects !== undefined ? { subjects: entry.subjects } : {}),\n ...(entry.allowedResources !== undefined ? { allowedResources: entry.allowedResources } : {}),\n });\n }\n }\n }\n\n if (security.limits !== undefined) {\n try {\n validateLimitsConfig(security.limits);\n if (security.limits.storeFile) security.limits = { ...security.limits, storeFile: resolve(dirname(sourcePath), security.limits.storeFile) };\n } catch (error) {\n problems.push((error as Error).message);\n }\n }\n const authorization = security.authorization;\n if (authorization !== undefined) {\n if (typeof authorization !== \"object\" || authorization === null || Array.isArray(authorization)) problems.push('\"authorization\" must be an object');\n else {\n for (const key of Object.keys(authorization)) if (key !== \"protectedSlots\") problems.push(`authorization: unknown key \"${key}\"`);\n const slots = authorization.protectedSlots;\n if (slots !== undefined && (typeof slots !== \"object\" || slots === null || Array.isArray(slots)))\n problems.push('\"authorization.protectedSlots\" must be an object keyed by slot name');\n else if (slots) {\n for (const [slot, entry] of Object.entries(slots)) {\n if (typeof entry !== \"object\" || entry === null || Array.isArray(entry)) {\n problems.push(`authorization.protectedSlots[\"${slot}\"] must be { \"declaredBy\": \"<id>\", \"publishedBy\": \"<id>\" }`);\n continue;\n }\n for (const key of Object.keys(entry))\n if (key !== \"declaredBy\" && key !== \"publishedBy\") problems.push(`authorization.protectedSlots[\"${slot}\"]: unknown key \"${key}\"`);\n }\n }\n }\n }\n\n if (problems.length > 0) throw new BrokerConfigError(sourcePath, problems.join(\"; \"));\n\n return {\n security,\n sourcePath,\n version: createHash(\"sha256\").update(raw!).digest(\"hex\").slice(0, 12),\n credentials,\n };\n}\n\n/**\n * A config file was designated or found, and could not be used.\n *\n * Thrown rather than logged: starting with an empty config instead would start\n * a broker with no authentication and no authorization at all.\n */\nexport class BrokerConfigError extends Error {\n constructor(\n public readonly sourcePath: string,\n public readonly detail: string\n ) {\n super(\n `[mcp-broker] Cannot use the config file at ${sourcePath}: ${detail}. ` +\n `The broker refuses to start rather than run without the security settings that file may hold. ` +\n `Fix the file, or point MCP_BROKER_CONFIG at a valid one.`\n );\n this.name = \"BrokerConfigError\";\n }\n}\n\n/**\n * Loads the broker config from a JSON file.\n *\n * Discovery order:\n * 1. The `path` argument when provided (explicit override).\n * 2. The `MCP_BROKER_CONFIG` env var.\n * 3. `./.mcp-broker/config.json` relative to `process.cwd()`.\n * 4. `./mcp-broker.config.json` relative to `process.cwd()` (legacy layout ,\n * a deprecation warning is written to stderr).\n *\n * When no file is found by discovery (steps 3 and 4), returns the built-in\n * empty config with `baseDir = process.cwd()`.\n *\n * Fails closed otherwise: throws a {@link BrokerConfigError} when a file was\n * designated (steps 1 and 2) but does not exist, or when the file that was\n * found cannot be read, is not valid JSON, or is not a JSON object. This used\n * to log a warning and return the empty config, and the empty config is a\n * broker with no authentication and no authorization: one stray comma in a\n * secured deployment's config opened every slot to everyone.\n *\n * Paths inside the config file are intended to be resolved against\n * {@link ILoadedBrokerConfig.baseDir} by the consumer.\n */\nexport function loadBrokerConfig(path?: string): ILoadedBrokerConfig {\n const cwd = process.cwd();\n const envPath = process.env[\"MCP_BROKER_CONFIG\"];\n\n let sourcePath: string | null = null;\n\n if (path) {\n sourcePath = resolve(cwd, path);\n } else if (envPath) {\n sourcePath = resolve(cwd, envPath);\n } else {\n const modern = resolve(cwd, DEFAULT_CONFIG_DIR, DEFAULT_CONFIG_FILENAME);\n const legacy = resolve(cwd, LEGACY_CONFIG_FILENAME);\n if (existsSync(modern)) {\n sourcePath = modern;\n } else if (existsSync(legacy)) {\n sourcePath = legacy;\n process.stderr.write(\n `[mcp-broker] Using legacy config at ${legacy}. ` + `Move it to ${resolve(cwd, DEFAULT_CONFIG_DIR, DEFAULT_CONFIG_FILENAME)} ` + `to silence this warning.\\n`\n );\n }\n }\n\n if (!sourcePath) {\n return { config: {}, baseDir: cwd, sourcePath: null };\n }\n if (!existsSync(sourcePath)) {\n const origin = path ? \"the path given to loadBrokerConfig()\" : \"MCP_BROKER_CONFIG\";\n throw new BrokerConfigError(sourcePath, `the file designated by ${origin} does not exist`);\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(readFileSync(sourcePath, \"utf-8\")) as unknown;\n } catch (err) {\n throw new BrokerConfigError(sourcePath, (err as Error).message);\n }\n if (typeof parsed !== \"object\" || parsed === null || Array.isArray(parsed)) {\n throw new BrokerConfigError(sourcePath, \"the top-level value must be a JSON object\");\n }\n return { config: parsed as IBrokerConfig, baseDir: dirname(sourcePath), sourcePath };\n}\n\n/**\n * Outcome of {@link resolveOpenTarget}. Exactly one of the three states holds:\n *\n * - `{ url: null, path: null }` and no `error`: nothing should be opened.\n * - `{ url, path }`: open `url`; `path` is what a static mount has to cover.\n * - `{ url: null, path: null, error }`: the value was refused, `error` is a\n * sentence to print verbatim that names both the fault and the fix.\n */\nexport interface IOpenTargetResolution {\n /** Absolute URL to hand to the platform opener, or `null` to open nothing. */\n url: string | null;\n /** Path portion of {@link url} (always starts with `/`), or `null`. */\n path: string | null;\n /** Set when the raw value was refused. Human-readable, names the fix. */\n error?: string;\n}\n\n/**\n * Resolves `www.open` / `MCP_BROKER_OPEN` into an absolute URL to launch.\n *\n * Lives here rather than in `bin.ts` because `bin.ts` starts a server the\n * moment it is imported, so nothing in it can be unit-tested.\n *\n * Accepted forms (leading/trailing whitespace is trimmed):\n *\n * | `raw` | result |\n * |----------------------------|-------------------------------------------|\n * | `undefined`, `false`, `\"\"`, `\"0\"`, `\"false\"` | open nothing |\n * | `true`, `\"1\"`, `\"true\"` | `<baseUrl>/` |\n * | `\"/app/\"`, `\"/index.html\"` | resolved against `baseUrl` |\n * | `\"http://localhost:3000/x\"`| passed through when the origin is `baseUrl`'s |\n * | anything else | refused, with `error` explaining why |\n *\n * Two refusals are security-load-bearing rather than pedantic:\n *\n * - **A foreign origin is refused.** Auto-opening is a startup convenience, and\n * a config file (or an env var inherited from a parent process) that can make\n * the broker launch a browser at an arbitrary site is a phishing primitive\n * with no upside: nothing about starting a broker requires visiting another\n * host. Open it yourself, or point `open` at a page this broker serves.\n * - **`//host/path` is refused** even though it starts with `/`: it is a\n * protocol-relative URL, so `new URL(\"//evil.example/x\", base)` resolves to\n * `evil.example` and a naive \"starts with a slash so it is local\" test lets\n * it through.\n *\n * Anything that is neither is refused rather than forwarded, because the\n * platform opener performs no validation of its own: a typo'd relative path is\n * handed to the shell and can launch a local file or a registered application.\n *\n * @param raw The configured value (`config.www.open`) or the raw env string.\n * @param baseUrl Origin this broker is reachable at, e.g. `http://localhost:3000`.\n */\nexport function resolveOpenTarget(raw: boolean | string | undefined | null, baseUrl: string): IOpenTargetResolution {\n const nothing: IOpenTargetResolution = { url: null, path: null };\n\n if (raw === undefined || raw === null || raw === false) return nothing;\n if (raw === true) return resolveOpenTarget(\"/\", baseUrl);\n\n const value = String(raw).trim();\n if (value === \"\" || value === \"0\" || value === \"false\") return nothing;\n if (value === \"1\" || value === \"true\") return resolveOpenTarget(\"/\", baseUrl);\n\n const refuse = (why: string): IOpenTargetResolution => ({\n url: null,\n path: null,\n error:\n `${why} Set it to true (or \"1\") for the broker root, to a path on this broker such as \"/app/index.html\", ` +\n `or to an absolute URL on ${baseUrl}. Leave it out to open nothing.`,\n });\n\n // Protocol-relative: starts with a slash but resolves off-origin.\n if (value.startsWith(\"//\")) {\n return refuse(`Refusing to open \"${value}\": a value starting with \"//\" is a protocol-relative URL and points at another host, not at this broker.`);\n }\n\n // Only two spellings are accepted, so that a bare word (almost always a\n // typo) is reported rather than silently resolved onto the broker root.\n const isAbsolutePath = value.startsWith(\"/\");\n const hasScheme = /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(value);\n if (!isAbsolutePath && !hasScheme) {\n return refuse(`Refusing to open \"${value}\": it is neither a path starting with \"/\" nor an absolute http(s) URL.`);\n }\n\n let resolved: URL;\n try {\n resolved = new URL(value, baseUrl);\n } catch {\n return refuse(`Refusing to open \"${value}\": it is not a valid path or URL.`);\n }\n\n if (hasScheme) {\n // Decide on the parsed form, not on the raw string: `localhost:3000/x`\n // looks like a host but parses with the scheme `localhost:`.\n if (resolved.protocol !== \"http:\" && resolved.protocol !== \"https:\") {\n return refuse(`Refusing to open \"${value}\": only http and https URLs are opened, and \"${resolved.protocol}\" is neither.`);\n }\n const base = new URL(baseUrl);\n if (resolved.origin !== base.origin) {\n return refuse(`Refusing to open \"${value}\": it points at ${resolved.origin}, which is not this broker (${base.origin}).`);\n }\n }\n\n return { url: resolved.toString(), path: resolved.pathname };\n}\n\n/** @deprecated Use {@link IBrokerAuthConfig}. */\nexport type BrokerAuthConfig = IBrokerAuthConfig;\n\n/** @deprecated Use {@link IBrokerConfig}. */\nexport type BrokerConfig = IBrokerConfig;\n\n/** @deprecated Use {@link ILoadedBrokerConfig}. */\nexport type LoadedBrokerConfig = ILoadedBrokerConfig;\n"]}