diff --git a/CHANGELOG.md b/CHANGELOG.md index 33fe7043..f7029342 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,10 @@ All notable changes to this project will be documented in this file. The format - [#200](https://github.com/mohanagy/miftah/issues/200) Reworked the README into a task-oriented first-use guide with complete Claude Desktop setup, authentication-path selection, generic MCP onboarding, profile-management tools, native versus upstream-owned OAuth, dashboard lifecycle, everyday diagnostics/audit commands, and focused security-control guidance; corrected stale configuration-version guidance to identify v3 as current while preserving an explicit v1/v2 removal window. +### Fixed + +- [#217](https://github.com/mohanagy/miftah/issues/217) Windows STDIO launch now resolves only direct `.exe`/`.com` commands before the MCP SDK, rejects command shims and shell executables, and refuses npx-backed presets on Windows rather than silently falling back to `cmd.exe`. + ## [0.4.0] - 2026-07-23 ### Added diff --git a/README.md b/README.md index 26a8f5c6..88a327c0 100644 --- a/README.md +++ b/README.md @@ -53,6 +53,8 @@ Start with the row that describes how your upstream MCP authenticates. Miftah requires Node.js 20 or newer. Each upstream keeps its own runtime and installation requirements; for example, the GitHub preset requires Docker and the Google Search Console adapter requires Python 3.11 or newer plus `uvx`. +On Windows, `generic`, `sentry`, and `generic-npx` are unavailable. npm's `npx` runner itself requires a command shell on Windows; Miftah refuses them instead of invoking `cmd.exe`. Use a direct `.exe` or `.com` local executable, a direct-executable adapter such as `uvx.exe` or `docker.exe`, or a remote MCP instead. + Shell examples below use POSIX syntax, including `~`, `$HOME`, and `\` line continuations. On Windows, run the same Miftah options from PowerShell with Windows paths and PowerShell line continuation, or put the command on one line. ### Prefer guided setup? @@ -192,7 +194,7 @@ miftah init analytics \ --client claude-desktop ``` -Replace the example package, version, and variable name with the upstream's documented values. An exact version is required. Run `validate`, `doctor`, `test-profile`, and `list-tools` before adding the printed client JSON. +Replace the example package, version, and variable name with the upstream's documented values. An exact version is required. This package-runner preset is available on macOS and Linux, not Windows: npm's `npx` runner uses a command shell there, and Miftah refuses it rather than invoking `cmd.exe`. On Windows, use a reviewed direct `.exe` or `.com` executable, a direct-executable adapter, or a remote MCP. Run `validate`, `doctor`, `test-profile`, and `list-tools` before adding the printed client JSON. ### Reviewed local executable template diff --git a/docs/cli.md b/docs/cli.md index 6a52d311..cd81a3b1 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -59,14 +59,14 @@ The Console API is versioned under `/api/v1` and uses exact Host checks, exact l ### `init` presets and paths -`--preset` defaults to `generic`. The strict catalog accepts `generic`, `github`, `sentry`, `google-search-console`, `generic-npx`, `generic-docker`, `local-stdio`, and `streamable-http`; an unrecognized preset is a usage error. `--output` defaults to `.miftah.json`. Miftah resolves the output path from the current working directory, creates missing parent directories, and refuses to overwrite an existing file. Quote shell paths and names containing spaces: +On macOS and Linux, `--preset` defaults to `generic`. On Windows, `--preset` is required for noninteractive `init`; there is no implicit generic preset. The strict catalog accepts `generic`, `github`, `sentry`, `google-search-console`, `generic-npx`, `generic-docker`, `local-stdio`, and `streamable-http`; an unrecognized preset is a usage error. `--output` defaults to `.miftah.json`. Miftah resolves the output path from the current working directory, creates missing parent directories, and refuses to overwrite an existing file. Quote shell paths and names containing spaces: ```sh miftah init "work wrapper" --preset github --output "$HOME/Miftah configs/work wrapper.json" miftah validate --config "$HOME/Miftah configs/work wrapper.json" ``` -`generic-npx` requires `--npm-package` with exact package SemVer; `generic-docker` requires a canonical digest in `--docker-image`; `streamable-http` requires `--url` plus optional credential environment/header metadata; and one-account noninteractive `google-search-console` requires `--oauth-client-secrets-file` with an absolute path. `local-stdio` requires `--local-command` and `--accept-local-command`; it accepts repeated literal `--arg` values, optional native absolute `--cwd`, and optional `--credential-env`. Use `--arg=--flag` for a value that begins with a dash. On Windows, the local executable must be an absolute `.exe` or `.com` binary; bare commands and `.cmd`/`.bat` shims are rejected so the direct argv path never uses a command processor. It rejects shell executables and wrappers, URL-like commands, environment references, controls, and credential-shaped command or argument values. It writes a read-only profile, treats unknown tools as destructive, and does not launch a generic local executable during `init` or `setup`. Guided GSC setup can collect one or more named accounts, their client-secrets paths, and an explicit default profile. `--credential-env` is optional where supported. The GSC adapter prints credential/browser/identity ownership without printing a configured path. See [preset and client compatibility](presets-and-clients.md) for exact inputs, pins, provenance, and client snippets, and [provider adapters](provider-adapters.md) for the upstream-owned OAuth boundary. +`generic-npx` requires `--npm-package` with exact package SemVer; `generic-docker` requires a canonical digest in `--docker-image`; `streamable-http` requires `--url` plus optional credential environment/header metadata; and one-account noninteractive `google-search-console` requires `--oauth-client-secrets-file` with an absolute path. `local-stdio` requires `--local-command` and `--accept-local-command`; it accepts repeated literal `--arg` values, optional native absolute `--cwd`, and optional `--credential-env`. Use `--arg=--flag` for a value that begins with a dash. On Windows, the local executable must be an absolute `.exe` or `.com` binary; bare commands and `.cmd`/`.bat` shims are rejected so the direct argv path never uses a command processor. On Windows, `generic`, `sentry`, and `generic-npx` are unavailable because npm's `npx` runner requires a command shell. It rejects shell executables and wrappers, URL-like commands, environment references, controls, and credential-shaped command or argument values. It writes a read-only profile, treats unknown tools as destructive, and does not launch a generic local executable during `init` or `setup`. Guided GSC setup can collect one or more named accounts, their client-secrets paths, and an explicit default profile. `--credential-env` is optional where supported. The GSC adapter prints credential/browser/identity ownership without printing a configured path. See [preset and client compatibility](presets-and-clients.md) for exact inputs, pins, provenance, and client snippets, and [provider adapters](provider-adapters.md) for the upstream-owned OAuth boundary. `--interactive` uses a wizard only when both input and output are TTYs. EOF or Ctrl-C while it is collecting initial configuration data cancels without writing a config. It asks for variable names and safe metadata, never secret values. For `local-stdio`, it asks for one argv element at a time and prints only a bounded count-based review summary before the acknowledgement; it does not echo arguments or credential values. For Google Search Console it asks for each account's profile name, optional description, and client-secrets path, then an explicit default profile. `miftah setup --verify` is an explicit opt-in to run each selected adapter's declared safe read-only check after the configuration write. It never accepts a tool name or arguments from the operator, never guesses a health command, does not auto-approve a policy confirmation, and returns only bounded status rather than provider output. The check runs only while the selected profile still matches the adapter's reviewed launch envelope; otherwise it reports a bounded unsupported status without launching the provider. If the post-write readiness prompt is cancelled, Miftah keeps the configuration, reports incomplete verification, and exits 1. A non-ready `setup --verify` result also keeps the configuration and exits 1. `init` is network-free and does not accept `--verify` or client-entry import flags. In noninteractive use, `init` creates only the config unless `--client` is supplied. `--client` prints JSON with absolute Node and compiled Miftah paths; it does not write a host config. For `claude-code` or `all`, it also prints a separate, exact management-tool `permissions.ask` fragment for manual merge into Claude Code settings; it never writes or overwrites those settings. Regenerate the snippets after moving or upgrading Miftah or changing the config path. diff --git a/docs/presets-and-clients.md b/docs/presets-and-clients.md index 3e5f14f5..c8906387 100644 --- a/docs/presets-and-clients.md +++ b/docs/presets-and-clients.md @@ -12,11 +12,11 @@ Miftah itself requires Node.js `>=20`. That does not establish an upstream serve | Catalog key | Exact generated command or required input | Upstream requirements and security boundary | | --- | --- | --- | -| `generic` | `npx --yes @modelcontextprotocol/server-everything@2026.7.4 stdio` | This is the MCP reference/test server, not a production-ready provider recommendation. Its npm metadata declares no upstream Node engine floor. An optional `--credential-env ` adds only a `${ENV_NAME}` reference. | +| `generic` | `npx --yes @modelcontextprotocol/server-everything@2026.7.4 stdio` | This is the MCP reference/test server, not a production-ready provider recommendation. Its npm metadata declares no upstream Node engine floor. An optional `--credential-env ` adds only a `${ENV_NAME}` reference. Unavailable on Windows because npm's `npx` runner requires a command shell. | | `github` | Docker STDIO: `docker run -i --rm -e GITHUB_PERSONAL_ACCESS_TOKEN ghcr.io/github/github-mcp-server:v1.5.0 stdio --read-only --toolsets=repos,issues,pull_requests` | Docker is required. Supply least-privilege GitHub provider tokens through the generated environment references. The catalog intentionally pins a tag, **not** an invented OCI digest. Before a reproducible production deployment, use an authenticated registry process to promote the approved tag, inspect and record its resolved digest in deployment records, then deploy that recorded digest according to the [GitHub digest guidance](https://docs.github.com/en/packages/working-with-a-github-packages-registry/working-with-the-container-registry#pull-by-digest). | -| `sentry` | `npx --yes @sentry/mcp-server@0.36.0 --skills=inspect`; generated environment reference: `SENTRY_ACCESS_TOKEN` | The upstream package requires Node.js `>=20`. Use least-privilege Sentry token scopes. `--skills=inspect` filters CLI skills; it is not provider-token authorization and is not a read-only flag or preset. Miftah local policy does not reduce provider token permissions. | +| `sentry` | `npx --yes @sentry/mcp-server@0.36.0 --skills=inspect`; generated environment reference: `SENTRY_ACCESS_TOKEN` | The upstream package requires Node.js `>=20`. Use least-privilege Sentry token scopes. `--skills=inspect` filters CLI skills; it is not provider-token authorization and is not a read-only flag or preset. Miftah local policy does not reduce provider token permissions. Unavailable on Windows because npm's `npx` runner requires a command shell. | | `google-search-console` | Noninteractive one-account setup requires `--oauth-client-secrets-file `; guided `miftah setup` supports one or more named accounts. Generated command: `uvx mcp-search-console@0.3.2`; generated environment: `GSC_OAUTH_CLIENT_SECRETS_FILE` and a distinct `GSC_CONFIG_DIR` per generated configuration file and profile. | Python `>=3.11` and `uvx` are required. OAuth, browser handoff, token cache, reauthentication, and revocation remain upstream/manual-owned. Miftah applies a read-only policy, does not set `GSC_ALLOW_DESTRUCTIVE`, and never reads the upstream cache. See the [provider-adapter contract](provider-adapters.md#google-search-console-pilot). | -| `generic-npx` | Required: `--npm-package `; optional `--credential-env ` | Only an exact npm package SemVer is accepted. The selected external package, not Miftah, declares its own Node requirement. | +| `generic-npx` | Required: `--npm-package `; optional `--credential-env ` | Only an exact npm package SemVer is accepted. The selected external package, not Miftah, declares its own Node requirement. Unavailable on Windows because npm's `npx` runner requires a command shell. | | `generic-docker` | Required: `--docker-image `; optional `--credential-env ` | Docker is required. Only a canonical image reference with a 64-hex-character `@sha256:` digest is accepted. | | `local-stdio` | Required: `--local-command ` and `--accept-local-command`; optional repeated `--arg `, `--cwd `, and `--credential-env `. Use a bare executable or native absolute path on macOS/Linux, and a direct native absolute `.exe` or `.com` binary on Windows. | Each `--arg` is one literal argv element; use `--arg=--flag` when the value starts with a dash. Miftah never uses a shell, expands no environment references, rejects shell executables/wrappers, URLs, controls, and credential-shaped command or argument values, and never starts this generic local command during setup. Windows rejects bare commands and `.cmd`/`.bat` shims so direct argv execution cannot fall back to a command processor. The generated profile is read-only and unknown tools remain destructive until deliberately configured. Review the executable and its arguments yourself before acknowledging it. | | `streamable-http` | Required: `--url `; optional credential metadata: `--credential-env`, `--header-name`, and `--header-prefix` | The URL must be HTTPS and must not contain userinfo, a query, or a fragment. Credentials may appear only as `${ENV_NAME}` through validated header metadata; allowed prefixes are empty, `Bearer `, and `Sentry `. Never place a credential in a URL or URL component. | @@ -51,7 +51,7 @@ Use the following upstream materials when assessing a pin or provider configurat ## First run -`init` and guided `setup` use the strict catalog. The default preset is `generic`; an unknown preset is rejected rather than falling back. (The legacy library-only `presetConfig` fallback does not describe CLI behavior.) +`init` and guided `setup` use the strict catalog. On macOS and Linux the default preset is `generic`; on Windows an explicit supported preset is required. An unknown preset is rejected rather than falling back. On Windows, choose a direct-executable or remote preset explicitly because the `generic`, `sentry`, and `generic-npx` npx-backed presets are refused rather than launched through a command shell. (The legacy library-only `presetConfig` fallback does not describe CLI behavior.) ```sh miftah init [name] \ diff --git a/docs/security.md b/docs/security.md index 8457f1bf..e9d06aa9 100644 --- a/docs/security.md +++ b/docs/security.md @@ -22,6 +22,8 @@ Miftah is a credential broker, so safe defaults are part of the product contract External secret providers execute only fixed programs with argument arrays and bounded stdout/stderr capture. Miftah does not expose provider output in an error, audit record, health entry, or doctor report. On Windows it resolves provider executables without current-directory lookup and uses a static System32 PowerShell launcher that joins a `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE` Job Object before creating the provider. Timeout, cancellation, output-limit, or launcher termination closes that job and terminates ordinary provider descendants as well. This process-tree guarantee does not cover providers that intentionally escape through services, scheduled tasks, elevation brokers, or WMI process creation. +Windows STDIO upstreams are resolved before the MCP SDK starts a child process. Miftah passes the SDK only an absolute direct `.exe` or `.com` path resolved from the configured command and final profile environment; it refuses `.cmd`/`.bat` shims and shell executables such as `cmd.exe`, PowerShell, and `pwsh` rather than relying on the SDK's Windows command-processor fallback. npm's `npx` runner itself uses a Windows command shell, so the `generic`, `sentry`, and `generic-npx` presets are unavailable on Windows. This does not remove direct Windows support for a reviewed local executable, `docker.exe`, `uvx.exe`, or other direct executables discoverable from an absolute PATH entry. + Allowlisted local plugins use the same bounded argument-array child-process path and Windows Job Object containment. Miftah preflights their API manifest before serving, verifies the resolved module remains below the configuration directory, scrubs the child environment, and gives secret providers only one canonical reference and routing matchers only a tool name plus bounded canonical signals. This isolates ordinary plugin failures and withholds Miftah's resolved configuration; it is not an operating-system sandbox for an arbitrary same-user Node module. A plugin can still make its own filesystem, process, or network calls, including actions affecting its parent or host, so every configured module and changes made after preflight must be reviewed and trusted by the operator. See [local plugins](plugins.md). Profile credential isolation is a separate, opt-in boundary. On macOS and Linux it gives one profile/upstream target a marker-owned, owner-restricted runtime tree and copies only explicitly configured files from below the canonical configuration directory. Miftah never resolves, materializes, injects, or bind-mounts another profile's managed path. It does not make a hostile native STDIO process safe: a process running under the same OS user can still open another profile's absolute path. Stronger native containment needs a separate OS identity or a correctly configured OS sandbox. diff --git a/src/cli/doctor.ts b/src/cli/doctor.ts index 1f25da79..c2147b67 100644 --- a/src/cli/doctor.ts +++ b/src/cli/doctor.ts @@ -19,6 +19,8 @@ import { type SecretProviderAvailability } from "../secrets/secret-provider-availability.js"; import type { UpstreamSession } from "../upstream/upstream-session.js"; +import { resolveProcessEnvironment } from "../upstream/upstream-process-manager.js"; +import { resolveWindowsStdioCommand } from "../upstream/windows-stdio-command.js"; import { MiftahError } from "../utils/errors.js"; import { SecretRedactor } from "../secrets/redact.js"; import { createRuntime } from "./create-runtime.js"; @@ -126,13 +128,13 @@ function configuredTargets(config: MiftahConfig): DoctorTarget[] { return targets; } -function pathForTarget(config: MiftahConfig, target: DoctorTarget): string | undefined { +function environmentForTarget(config: MiftahConfig, target: DoctorTarget): Record { const profile: ProfileConfig | undefined = config.profiles[target.profile]; - const profileEnvironment = { - ...(profile?.env ?? {}), - ...(target.upstreamName ? profile?.upstreams?.[target.upstreamName]?.env ?? {} : {}) - }; - return profileEnvironment.PATH ?? target.upstream.env?.PATH ?? process.env.PATH; + const override = target.upstreamName ? profile?.upstreams?.[target.upstreamName] : undefined; + const profileEnvironment = override === undefined + ? profile?.env + : { ...(profile?.env ?? {}), ...override.env }; + return resolveProcessEnvironment(target.upstream.env, profileEnvironment).environment; } function effectiveTargetOptions( @@ -149,22 +151,28 @@ function effectiveTargetOptions( async function isExecutableAvailable( command: string | undefined, - pathValue: string | undefined, + environment: Record, cwd: string | undefined ): Promise { if (!command) return false; + + if (process.platform === "win32") { + try { + await resolveWindowsStdioCommand(command, [], { environment }); + return true; + } catch { + // Doctor deliberately reports the same bounded unavailable result as the + // runtime boundary without exposing the command or resolver diagnostics. + return false; + } + } + const candidates = isAbsolute(command) || command.includes("/") || command.includes("\\") ? [isAbsolute(command) ? command : resolve(cwd ?? process.cwd(), command)] - : (pathValue ?? "") + : (environment.PATH ?? "") .split(delimiter) .filter((entry) => entry.length > 0) - .flatMap((entry) => - process.platform === "win32" - ? ["", ...(process.env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM").split(";")].map((extension) => - join(entry, `${command}${extension}`) - ) - : [join(entry, command)] - ); + .map((entry) => join(entry, command)); for (const candidate of candidates) { try { await access(candidate, constants.X_OK); @@ -495,15 +503,66 @@ export async function runDoctor(configPath: string): Promise { "Review the configured expected fingerprint and identity probe before relying on risky operations." ); }; + const recordTargetResolutionFailure = (target: DoctorTarget, targetText: string, error: unknown): void => { + incompleteProfiles.add(target.profile); + const secretResolutionFailure = isSecretResolutionFailure(error); + checks.push( + check( + secretResolutionFailure ? DOCTOR_CODES.SECRET_REFERENCES : DOCTOR_CODES.CONFIGURATION, + "error", + targetText, + secretResolutionFailure + ? "Target secret references could not be resolved safely." + : "Target configuration could not be resolved safely.", + secretResolutionFailure + ? "Correct target secret provider configuration and retry doctor." + : "Correct target configuration and retry doctor." + ), + check( + DOCTOR_CODES.STARTUP, + "skipped", + targetText, + secretResolutionFailure + ? "Upstream startup was skipped because target secret resolution did not complete." + : "Upstream startup was skipped because target configuration could not be resolved.", + secretResolutionFailure + ? "Correct target secret provider configuration before retrying doctor." + : "Correct target configuration before retrying doctor." + ), + skippedDiscoveryCheck(DOCTOR_CODES.TOOLS_DISCOVERY, targetText, "Tool"), + unavailableIdentityCheck(target, targetText, "startup"), + skippedDiscoveryCheck(DOCTOR_CODES.RESOURCES_DISCOVERY, targetText, "Resource"), + skippedDiscoveryCheck(DOCTOR_CODES.PROMPTS_DISCOVERY, targetText, "Prompt") + ); + }; const probeTarget = async (target: DoctorTarget): Promise => { const targetText = targetLabel(target); let runtime: Awaited>; + try { + runtime = await createRuntime(canonicalConfigPath, { + profile: target.profile, + upstreamName: target.upstreamName + }); + const profileRuntimes = runtimes.get(target.profile) ?? []; + profileRuntimes.push(runtime); + runtimes.set(target.profile, profileRuntimes); + } catch (error) { + recordTargetResolutionFailure(target, targetText, error); + return; + } + if (target.upstream.transport === "stdio") { - const available = await isExecutableAvailable( - target.upstream.command, - pathForTarget(config, target), - effectiveTargetOptions(config, target).cwd - ); + let available: boolean; + try { + available = await isExecutableAvailable( + target.upstream.command, + environmentForTarget(runtime.config, target), + effectiveTargetOptions(runtime.config, target).cwd + ); + } catch (error) { + recordTargetResolutionFailure(target, targetText, error); + return; + } checks.push( check( DOCTOR_CODES.EXECUTABLE, @@ -527,48 +586,6 @@ export async function runDoctor(configPath: string): Promise { ); } - try { - runtime = await createRuntime(canonicalConfigPath, { - profile: target.profile, - upstreamName: target.upstreamName - }); - const profileRuntimes = runtimes.get(target.profile) ?? []; - profileRuntimes.push(runtime); - runtimes.set(target.profile, profileRuntimes); - } catch (error) { - incompleteProfiles.add(target.profile); - const secretResolutionFailure = isSecretResolutionFailure(error); - checks.push( - check( - secretResolutionFailure ? DOCTOR_CODES.SECRET_REFERENCES : DOCTOR_CODES.CONFIGURATION, - "error", - targetText, - secretResolutionFailure - ? "Target secret references could not be resolved safely." - : "Target configuration could not be resolved safely.", - secretResolutionFailure - ? "Correct target secret provider configuration and retry doctor." - : "Correct target configuration and retry doctor." - ), - check( - DOCTOR_CODES.STARTUP, - "skipped", - targetText, - secretResolutionFailure - ? "Upstream startup was skipped because target secret resolution did not complete." - : "Upstream startup was skipped because target configuration could not be resolved.", - secretResolutionFailure - ? "Correct target secret provider configuration before retrying doctor." - : "Correct target configuration before retrying doctor." - ), - skippedDiscoveryCheck(DOCTOR_CODES.TOOLS_DISCOVERY, targetText, "Tool"), - unavailableIdentityCheck(target, targetText, "startup"), - skippedDiscoveryCheck(DOCTOR_CODES.RESOURCES_DISCOVERY, targetText, "Resource"), - skippedDiscoveryCheck(DOCTOR_CODES.PROMPTS_DISCOVERY, targetText, "Prompt") - ); - return; - } - let session: UpstreamSession; try { session = await runtime.manager.get(target.profile, target.upstreamName); diff --git a/src/cli/init.ts b/src/cli/init.ts index b528a4df..9a263a14 100644 --- a/src/cli/init.ts +++ b/src/cli/init.ts @@ -89,6 +89,20 @@ function usageError(message: string): never { throw new CliUsageError(message); } +function defaultPresetForPlatform(): string | undefined { + return process.platform === "win32" ? undefined : "generic"; +} + +function requirePresetSelection(preset: string | undefined): string { + if (preset !== undefined) return preset; + if (process.platform === "win32") { + usageError( + "On Windows, specify --preset explicitly. The generic default uses npm's npx package runner, which requires a command shell; choose a direct .exe or .com local-stdio executable, a direct-executable preset, or a remote MCP." + ); + } + return "generic"; +} + function isTty(context: InitCommandContext): boolean { return context.input.isTTY === true && context.output.isTTY === true; } @@ -361,8 +375,10 @@ async function collectInteractiveValues(options: InitCommandOptions, context: In const cancellation = createCancellation(line); try { const name = options.name ?? (await prompt(line, cancellation, "Name", "miftah-wrapper")); - const preset = options.preset ?? (await prompt(line, cancellation, "Catalog preset", "generic")); - const presetOptions = await collectPresetOptions(line, cancellation, preset ?? "generic", options, context.output); + const preset = requirePresetSelection( + options.preset ?? (await prompt(line, cancellation, "Catalog preset", defaultPresetForPlatform())) + ); + const presetOptions = await collectPresetOptions(line, cancellation, preset, options, context.output); const output = options.output ?? (await prompt(line, cancellation, "Output location", `${name}.miftah.json`)); const client = options.client ?? (await prompt( line, @@ -370,7 +386,7 @@ async function collectInteractiveValues(options: InitCommandOptions, context: In "Client (claude-desktop, claude-code, cursor, vscode, all; blank for config only)" )); - if (name === undefined || preset === undefined || output === undefined) { + if (name === undefined || output === undefined) { usageError("Interactive init requires a name, preset, and output location."); } return { name, preset, output, client, ...presetOptions }; @@ -387,7 +403,7 @@ function nonInteractiveValues(options: InitCommandOptions): InitValues { const name = options.name ?? "miftah-wrapper"; return { name, - preset: options.preset ?? "generic", + preset: requirePresetSelection(options.preset ?? defaultPresetForPlatform()), output: options.output ?? `${name}.miftah.json`, client: options.client, credentialEnv: options.credentialEnv, diff --git a/src/config/presets.ts b/src/config/presets.ts index e8895a4d..8a1e132d 100644 --- a/src/config/presets.ts +++ b/src/config/presets.ts @@ -27,7 +27,7 @@ const embeddedCredentialScheme = /(?:^|=|,|:|\{|\[|"|')(?:api[-_ ]?key|basic|bea const credentialUrlUserinfo = /[A-Za-z][A-Za-z0-9+.-]*:\/\/[^/?#\s@]+@/u; const credentialQueryParameter = /[?&](?:access[-_]?key|access[-_]?token|api[-_]?key|auth(?:orization)?|bearer|client[-_]?secret|cookie|credential(?:s)?|jwt|key|password|passwd|private[-_]?key|secret|sig(?:nature)?|token)=[^&\s]+/iu; const uriScheme = /^[A-Za-z][A-Za-z0-9+.-]*:\/\//u; -const shellExecutable = /^(?:bash|cmd(?:\.exe)?|fish|powershell(?:\.exe)?|pwsh(?:\.exe)?|sh|zsh)$/iu; +const shellExecutable = /^(?:bash|cmd|command|fish|powershell|pwsh|sh|zsh)$/iu; const environmentWrapper = /^env(?:\.exe)?$/iu; const bareExecutable = /^[A-Za-z0-9][A-Za-z0-9._+-]*$/u; const windowsDirectExecutable = /\.(?:com|exe)$/iu; @@ -35,6 +35,7 @@ const environmentReferenceArgument = /\$\{[A-Za-z_][A-Za-z0-9_]*\}/u; const maximumLocalArgumentCount = 128; const maximumLocalArgumentBytes = 4 * 1024; const maximumLocalArgumentTotalBytes = 16 * 1024; +const windowsUnsupportedNpxPresets = new Set(["generic", "generic-npx", "sentry"]); type CurrentMiftahConfig = Extract; type CurrentUpstreamConfig = NonNullable; @@ -88,6 +89,14 @@ function catalogError(message: string): never { throw new PresetCatalogError(message); } +/** True when a catalog preset would require npm's Windows command-shell runner. */ +export function isWindowsNpxPresetUnavailable( + preset: string, + platform: NodeJS.Platform = process.platform +): boolean { + return platform === "win32" && windowsUnsupportedNpxPresets.has(preset); +} + function environmentReference(name: unknown): string { if (typeof name !== "string" || !environmentVariableName.test(name)) { catalogError(`Invalid credential environment variable name '${name}'.`); @@ -164,10 +173,19 @@ function buildStandardPreset( }; } +/** Builds safe shared defaults for a caller that already owns a validated upstream launch shape. */ +export function buildSafeStandardConfig( + name: string, + upstream: CurrentUpstreamConfig, + credentialEnv?: string +): MiftahConfig { + return buildStandardPreset(name, upstream, credentialEnv); +} + /** Builds the generic reference MCP server preset. */ function buildGenericPreset(name: string, options: PresetBuildOptions): MiftahConfig { // npm registry metadata for this package does not declare an upstream Node engine floor. - return buildStandardPreset( + return buildSafeStandardConfig( name, { transport: "stdio", @@ -444,7 +462,7 @@ function nativeAbsolutePath(value: string): boolean { function executableStem(command: string): string { const executableName = command.replaceAll("\\", "/").split("/").at(-1) ?? command; - return executableName.replace(/\.(?:cmd|exe)$/iu, "").toLowerCase(); + return executableName.replace(/\.(?:cmd|com|exe)$/iu, "").toLowerCase(); } function normalizeCredentialText(value: string): string { @@ -708,10 +726,15 @@ export function buildPresetConfig( } const definition = PRESET_CATALOG.presets[preset as PresetCatalogName]; validatePresetOptions(preset, definition.requirements, options); - if (preset === "google-search-console") { - return buildGoogleSearchConsolePreset(name, options, context); + const config = preset === "google-search-console" + ? buildGoogleSearchConsolePreset(name, options, context) + : definition.build(name, options); + if (isWindowsNpxPresetUnavailable(preset)) { + catalogError( + `Preset '${preset}' uses npm's npx package runner, which requires a Windows command shell. Use a direct .exe or .com local-stdio executable, a direct-executable preset, or a remote MCP instead.` + ); } - return definition.build(name, options); + return config; } /** Builds a named legacy configuration preset, retaining its generic fallback behavior. */ diff --git a/src/console/console-application-service.ts b/src/console/console-application-service.ts index c28c1d51..993cc609 100644 --- a/src/console/console-application-service.ts +++ b/src/console/console-application-service.ts @@ -3,7 +3,11 @@ import { mkdir } from "node:fs/promises"; import { dirname, join } from "node:path"; import { readAuditJsonl } from "../cli/audit-jsonl.js"; import { resolvePath } from "../config/path-resolve.js"; -import { buildPresetConfig, PresetCatalogError } from "../config/presets.js"; +import { + buildPresetConfig, + isWindowsNpxPresetUnavailable, + PresetCatalogError +} from "../config/presets.js"; import type { PresetBuildOptions } from "../config/presets.js"; import type { MiftahConfig } from "../config/types.js"; import { validateConfig } from "../config/validate-config.js"; @@ -359,7 +363,12 @@ export class ConsoleApplicationService implements ConsoleControlApplication { validateConfig(config); } catch (error) { if (error instanceof PresetCatalogError) { - throw new MiftahError("CONFIG_SCHEMA_INVALID", "CONFIG_SCHEMA_INVALID: the requested setup connector is not valid"); + throw new MiftahError( + "CONFIG_SCHEMA_INVALID", + isWindowsNpxPresetUnavailable(request.preset) + ? "CONFIG_SCHEMA_INVALID: the selected npm package-runner connector is unavailable on Windows; choose a direct .exe or .com executable, a direct-executable preset, or a remote MCP." + : "CONFIG_SCHEMA_INVALID: the requested setup connector is not valid" + ); } throw error; } diff --git a/src/secrets/executable-resolver.ts b/src/secrets/executable-resolver.ts index 164cc326..87ce55fc 100644 --- a/src/secrets/executable-resolver.ts +++ b/src/secrets/executable-resolver.ts @@ -1,6 +1,8 @@ -import { access, constants } from "node:fs/promises"; +import { access, constants, open } from "node:fs/promises"; import { posix, win32 } from "node:path"; +const windowsDirectExecutable = /\.(?:com|exe)$/iu; + export interface ExecutableResolverOptions { readonly environment?: NodeJS.ProcessEnv; readonly platform?: NodeJS.Platform; @@ -36,6 +38,43 @@ export async function resolveExecutablePath( return undefined; } +/** + * Resolves a Windows command only when it is a direct executable. Unlike the + * general resolver, this intentionally never considers PATHEXT entries such + * as .cmd or .bat and never resolves a relative path through the current + * directory. + */ +export async function resolveWindowsDirectExecutablePath( + command: string, + options: ExecutableResolverOptions = {} +): Promise { + if (command.length === 0 || command.includes("\u0000")) return undefined; + + const platform = options.platform ?? process.platform; + if (platform !== "win32") return undefined; + const environment = options.environment ?? process.env; + const hasPath = command.includes("/") || command.includes("\\") || win32.isAbsolute(command); + if (hasPath) { + if (!win32.isAbsolute(command) || !windowsDirectExecutable.test(command)) return undefined; + return accessibleExecutable(command); + } + + if (win32.extname(command).length > 0 && !windowsDirectExecutable.test(command)) return undefined; + const pathValue = environmentValue(environment, "PATH"); + if (pathValue === undefined) return undefined; + const names = windowsDirectExecutable.test(command) ? [command] : [`${command}.exe`, `${command}.com`]; + + for (const entry of pathValue.split(win32.delimiter)) { + const directory = normalizePathEntry(entry); + if (directory === undefined || !win32.isAbsolute(directory)) continue; + for (const name of names) { + const resolved = await accessibleExecutable(win32.join(directory, name)); + if (resolved !== undefined) return resolved; + } + } + return undefined; +} + function bareCommandCandidates( command: string, environment: NodeJS.ProcessEnv, @@ -62,6 +101,27 @@ function windowsExtensions(command: string, environment: NodeJS.ProcessEnv): str return ["", ...pathExtensions.split(";").filter((extension) => extension.length > 0)]; } +async function accessibleExecutable(candidate: string): Promise { + try { + await access(candidate, constants.X_OK); + const file = await open(candidate, "r"); + try { + const header = Buffer.alloc(2); + const { bytesRead } = await file.read(header, 0, header.length, 0); + // cross-spawn reparses shebang files through an interpreter before it + // decides whether to invoke cmd.exe. A direct extension alone is not a + // safe Windows stdio launch boundary. + if (bytesRead >= header.length && header[0] === 0x23 && header[1] === 0x21) return undefined; + return candidate; + } finally { + await file.close(); + } + } catch { + // An unavailable path is deliberately indistinguishable from other filesystem failures. + return undefined; + } +} + function normalizePathEntry(entry: string): string | undefined { const trimmed = entry.trim(); if (trimmed.length === 0) return undefined; diff --git a/src/setup/client-entry-import.ts b/src/setup/client-entry-import.ts index fe4e8b07..0cf46168 100644 --- a/src/setup/client-entry-import.ts +++ b/src/setup/client-entry-import.ts @@ -1,5 +1,5 @@ import { isAbsolute } from "node:path"; -import { buildPresetConfig, PresetCatalogError } from "../config/presets.js"; +import { buildSafeStandardConfig } from "../config/presets.js"; import type { MiftahConfig } from "../config/types.js"; import { validateConfig } from "../config/validate-config.js"; @@ -12,7 +12,7 @@ const credentialAssignment = /(?:^|[^A-Za-z0-9])(?:access[-_]?key|access[-_]?tok const embeddedCredentialScheme = /(?:^|=|,|:|\{|\[|"|')(?:api[-_ ]?key|basic|bearer|jwt|token)\s+\S+/iu; const credentialUrlUserinfo = /[A-Za-z][A-Za-z0-9+.-]*:\/\/[^/?#\s@]+@/u; const uriScheme = /^[A-Za-z][A-Za-z0-9+.-]*:\/\//u; -const shellExecutable = /^(?:bash|cmd(?:\.exe)?|fish|powershell(?:\.exe)?|pwsh(?:\.exe)?|sh|zsh)$/iu; +const shellExecutable = /^(?:bash|cmd|command|fish|powershell|pwsh|sh|zsh)$/iu; const windowsDirectExecutable = /\.(?:com|exe)$/iu; const staticFlag = /^--?[A-Za-z][A-Za-z0-9-]*$/u; const staticPackageSpecifier = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*@v?\d+\.\d+\.\d+(?:[-+][a-z0-9.-]+)?$/u; @@ -139,7 +139,7 @@ function credentialBearingArgument(value: string): boolean { function executableStem(command: string): string { const executableName = command.replaceAll("\\", "/").split("/").at(-1) ?? command; - return executableName.replace(/\.(?:cmd|exe)$/iu, "").toLowerCase(); + return executableName.replace(/\.(?:cmd|com|exe)$/iu, "").toLowerCase(); } function staticFlagArgument(value: string): boolean { @@ -317,7 +317,12 @@ function selectedStdioEntry(value: unknown, container: ClientEntryContainer): Im function safeImportedConfig(name: string, upstream: ImportedStdioEntry): MiftahConfig { try { - const baseline = buildPresetConfig(name, "generic", {}); + const baseline = buildSafeStandardConfig(name, { + transport: "stdio", + command: upstream.command, + args: [...upstream.args], + ...(upstream.cwd === undefined ? {} : { cwd: upstream.cwd }) + }); return validateConfig({ ...baseline, description: `${name} imported from an existing MCP client entry`, @@ -337,9 +342,6 @@ function safeImportedConfig(name: string, upstream: ImportedStdioEntry): MiftahC tooling: { ...baseline.tooling, unknownToolRisk: "destructive" } }); } catch (error) { - if (error instanceof PresetCatalogError) { - importError("The requested Miftah configuration name is not valid."); - } if (error instanceof Error) { importError("The imported MCP entry could not be converted into a valid Miftah configuration."); } diff --git a/src/upstream/upstream-process-manager.ts b/src/upstream/upstream-process-manager.ts index 3468bb80..443b884b 100644 --- a/src/upstream/upstream-process-manager.ts +++ b/src/upstream/upstream-process-manager.ts @@ -17,6 +17,7 @@ import { asRemoteError, fetchSsePostWithStatusOnly } from "./remote-error.js"; import { UpstreamSession } from "./upstream-session.js"; import { MIFTAH_VERSION } from "../version.js"; import { mergeHeaders } from "./headers.js"; +import { resolveWindowsStdioCommand } from "./windows-stdio-command.js"; const defaultStartupTimeoutMs = 30_000; const defaultShutdownTimeoutMs = 5_000; @@ -27,7 +28,11 @@ const restartJitterFraction = 0.2; const restartStabilityWindowMs = 30_000; const credentialKeyPattern = /(token|secret|password|api[_-]?key|auth|private|credential|cookie)/i; -function mergeEnvironment(...environmentSets: Array | undefined>): Record { +/** + * Combines child-process environments with Windows' case-insensitive variable + * semantics. Callers that preflight a launch must use this same precedence. + */ +export function mergeEnvironment(...environmentSets: Array | undefined>): Record { if (process.platform !== "win32") return Object.assign({}, ...environmentSets); const merged = new Map(); for (const environment of environmentSets) { @@ -38,6 +43,30 @@ function mergeEnvironment(...environmentSets: Array | und return Object.fromEntries(merged.values()); } +/** Expands configured process environment values and applies the runtime's launch precedence. */ +export function resolveProcessEnvironment( + upstreamEnvironment: Record | undefined, + profileEnvironment: Record | undefined +): { environment: Record; secretValues: string[] } { + const expandedUpstreamEnvironment = upstreamEnvironment + ? expandEnvironmentReferencesWithSecretValues(upstreamEnvironment) + : undefined; + const expandedProfileEnvironment = profileEnvironment + ? expandEnvironmentReferencesWithSecretValues(profileEnvironment) + : undefined; + return { + environment: mergeEnvironment( + getDefaultEnvironment(), + expandedUpstreamEnvironment?.values, + expandedProfileEnvironment?.values + ), + secretValues: [ + ...(expandedUpstreamEnvironment?.secretValues ?? []), + ...(expandedProfileEnvironment?.secretValues ?? []) + ] + }; +} + /** Configures lifecycle behavior, capacity, and redacted diagnostics for an upstream manager. */ export interface UpstreamManagerOptions { startupTimeoutMs?: number; @@ -357,6 +386,10 @@ export class UpstreamProcessManager { profileConfig.args ?? this.upstream.args ?? [] ); this.assertCurrentStartup(profile, generation); + const stdioCommand = this.upstream.transport === "stdio" + ? await resolveWindowsStdioCommand(this.upstream.command!, args, { environment }) + : undefined; + this.assertCurrentStartup(profile, generation); try { oauthProvider = await this.options.oauthProvider?.(profile, this.upstreamName); } catch (error) { @@ -371,9 +404,12 @@ export class UpstreamProcessManager { } if (this.upstream.transport === "stdio") { + if (stdioCommand === undefined) { + throw new MiftahError("UPSTREAM_START_FAILED", "UPSTREAM_START_FAILED: stdio upstream requires a direct executable"); + } stdioTransport = new StdioClientTransport({ - command: this.upstream.command!, - args, + command: stdioCommand.command, + args: [...stdioCommand.args], env: environment, ...(profileConfig.cwd ?? this.upstream.cwd ? { cwd: profileConfig.cwd ?? this.upstream.cwd } : {}), stderr: "pipe" @@ -548,19 +584,12 @@ export class UpstreamProcessManager { args: string[]; suppressStderr: boolean; }> { - const upstreamEnvironment = this.upstream.env - ? expandEnvironmentReferencesWithSecretValues(this.upstream.env) - : undefined; - const profileEnvironment = profile.env ? expandEnvironmentReferencesWithSecretValues(profile.env) : undefined; + const resolvedEnvironment = resolveProcessEnvironment(this.upstream.env, profile.env); const upstreamHeaders = this.upstream.headers ? expandEnvironmentReferencesWithSecretValues(this.upstream.headers) : undefined; const profileHeaders = profile.headers ? expandEnvironmentReferencesWithSecretValues(profile.headers) : undefined; - const baseEnvironment = mergeEnvironment( - getDefaultEnvironment(), - upstreamEnvironment?.values, - profileEnvironment?.values - ); + const baseEnvironment = resolvedEnvironment.environment; let isolationEnvironment: Record | undefined; let suppressStderr = false; if (profile.isolation !== undefined) { @@ -586,8 +615,7 @@ export class UpstreamProcessManager { const environment = mergeEnvironment(baseEnvironment, isolationEnvironment); const headers = mergeHeaders(upstreamHeaders?.values, profileHeaders?.values); for (const value of [ - ...(upstreamEnvironment?.secretValues ?? []), - ...(profileEnvironment?.secretValues ?? []), + ...resolvedEnvironment.secretValues, ...(upstreamHeaders?.secretValues ?? []), ...(profileHeaders?.secretValues ?? []) ]) { diff --git a/src/upstream/windows-stdio-command.ts b/src/upstream/windows-stdio-command.ts new file mode 100644 index 00000000..d22a3fa1 --- /dev/null +++ b/src/upstream/windows-stdio-command.ts @@ -0,0 +1,60 @@ +import { win32 } from "node:path"; +import { + resolveWindowsDirectExecutablePath, + type ExecutableResolverOptions +} from "../secrets/executable-resolver.js"; +import { MiftahError } from "../utils/errors.js"; + +const shellExecutable = /^(?:bash|cmd|command|fish|powershell|pwsh|sh|zsh)$/iu; +const directExecutable = /\.(?:com|exe)$/iu; + +function executableStem(executable: string): string { + return win32.basename(executable).replace(directExecutable, ""); +} + +export interface ResolvedStdioCommand { + readonly command: string; + readonly args: readonly string[]; +} + +/** Deterministic overrides used by focused resolver tests. */ +export interface WindowsStdioCommandResolutionOptions { + readonly platform?: NodeJS.Platform; + readonly environment?: NodeJS.ProcessEnv; + readonly resolveExecutable?: ( + command: string, + options?: ExecutableResolverOptions + ) => Promise; +} + +/** + * Normalizes a stdio launch to a direct Windows executable before the MCP SDK + * receives it. cross-spawn otherwise routes bare and command-shim names through + * cmd.exe even when its shell option is false. + */ +export async function resolveWindowsStdioCommand( + command: string, + args: readonly string[], + options: WindowsStdioCommandResolutionOptions = {} +): Promise { + const platform = options.platform ?? process.platform; + if (platform !== "win32") return { command, args }; + + const resolveExecutable = options.resolveExecutable ?? resolveWindowsDirectExecutablePath; + const executable = await resolveExecutable(command, { + platform, + ...(options.environment === undefined ? {} : { environment: options.environment }) + }); + if ( + executable === undefined || + !directExecutable.test(executable) || + shellExecutable.test(executableStem(executable)) + ) { + throw new MiftahError( + "UPSTREAM_START_FAILED", + "UPSTREAM_START_FAILED: Windows stdio upstreams require a direct .exe or .com executable; command shells and command shims are not supported." + ); + } + + return { command: executable, args }; +} diff --git a/tests/client-entry-import.test.ts b/tests/client-entry-import.test.ts index 0ee9ee6d..678c48c8 100644 --- a/tests/client-entry-import.test.ts +++ b/tests/client-entry-import.test.ts @@ -128,6 +128,32 @@ describe("client entry import", () => { } }); + it("rejects a legacy Windows command interpreter entry", () => { + expect(() => createImportedClientConfiguration({ + configurationName: "legacy-command-shell", + document: JSON.stringify({ mcpServers: { example: { command: "COMMAND.COM", args: [] } } }), + entry: "example" + })).toThrow(ClientEntryImportError); + }); + + it.runIf(process.platform === "win32")("imports a direct Windows executable without depending on an npx preset baseline", () => { + const config = createImportedClientConfiguration({ + configurationName: "windows-direct", + document: JSON.stringify({ + mcpServers: { + example: { command: "C:\\tools\\provider.exe", args: ["--readonly"] } + } + }), + entry: "example" + }); + + expect(config).toMatchObject({ + upstream: { transport: "stdio", command: "C:\\tools\\provider.exe", args: ["--readonly"] }, + profiles: { default: { policy: "readonly" } }, + tooling: { unknownToolRisk: "destructive" } + }); + }); + it.each([ { command: "npx", args: ["--yes", "-y", "@posthog/mcp@1.2.3"] }, { command: "bunx", args: ["--silent", "--verbose", "@posthog/mcp@1.2.3"] }, diff --git a/tests/config-runtime-parity.test.ts b/tests/config-runtime-parity.test.ts index 2c1b8661..5661b294 100644 --- a/tests/config-runtime-parity.test.ts +++ b/tests/config-runtime-parity.test.ts @@ -1,6 +1,10 @@ import { readFileSync } from "node:fs"; import { describe, expect, it } from "vitest"; -import { buildPresetConfig } from "../src/config/presets.js"; +import { + buildPresetConfig, + isWindowsNpxPresetUnavailable, + PresetCatalogError +} from "../src/config/presets.js"; import { validateConfig } from "../src/config/validate-config.js"; import { MiftahError } from "../src/utils/errors.js"; @@ -532,6 +536,10 @@ describe("config runtime parity", () => { }], ["streamable-http", { url: "https://mcp.example.com" }] ])("keeps the %s generated preset valid", (preset, options) => { + if (isWindowsNpxPresetUnavailable(preset)) { + expect(() => buildPresetConfig("test", preset, options)).toThrow(PresetCatalogError); + return; + } expect(() => validateConfig(buildPresetConfig("test", preset, options))).not.toThrow(); }); diff --git a/tests/console-application-service.test.ts b/tests/console-application-service.test.ts index 204eb98a..bb3623fc 100644 --- a/tests/console-application-service.test.ts +++ b/tests/console-application-service.test.ts @@ -14,6 +14,26 @@ import { createPrivateConsoleDirectory } from "./helpers/private-console-directo const temporaryDirectories: string[] = []; const connectionRef = "oauthconn:31cb3ef5-22cb-4bf7-9ebf-e4a2d32bf18c"; +const platformDescriptor = Object.getOwnPropertyDescriptor(process, "platform"); + +function supportedKnownConnectorOptions(): { + readonly preset: string; + readonly credentialEnv: string; + readonly npmPackage?: string; + readonly dockerImage?: string; +} { + return process.platform === "win32" + ? { + preset: "generic-docker", + dockerImage: "ghcr.io/acme/server@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", + credentialEnv: "SUPPORT_TOKEN" + } + : { + preset: "generic-npx", + npmPackage: "@scope/server@1.2.3", + credentialEnv: "SUPPORT_TOKEN" + }; +} function importableClientEntry(): { readonly command: string; readonly args: readonly string[] } { return process.platform === "win32" @@ -22,6 +42,7 @@ function importableClientEntry(): { readonly command: string; readonly args: rea } afterEach(async () => { + if (platformDescriptor !== undefined) Object.defineProperty(process, "platform", platformDescriptor); await Promise.all(temporaryDirectories.splice(0).map((directory) => rm(directory, { recursive: true, force: true }))); }); @@ -201,12 +222,12 @@ describe("Console application service", () => { const privateParent = await createPrivateConsoleDirectory(root); const configPath = join(privateParent, "miftah", "miftah.json"); const service = new ConsoleApplicationService(configPath); + const { preset, ...options } = supportedKnownConnectorOptions(); const created = await service.onboardPreset({ name: "support-tools", - preset: "generic-npx", - npmPackage: "@scope/server@1.2.3", - credentialEnv: "SUPPORT_TOKEN" + preset, + ...options }); expect(created).toEqual({ @@ -215,20 +236,36 @@ describe("Console application service", () => { name: "support-tools", defaultProfile: "default", profileCount: 1, - actions: ["Created Miftah configuration 'support-tools' from preset 'generic-npx'."] + actions: [`Created Miftah configuration 'support-tools' from preset '${preset}'.`] }); expect(JSON.parse(await readFile(configPath, "utf8"))).toEqual( - buildPresetConfig("support-tools", "generic-npx", { - npmPackage: "@scope/server@1.2.3", - credentialEnv: "SUPPORT_TOKEN" - }) + buildPresetConfig("support-tools", preset, options) ); await expect(service.onboardPreset({ name: "replacement", - preset: "generic" + preset, + ...options })).rejects.toMatchObject({ code: "CONFIG_ALREADY_EXISTS" }); }); + it("refuses a Windows npx preset before it can create a Console configuration", async () => { + Object.defineProperty(process, "platform", { configurable: true, value: "win32" }); + const root = await mkdtemp(join(tmpdir(), "miftah-console-windows-npx-")); + temporaryDirectories.push(root); + const configPath = join(root, "miftah", "miftah.json"); + const service = new ConsoleApplicationService(configPath); + + await expect(service.onboardPreset({ + name: "unsafe-npx", + preset: "generic-npx", + npmPackage: "@scope/server@1.2.3" + })).rejects.toMatchObject({ + code: "CONFIG_SCHEMA_INVALID", + message: expect.stringContaining("unavailable on Windows") + }); + await expect(readFile(configPath, "utf8")).rejects.toMatchObject({ code: "ENOENT" }); + }); + it("creates an explicitly acknowledged local stdio configuration through the same preset path", async () => { const root = await mkdtemp(join(tmpdir(), "miftah-console-local-stdio-")); temporaryDirectories.push(root); diff --git a/tests/console-dashboard-application-service.test.ts b/tests/console-dashboard-application-service.test.ts index 3a63626a..358ccf55 100644 --- a/tests/console-dashboard-application-service.test.ts +++ b/tests/console-dashboard-application-service.test.ts @@ -4,6 +4,7 @@ import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import { discoverConsoleConfigCatalog } from "../src/console/console-config-catalog.js"; import { ConsoleDashboardApplicationService } from "../src/console/console-dashboard-application-service.js"; +import { buildPresetConfig } from "../src/config/presets.js"; import { verifyWindowsConfigPathSecurity } from "../src/cli/windows-config-acl.js"; import { createPrivateConsoleDirectory, @@ -12,6 +13,22 @@ import { const temporaryDirectories: string[] = []; +function supportedKnownConnectorOptions(): { + readonly preset: string; + readonly npmPackage?: string; + readonly dockerImage?: string; +} { + return process.platform === "win32" + ? { + preset: "generic-docker", + dockerImage: "ghcr.io/acme/server@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + } + : { + preset: "generic-npx", + npmPackage: "@scope/server@1.2.3" + }; +} + function importableClientEntry(): { readonly command: string; readonly args: readonly string[] } { return process.platform === "win32" ? { command: process.execPath, args: ["server.mjs"] } @@ -148,15 +165,15 @@ describe("Console dashboard application service", () => { launcher: { command: process.execPath, args: ["serve"] } }); + const { preset, ...presetOptions } = supportedKnownConnectorOptions(); await expect(service.onboardPreset({ name: "support-tools", - preset: "generic-npx", - npmPackage: "@scope/server@1.2.3" + preset, + ...presetOptions })).resolves.toMatchObject({ name: "support-tools", defaultProfile: "default" }); - expect(JSON.parse(await readFile(configPath, "utf8"))).toMatchObject({ - name: "support-tools", - upstream: { args: ["--yes", "@scope/server@1.2.3"] } - }); + expect(JSON.parse(await readFile(configPath, "utf8"))).toEqual( + buildPresetConfig("support-tools", preset, presetOptions) + ); await expect(service.health()).rejects.toMatchObject({ code: "CONSOLE_CONFIGURATION_SELECTION_REQUIRED" }); }); diff --git a/tests/console-server.test.ts b/tests/console-server.test.ts index 5b1f48df..b6e506c6 100644 --- a/tests/console-server.test.ts +++ b/tests/console-server.test.ts @@ -18,6 +18,25 @@ import { const temporaryDirectories: string[] = []; +function supportedKnownConnectorOptions(): { + readonly preset: string; + readonly credentialEnv: string; + readonly npmPackage?: string; + readonly dockerImage?: string; +} { + return process.platform === "win32" + ? { + preset: "generic-docker", + dockerImage: "ghcr.io/acme/server@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", + credentialEnv: "SUPPORT_TOKEN" + } + : { + preset: "generic-npx", + npmPackage: "@scope/server@1.2.3", + credentialEnv: "SUPPORT_TOKEN" + }; +} + function importableClientEntry(): { readonly command: string; readonly args: readonly string[] } { return process.platform === "win32" ? { command: process.execPath, args: ["server.mjs"] } @@ -971,9 +990,7 @@ describe("local Console control server", () => { const endpoint = new URL("/api/v1/onboarding/preset", server.url); const request = { name: "support-tools", - preset: "generic-npx", - npmPackage: "@scope/server@1.2.3", - credentialEnv: "SUPPORT_TOKEN" + ...supportedKnownConnectorOptions() }; const missingCsrf = await fetch(endpoint, { method: "POST", @@ -1018,7 +1035,7 @@ describe("local Console control server", () => { name: "support-tools", defaultProfile: "default", profileCount: 1, - actions: ["Created Miftah configuration 'support-tools' from preset 'generic-npx'."] + actions: [`Created Miftah configuration 'support-tools' from preset '${request.preset}'.`] } }); expect(JSON.parse(await readFile(configPath, "utf8"))).toMatchObject({ diff --git a/tests/doctor.test.ts b/tests/doctor.test.ts index 7401987d..a34b2116 100644 --- a/tests/doctor.test.ts +++ b/tests/doctor.test.ts @@ -67,6 +67,27 @@ function check(report: Awaited>, code: DoctorCode): return found; } +async function withPlatform(platform: NodeJS.Platform, run: () => Promise): Promise { + const descriptor = Object.getOwnPropertyDescriptor(process, "platform"); + if (descriptor === undefined) throw new Error("Unable to override the platform for this test."); + Object.defineProperty(process, "platform", { ...descriptor, value: platform }); + try { + return await run(); + } finally { + Object.defineProperty(process, "platform", descriptor); + } +} + +async function withWorkingDirectory(directory: string, run: () => Promise): Promise { + const originalDirectory = process.cwd(); + process.chdir(directory); + try { + return await run(); + } finally { + process.chdir(originalDirectory); + } +} + afterEach(async () => { await rm(fixtureDirectory, { force: true, recursive: true }); }); @@ -628,6 +649,128 @@ describe("doctor readiness runner", () => { expect(serialized).not.toContain("miftah-doctor-missing-executable"); }); + it("reports a Windows command shim as unavailable before runtime startup", async () => { + const commandShim = join(fixtureDirectory, "windows-command-shim", "provider.cmd"); + await mkdir(dirname(commandShim), { recursive: true }); + await writeFile(commandShim, "", { mode: 0o700 }); + const { configPath } = await writeConfig( + "windows-command-shim", + baseConfig({ transport: "stdio", command: commandShim, args: [] }) + ); + + const report = await withPlatform("win32", () => runDoctor(configPath)); + + expect(check(report, DOCTOR_CODES.EXECUTABLE).status).toBe("error"); + expect(check(report, DOCTOR_CODES.STARTUP).status).toBe("error"); + expect(JSON.stringify(report)).not.toContain(commandShim); + }); + + it("reports a Windows command-shell executable as unavailable before runtime startup", async () => { + const commandShell = join(fixtureDirectory, "windows-command-shell", "cmd.exe"); + await mkdir(dirname(commandShell), { recursive: true }); + await writeFile(commandShell, "", { mode: 0o700 }); + const { configPath } = await writeConfig( + "windows-command-shell", + baseConfig({ transport: "stdio", command: commandShell, args: [] }) + ); + + const report = await withPlatform("win32", () => runDoctor(configPath)); + + expect(check(report, DOCTOR_CODES.EXECUTABLE).status).toBe("error"); + expect(check(report, DOCTOR_CODES.STARTUP).status).toBe("error"); + expect(JSON.stringify(report)).not.toContain(commandShell); + }); + + it("uses the effective case-insensitive Windows profile environment for direct executable readiness", async () => { + const commandDirectory = join(fixtureDirectory, "windows-path-casing", "cwd"); + const executable = "C:\\tools\\provider.exe"; + await mkdir(commandDirectory, { recursive: true }); + await writeFile(join(commandDirectory, executable), "x", { mode: 0o700 }); + const { configPath } = await writeConfig( + "windows-path-casing", + { + version: "1", + name: "windows-path-casing", + defaultProfile: "default", + upstreams: { primary: { transport: "stdio", command: "provider", args: [] } }, + profiles: { + default: { + env: { PATH: "C:\\missing" }, + upstreams: { primary: { env: { Path: "C:\\tools" } } } + } + }, + process: { startupTimeoutMs: 1_000, shutdownTimeoutMs: 1_000 } + } + ); + + const report = await withWorkingDirectory(commandDirectory, () => withPlatform("win32", () => runDoctor(configPath))); + + expect(check(report, DOCTOR_CODES.EXECUTABLE).status).toBe("pass"); + }); + + it("expands the effective Windows profile environment before direct executable readiness", async () => { + const commandDirectory = join(fixtureDirectory, "windows-path-expansion", "cwd"); + const executable = "C:\\tools\\provider.exe"; + const environmentVariable = "MIFTAH_DOCTOR_WINDOWS_PROVIDER_PATH"; + const originalValue = process.env[environmentVariable]; + await mkdir(commandDirectory, { recursive: true }); + await writeFile(join(commandDirectory, executable), "x", { mode: 0o700 }); + const { configPath } = await writeConfig( + "windows-path-expansion", + { + version: "1", + name: "windows-path-expansion", + defaultProfile: "default", + upstreams: { primary: { transport: "stdio", command: "provider", args: [] } }, + profiles: { + default: { + upstreams: { primary: { env: { Path: `\${${environmentVariable}}` } } } + } + }, + process: { startupTimeoutMs: 1_000, shutdownTimeoutMs: 1_000 } + } + ); + + process.env[environmentVariable] = "C:\\tools"; + try { + const report = await withWorkingDirectory(commandDirectory, () => withPlatform("win32", () => runDoctor(configPath))); + + expect(check(report, DOCTOR_CODES.EXECUTABLE).status).toBe("pass"); + } finally { + if (originalValue === undefined) delete process.env[environmentVariable]; + else process.env[environmentVariable] = originalValue; + } + }); + + it("resolves target secret references before Windows direct executable readiness", async () => { + const commandDirectory = join(fixtureDirectory, "windows-path-secret-reference", "cwd"); + const executable = "C:\\tools\\provider.exe"; + await mkdir(commandDirectory, { recursive: true }); + await writeFile(join(commandDirectory, executable), "x", { mode: 0o700 }); + const { configPath } = await writeConfig( + "windows-path-secret-reference", + { + version: "1", + name: "windows-path-secret-reference", + defaultProfile: "default", + upstreams: { primary: { transport: "stdio", command: "provider", args: [] } }, + profiles: { + default: { + upstreams: { primary: { env: { Path: "secretref:dotenv://MIFTAH_DOCTOR_WINDOWS_PROVIDER_PATH" } } } + } + }, + secrets: { envFiles: [".env"] }, + process: { startupTimeoutMs: 1_000, shutdownTimeoutMs: 1_000 } + }, + { MIFTAH_DOCTOR_WINDOWS_PROVIDER_PATH: "C:\\tools" } + ); + + const report = await withWorkingDirectory(commandDirectory, () => withPlatform("win32", () => runDoctor(configPath))); + + expect(check(report, DOCTOR_CODES.EXECUTABLE).status).toBe("pass"); + expect(JSON.stringify(report)).not.toContain("C:\\tools"); + }); + it("does not leak secrets when initialization fails", async () => { const secret = "doctor-initialize-secret"; const { configPath } = await writeConfig( diff --git a/tests/executable-resolver.test.ts b/tests/executable-resolver.test.ts index d621ba38..be03329f 100644 --- a/tests/executable-resolver.test.ts +++ b/tests/executable-resolver.test.ts @@ -2,7 +2,7 @@ import { mkdir, rm, writeFile } from "node:fs/promises"; import { delimiter, join, win32 } from "node:path"; import { randomUUID } from "node:crypto"; import { afterAll, describe, expect, it } from "vitest"; -import { resolveExecutablePath } from "../src/secrets/executable-resolver.js"; +import { resolveExecutablePath, resolveWindowsDirectExecutablePath } from "../src/secrets/executable-resolver.js"; const testRoot = join(process.cwd(), ".miftah-executable-resolver-tests"); @@ -20,11 +20,85 @@ async function inSandbox(run: (directory: string) => Promise): Promise } } +async function inWindowsPathSandbox(run: () => Promise): Promise { + const originalDirectory = process.cwd(); + return inSandbox(async (directory) => { + process.chdir(directory); + try { + return await run(); + } finally { + process.chdir(originalDirectory); + } + }); +} + async function createExecutableMarker(path: string): Promise { await writeFile(path, "", { mode: 0o700 }); } describe("secret executable resolution", () => { + it.runIf(process.platform === "win32")( + "resolves a Windows PATH command only through .exe or .com candidates", + async () => { + await inSandbox(async (directory) => { + const binDirectory = win32.join(directory, "bin"); + const executable = win32.join(binDirectory, "provider.exe"); + const commandShim = win32.join(binDirectory, "provider.cmd"); + await mkdir(binDirectory); + await Promise.all([createExecutableMarker(executable), createExecutableMarker(commandShim)]); + + await expect( + resolveWindowsDirectExecutablePath("provider", { + platform: "win32", + environment: { PATH: binDirectory } + }) + ).resolves.toBe(executable); + await expect( + resolveWindowsDirectExecutablePath(commandShim, { + platform: "win32", + environment: { PATH: binDirectory } + }) + ).resolves.toBeUndefined(); + }); + } + ); + + it.runIf(process.platform !== "win32")( + "applies the direct Windows executable policy with Windows PATH semantics", + async () => { + await inWindowsPathSandbox(async () => { + const executable = "C:\\tools\\provider.exe"; + const comExecutable = "C:\\tools\\provider.com"; + await Promise.all([createExecutableMarker(executable), createExecutableMarker(comExecutable)]); + + await expect( + resolveWindowsDirectExecutablePath("provider", { + platform: "win32", + environment: { Path: '"C:\\tools"' } + }) + ).resolves.toBe(executable); + await expect( + resolveWindowsDirectExecutablePath("provider.com", { + platform: "win32", + environment: { PATH: "relative;C:\\tools" } + }) + ).resolves.toBe(comExecutable); + await expect( + resolveWindowsDirectExecutablePath("C:\\tools\\missing.exe", { platform: "win32", environment: {} }) + ).resolves.toBeUndefined(); + }); + } + ); + + it("fails closed when a Windows direct executable cannot be established", async () => { + await expect(resolveWindowsDirectExecutablePath("provider", { platform: "darwin" })).resolves.toBeUndefined(); + await expect(resolveWindowsDirectExecutablePath("", { platform: "win32", environment: {} })).resolves.toBeUndefined(); + await expect(resolveWindowsDirectExecutablePath("provider\u0000", { platform: "win32", environment: {} })).resolves.toBeUndefined(); + await expect(resolveWindowsDirectExecutablePath("provider", { platform: "win32", environment: {} })).resolves.toBeUndefined(); + await expect(resolveWindowsDirectExecutablePath(".\\provider.exe", { platform: "win32", environment: {} })).resolves.toBeUndefined(); + await expect(resolveWindowsDirectExecutablePath("C:\\tools\\provider.cmd", { platform: "win32", environment: {} })).resolves.toBeUndefined(); + }); + it("resolves a bare command from an absolute PATH entry", async () => { await inSandbox(async (directory) => { const binDirectory = join(directory, "bin"); diff --git a/tests/init-command.test.ts b/tests/init-command.test.ts index ae52b41b..0ebfad13 100644 --- a/tests/init-command.test.ts +++ b/tests/init-command.test.ts @@ -7,6 +7,7 @@ import { runInitCommand } from "../src/cli/init.js"; import { CliUsageError } from "../src/cli/parse.js"; const outputRoot = resolve(process.cwd(), ".init-command-test-output"); +const platformDescriptor = Object.getOwnPropertyDescriptor(process, "platform"); interface TtyStreams { readonly input: PassThrough & { isTTY?: boolean }; @@ -73,11 +74,12 @@ beforeEach(async () => { }); afterEach(async () => { + if (platformDescriptor !== undefined) Object.defineProperty(process, "platform", platformDescriptor); await rm(outputRoot, { recursive: true, force: true }); }); describe("init command", () => { - it("keeps noninteractive init config-only output compatible and writes a strict valid config", async () => { + it.skipIf(process.platform === "win32")("keeps noninteractive generic init output compatible and writes a strict valid config", async () => { const streams = createStreams(); const output = resolve(outputRoot, "generic.json"); @@ -89,15 +91,37 @@ describe("init command", () => { expect(streams.transcript.contents).toBe(`Created ${output}\n`); }); + it("requires an explicit safe preset for Windows instead of silently selecting the shell-backed generic preset", async () => { + Object.defineProperty(process, "platform", { configurable: true, value: "win32" }); + const streams = createStreams(); + const output = resolve(outputRoot, "windows-default.json"); + + await expect( + runInitCommand({ name: "windows-default", output: "windows-default.json" }, commandContext(streams)) + ).rejects.toThrow("On Windows, specify --preset explicitly"); + await expectNoPath(output); + streams.input.end(); + }); + it("reports an existing output file as a usage error without changing it", async () => { const streams = createStreams(); const output = resolve(outputRoot, "existing.json"); - await runInitCommand({ name: "existing", output: "existing.json" }, commandContext(streams)); + await runInitCommand({ + name: "existing", + preset: "streamable-http", + url: "https://mcp.example.com/v1", + output: "existing.json" + }, commandContext(streams)); const originalContents = await readFile(output, "utf8"); await expect( - runInitCommand({ name: "replacement", output: "existing.json" }, commandContext(streams)) + runInitCommand({ + name: "replacement", + preset: "streamable-http", + url: "https://mcp.example.com/v1", + output: "existing.json" + }, commandContext(streams)) ).rejects.toThrow(CliUsageError); expect(await readFile(output, "utf8")).toBe(originalContents); @@ -134,7 +158,13 @@ describe("init command", () => { const streams = createStreams(); const output = resolve(outputRoot, "client.json"); - await runInitCommand({ name: "client", output: "client.json", client: "cursor" }, commandContext(streams)); + await runInitCommand({ + name: "client", + preset: "streamable-http", + url: "https://mcp.example.com/v1", + output: "client.json", + client: "cursor" + }, commandContext(streams)); streams.input.end(); expect(JSON.parse(await readFile(output, "utf8"))).toMatchObject({ name: "client" }); @@ -154,7 +184,13 @@ describe("init command", () => { const streams = createStreams(); const output = resolve(outputRoot, "miftah.json"); - await runInitCommand({ name: "miftah", output: "miftah.json", client: "claude-code" }, commandContext(streams)); + await runInitCommand({ + name: "miftah", + preset: "streamable-http", + url: "https://mcp.example.com/v1", + output: "miftah.json", + client: "claude-code" + }, commandContext(streams)); streams.input.end(); expect(streams.transcript.contents).toContain("Claude Code settings permissions:"); @@ -166,7 +202,7 @@ describe("init command", () => { await expect(readFile(output, "utf8")).resolves.toContain('"name": "miftah"'); }); - it("runs the TTY wizard with real streams for a generic config", async () => { + it.skipIf(process.platform === "win32")("runs the TTY wizard with real streams for a generic config", async () => { const streams = createStreams(); const output = resolve(outputRoot, "wizard-generic.json"); const command = runInitCommand({ interactive: true }, commandContext(streams)); @@ -183,7 +219,7 @@ describe("init command", () => { expect(streams.transcript.contents).toContain("Claude Code project .mcp.json (claude-code):"); }); - it("prompts for generic-npx metadata and validates the resulting config", async () => { + it.skipIf(process.platform === "win32")("prompts for generic-npx metadata and validates the resulting config", async () => { const streams = createStreams(); const output = resolve(outputRoot, "wizard-npx.json"); const command = runInitCommand( @@ -315,7 +351,8 @@ describe("init command", () => { { interactive: true, name: "fully-supplied", - preset: "generic", + preset: "generic-docker", + dockerImage: "ghcr.io/acme/server@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", output: "fully-supplied.json", client: "all" }, diff --git a/tests/package-contract.test.ts b/tests/package-contract.test.ts index 387c1953..ab7430f4 100644 --- a/tests/package-contract.test.ts +++ b/tests/package-contract.test.ts @@ -1393,7 +1393,19 @@ describe("packed artifact contract", () => { const initOutputPath = join(cliContractDirectory, "generated output with spaces", "starter config with spaces.json"); const initialized = runInstalledBinaryThroughShell( binary, - ["init", "starter config with spaces", "--preset", "generic", "--output", initOutputPath], + process.platform === "win32" + ? [ + "init", + "starter config with spaces", + "--preset", + "local-stdio", + "--local-command", + process.execPath, + "--accept-local-command", + "--output", + initOutputPath + ] + : ["init", "starter config with spaces", "--preset", "generic", "--output", initOutputPath], cliContractDirectory ); expect(initialized.status, initialized.stderr || initialized.stdout).toBe(0); diff --git a/tests/preset-catalog.test.ts b/tests/preset-catalog.test.ts index fbd86093..326c6011 100644 --- a/tests/preset-catalog.test.ts +++ b/tests/preset-catalog.test.ts @@ -47,16 +47,10 @@ describe("preset catalog", () => { it("builds every catalog config as a valid strict Miftah config without literal secrets", () => { const genericOptions = { credentialEnv: "GENERIC_TOKEN" }; const configs = [ - buildPresetConfig("generic", "generic", genericOptions), buildPresetConfig("github", "github"), - buildPresetConfig("sentry", "sentry"), buildPresetConfig("gsc", "google-search-console", { oauthClientSecretsFile: gscClientSecretsFile }), - buildPresetConfig("npx", "generic-npx", { - npmPackage: "@scope/server@1.2.3", - credentialEnv: "NPM_SERVER_TOKEN" - }), buildPresetConfig("docker", "generic-docker", { dockerImage: "ghcr.io/acme/server@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", credentialEnv: "DOCKER_SERVER_TOKEN" @@ -72,7 +66,17 @@ describe("preset catalog", () => { credentialEnv: "REMOTE_TOKEN", headerName: "Authorization", headerPrefix: "Bearer " - }) + }), + ...(process.platform === "win32" + ? [] + : [ + buildPresetConfig("generic", "generic", genericOptions), + buildPresetConfig("sentry", "sentry"), + buildPresetConfig("npx", "generic-npx", { + npmPackage: "@scope/server@1.2.3", + credentialEnv: "NPM_SERVER_TOKEN" + }) + ]) ]; for (const config of configs) { @@ -82,11 +86,8 @@ describe("preset catalog", () => { }); it("builds exact provider contracts with only environment secret references", () => { - const generic = buildPresetConfig("generic", "generic"); const github = buildPresetConfig("github", "github"); - const sentry = buildPresetConfig("sentry", "sentry"); - expect(generic.upstream?.args).toEqual(["--yes", "@modelcontextprotocol/server-everything@2026.7.4", "stdio"]); expect(github.upstream?.args).toEqual([ "run", "-i", @@ -102,6 +103,12 @@ describe("preset catalog", () => { work: { env: { GITHUB_PERSONAL_ACCESS_TOKEN: "${GITHUB_WORK_TOKEN}" }, policy: "readonly" }, personal: { env: { GITHUB_PERSONAL_ACCESS_TOKEN: "${GITHUB_PERSONAL_TOKEN}" }, policy: "readonly" } }); + + if (process.platform === "win32") return; + + const generic = buildPresetConfig("generic", "generic"); + const sentry = buildPresetConfig("sentry", "sentry"); + expect(generic.upstream?.args).toEqual(["--yes", "@modelcontextprotocol/server-everything@2026.7.4", "stdio"]); expect(sentry.upstream?.args).toEqual(["--yes", "@sentry/mcp-server@0.36.0", "--skills=inspect"]); expect(sentry.profiles.default).toMatchObject({ env: { SENTRY_ACCESS_TOKEN: "${SENTRY_ACCESS_TOKEN}" }, @@ -213,12 +220,14 @@ describe("preset catalog", () => { }); it("requires and validates exact generic preset inputs", () => { - expect(() => buildPresetConfig("npx", "generic-npx", { npmPackage: "server@1.2.3" })).not.toThrow(); - expect(() => buildPresetConfig("npx", "generic-npx", { npmPackage: "@scope/server@1.2.3" })).not.toThrow(); - expect(buildPresetConfig("npx", "generic-npx", { npmPackage: "@sentry/mcp-server@0.36.0" }).upstream?.args).toEqual([ - "--yes", - "@sentry/mcp-server@0.36.0" - ]); + if (process.platform !== "win32") { + expect(() => buildPresetConfig("npx", "generic-npx", { npmPackage: "server@1.2.3" })).not.toThrow(); + expect(() => buildPresetConfig("npx", "generic-npx", { npmPackage: "@scope/server@1.2.3" })).not.toThrow(); + expect(buildPresetConfig("npx", "generic-npx", { npmPackage: "@sentry/mcp-server@0.36.0" }).upstream?.args).toEqual([ + "--yes", + "@sentry/mcp-server@0.36.0" + ]); + } expect(() => buildPresetConfig("npx", "generic-npx", { npmPackage: "server@latest" })).toThrow(PresetCatalogError); expect(() => buildPresetConfig("npx", "generic-npx", { npmPackage: "server@^1.2.3" })).toThrow(PresetCatalogError); expect(() => buildPresetConfig("npx", "generic-npx", { npmPackage: "server" })).toThrow(PresetCatalogError); @@ -228,8 +237,10 @@ describe("preset catalog", () => { expect(() => buildPresetConfig("npx", "generic-npx", { npmPackage: "server@1.2.3-alpha.01" })).toThrow( PresetCatalogError ); - expect(() => buildPresetConfig("npx", "generic-npx", { npmPackage: "server@1.2.3-0" })).not.toThrow(); - expect(() => buildPresetConfig("npx", "generic-npx", { npmPackage: "server@1.2.3-01alpha" })).not.toThrow(); + if (process.platform !== "win32") { + expect(() => buildPresetConfig("npx", "generic-npx", { npmPackage: "server@1.2.3-0" })).not.toThrow(); + expect(() => buildPresetConfig("npx", "generic-npx", { npmPackage: "server@1.2.3-01alpha" })).not.toThrow(); + } expect(() => buildPresetConfig("docker", "generic-docker", { dockerImage: "ghcr.io/acme/server:latest" })).toThrow( PresetCatalogError ); @@ -297,6 +308,14 @@ describe("preset catalog", () => { } }); + it("rejects the legacy Windows command interpreter as a local stdio executable", () => { + expect(() => buildPresetConfig("local-tools", "local-stdio", { + localCommand: "COMMAND.COM", + args: ["/c", "server"], + acceptLocalCommand: true + })).toThrow(PresetCatalogError); + }); + it("requires a direct Windows binary for local stdio instead of a command-processor shim", () => { Object.defineProperty(process, "platform", { configurable: true, value: "win32" }); const base = { args: ["server.mjs"], acceptLocalCommand: true } as const; @@ -306,6 +325,24 @@ describe("preset catalog", () => { } }); + it("does not create npx-backed presets on Windows where npm requires a command shell", () => { + Object.defineProperty(process, "platform", { configurable: true, value: "win32" }); + + expect(() => buildPresetConfig("generic", "generic")).toThrow(PresetCatalogError); + expect(() => buildPresetConfig("sentry", "sentry")).toThrow(PresetCatalogError); + expect(() => buildPresetConfig("npx", "generic-npx", { npmPackage: "@scope/server@1.2.3" })).toThrow( + PresetCatalogError + ); + }); + + it("validates generic-npx input before rejecting its Windows package runner", () => { + Object.defineProperty(process, "platform", { configurable: true, value: "win32" }); + + expect(() => + buildPresetConfig("npx", "generic-npx", { npmPackage: null as unknown as string }) + ).toThrow("Preset option 'npmPackage' must be a string."); + }); + it("accepts only safe streamable HTTP credential header inputs", () => { const config = buildPresetConfig("remote", "streamable-http", { url: "https://mcp.example.com/v1", @@ -448,7 +485,9 @@ describe("preset catalog", () => { ); it("accepts explicitly undefined optional preset inputs", () => { - expect(() => buildPresetConfig("generic", "generic", { credentialEnv: undefined })).not.toThrow(); + if (process.platform !== "win32") { + expect(() => buildPresetConfig("generic", "generic", { credentialEnv: undefined })).not.toThrow(); + } expect(() => buildPresetConfig("remote", "streamable-http", { url: "https://mcp.example.com/v1", credentialEnv: undefined, diff --git a/tests/presets.test.ts b/tests/presets.test.ts index 716c73b7..d047fbf4 100644 --- a/tests/presets.test.ts +++ b/tests/presets.test.ts @@ -1,5 +1,11 @@ -import { describe, expect, it } from "vitest"; -import { presetConfig } from "../src/config/presets.js"; +import { afterEach, describe, expect, it } from "vitest"; +import { PresetCatalogError, presetConfig } from "../src/config/presets.js"; + +const platformDescriptor = Object.getOwnPropertyDescriptor(process, "platform"); + +afterEach(() => { + if (platformDescriptor !== undefined) Object.defineProperty(process, "platform", platformDescriptor); +}); describe("preset config", () => { it("generates a pinned, token-forwarding GitHub Docker preset with profile-specific env refs", () => { @@ -44,6 +50,10 @@ describe("preset config", () => { }); it("preserves the generic preset defaults", () => { + if (process.platform === "win32") { + expect(() => presetConfig("example")).toThrow(PresetCatalogError); + return; + } const config = presetConfig("example"); expect(config).toMatchObject({ @@ -61,12 +71,28 @@ describe("preset config", () => { }); it("retains the public generic fallback for unknown preset names", () => { + if (process.platform === "win32") { + expect(() => presetConfig("example", "not-a-catalog-preset")).toThrow(PresetCatalogError); + return; + } const config = presetConfig("example", "not-a-catalog-preset"); expect(config.upstream?.args).toEqual(["--yes", "@modelcontextprotocol/server-everything@2026.7.4", "stdio"]); }); + it("fails closed for legacy npx-backed presets on Windows", () => { + Object.defineProperty(process, "platform", { configurable: true, value: "win32" }); + + expect(() => presetConfig("generic")).toThrow(PresetCatalogError); + expect(() => presetConfig("fallback", "not-a-catalog-preset")).toThrow(PresetCatalogError); + expect(() => presetConfig("sentry", "sentry")).toThrow(PresetCatalogError); + }); + it("uses the Sentry package with the shared preset defaults", () => { + if (process.platform === "win32") { + expect(() => presetConfig("sentry", "sentry")).toThrow(PresetCatalogError); + return; + } const config = presetConfig("sentry", "sentry"); expect(config).toMatchObject({ diff --git a/tests/setup-command.test.ts b/tests/setup-command.test.ts index 76bec445..c2373e71 100644 --- a/tests/setup-command.test.ts +++ b/tests/setup-command.test.ts @@ -91,7 +91,12 @@ describe("setup command", () => { }); await answer(streams, "Name [miftah-wrapper]", "guided"); - await answer(streams, "Catalog preset [generic]", ""); + await answer(streams, "Catalog preset", "generic-docker"); + await answer( + streams, + "Docker image (digest-pinned)", + "ghcr.io/acme/server@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef" + ); await answer(streams, "Output location [guided.miftah.json]", "guided.json"); await answer(streams, "Client", ""); await command; @@ -592,7 +597,7 @@ describe("setup command", () => { }); await answer(streams, "Name [miftah-wrapper]", "gsc"); - await answer(streams, "Catalog preset [generic]", "google-search-console"); + await answer(streams, "Catalog preset", "google-search-console"); await answer(streams, "Google account profile name [google-account-1]", "google-govalidate"); await answer(streams, "Google account description (optional)", "GoValidate Google account"); await answer(streams, "Google OAuth client-secrets file (absolute path)", govalidateSecrets); diff --git a/tests/upstream-manager.test.ts b/tests/upstream-manager.test.ts index cd815ced..873acaea 100644 --- a/tests/upstream-manager.test.ts +++ b/tests/upstream-manager.test.ts @@ -40,6 +40,26 @@ async function waitFor( } describe("upstream process manager", () => { + it.runIf(process.platform === "win32")("rejects a command shim before it can create a child process", async () => { + const directory = await mkdtemp(join(tmpdir(), "miftah-windows-command-shim-")); + const markerPath = join(directory, "command-shim-ran"); + const commandShim = join(directory, "upstream.cmd"); + await writeFile(commandShim, `@echo off\r\necho command-shim-ran > "${markerPath}"\r\nexit /b 0\r\n`); + const manager = new UpstreamProcessManager( + { transport: "stdio", command: commandShim, args: [] }, + { work: {} }, + { startupTimeoutMs: 1_000 } + ); + + try { + await expect(manager.get("work")).rejects.toMatchObject({ code: "UPSTREAM_START_FAILED" }); + expect(existsSync(markerPath)).toBe(false); + } finally { + await manager.close().catch(() => undefined); + await rm(directory, { recursive: true, force: true }); + } + }); + it("preserves progress emitted immediately before an upstream response", async () => { const manager = new UpstreamProcessManager( { diff --git a/tests/windows-stdio-command.test.ts b/tests/windows-stdio-command.test.ts new file mode 100644 index 00000000..c3c78142 --- /dev/null +++ b/tests/windows-stdio-command.test.ts @@ -0,0 +1,108 @@ +import { mkdtemp, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join, win32 } from "node:path"; +import { describe, expect, it } from "vitest"; +import { resolveWindowsStdioCommand } from "../src/upstream/windows-stdio-command.js"; + +function resolver(paths: Readonly>) { + const commands: string[] = []; + return { + commands, + resolveExecutable: async (command: string) => { + commands.push(command); + return paths[command]; + } + }; +} + +describe("Windows stdio command resolution", () => { + it("passes a generated runner to the SDK only after it resolves to a direct executable", async () => { + const files = resolver({ uvx: "C:\\uv\\uvx.exe" }); + + await expect(resolveWindowsStdioCommand("uvx", ["mcp-search-console@0.3.2"], { + platform: "win32", + resolveExecutable: files.resolveExecutable + })).resolves.toEqual({ + command: "C:\\uv\\uvx.exe", + args: ["mcp-search-console@0.3.2"] + }); + expect(files.commands).toEqual(["uvx"]); + }); + + it("rejects an npx command shim instead of allowing the SDK to fall back to cmd.exe", async () => { + const files = resolver({ npx: undefined }); + + await expect(resolveWindowsStdioCommand("npx", ["--yes", "@scope/server@1.2.3"], { + platform: "win32", + resolveExecutable: files.resolveExecutable + })).rejects.toMatchObject({ code: "UPSTREAM_START_FAILED" }); + }); + + it("rejects a command shim even if a future resolver returns it", async () => { + const files = resolver({ provider: "C:\\tools\\provider.cmd" }); + + await expect(resolveWindowsStdioCommand("provider", [], { + platform: "win32", + resolveExecutable: files.resolveExecutable + })).rejects.toMatchObject({ code: "UPSTREAM_START_FAILED" }); + }); + + it("rejects an explicit shell executable even when it has a direct executable extension", async () => { + const files = resolver({ "C:\\Windows\\System32\\cmd.exe": "C:\\Windows\\System32\\cmd.exe" }); + + await expect(resolveWindowsStdioCommand("C:\\Windows\\System32\\cmd.exe", ["/d", "/s", "/c", "server"], { + platform: "win32", + resolveExecutable: files.resolveExecutable + })).rejects.toMatchObject({ code: "UPSTREAM_START_FAILED" }); + }); + + it("rejects the legacy Windows command interpreter", async () => { + const files = resolver({ "C:\\Windows\\System32\\COMMAND.COM": "C:\\Windows\\System32\\COMMAND.COM" }); + + await expect(resolveWindowsStdioCommand("C:\\Windows\\System32\\COMMAND.COM", ["/c", "server"], { + platform: "win32", + resolveExecutable: files.resolveExecutable + })).rejects.toMatchObject({ code: "UPSTREAM_START_FAILED" }); + }); + + it("rejects a POSIX shell executable even when it has a direct executable extension", async () => { + const files = resolver({ "C:\\Program Files\\Git\\bin\\bash.exe": "C:\\Program Files\\Git\\bin\\bash.exe" }); + + await expect(resolveWindowsStdioCommand("C:\\Program Files\\Git\\bin\\bash.exe", ["-c", "server"], { + platform: "win32", + resolveExecutable: files.resolveExecutable + })).rejects.toMatchObject({ code: "UPSTREAM_START_FAILED" }); + }); + + it("rejects a direct-extension file that cross-spawn would reinterpret through a shebang", async () => { + const directory = await mkdtemp(join(tmpdir(), "miftah-windows-stdio-")); + const executable = join(directory, "provider.exe"); + try { + await writeFile(executable, "#!cmd.exe\n", { mode: 0o700 }); + + await expect(resolveWindowsStdioCommand(executable, [], { platform: "win32" })).rejects.toMatchObject({ + code: "UPSTREAM_START_FAILED" + }); + } finally { + await rm(directory, { recursive: true, force: true }); + } + }); + + it.runIf(process.platform === "win32")( + "rejects a bare npx command when only an npx.cmd shim is on the final PATH", + async () => { + const directory = await mkdtemp(join(tmpdir(), "miftah-windows-stdio-")); + const commandShim = win32.join(directory, "npx.cmd"); + try { + await writeFile(commandShim, "", { mode: 0o700 }); + + await expect(resolveWindowsStdioCommand("npx", ["--yes", "@scope/server@1.2.3"], { + platform: "win32", + environment: { PATH: directory } + })).rejects.toMatchObject({ code: "UPSTREAM_START_FAILED" }); + } finally { + await rm(directory, { recursive: true, force: true }); + } + } + ); +}); diff --git a/tests/windows-stdio-docs-contract.test.ts b/tests/windows-stdio-docs-contract.test.ts new file mode 100644 index 00000000..46596a73 --- /dev/null +++ b/tests/windows-stdio-docs-contract.test.ts @@ -0,0 +1,26 @@ +import { readFileSync } from "node:fs"; +import { describe, expect, it } from "vitest"; +import { changelogIssueEntry } from "./helpers/changelog.js"; + +const readme = readFileSync(new URL("../README.md", import.meta.url), "utf8"); +const cli = readFileSync(new URL("../docs/cli.md", import.meta.url), "utf8"); +const security = readFileSync(new URL("../docs/security.md", import.meta.url), "utf8"); +const presets = readFileSync(new URL("../docs/presets-and-clients.md", import.meta.url), "utf8"); +const changelog = readFileSync(new URL("../CHANGELOG.md", import.meta.url), "utf8"); + +describe("Windows stdio launch documentation", () => { + it("explains why npx-backed presets are unavailable instead of silently using cmd.exe", () => { + expect(readme).toContain("On Windows, `generic`, `sentry`, and `generic-npx` are unavailable."); + expect(readme).toContain("Miftah refuses them instead of invoking `cmd.exe`."); + expect(cli).toContain("On Windows, `generic`, `sentry`, and `generic-npx` are unavailable because npm's `npx` runner requires a command shell."); + expect(cli).toContain("On Windows, `--preset` is required for noninteractive `init`; there is no implicit generic preset."); + expect(security).toContain("Windows STDIO upstreams are resolved before the MCP SDK starts a child process."); + expect(presets).toContain("the `generic`, `sentry`, and `generic-npx` npx-backed presets are refused rather than launched through a command shell"); + expect(presets).toContain("On macOS and Linux the default preset is `generic`; on Windows an explicit supported preset is required."); + }); + + it("records the fail-closed Windows launch boundary under issue #217", () => { + expect(changelogIssueEntry(changelog, 217)).toContain("Windows STDIO"); + expect(changelogIssueEntry(changelog, 217)).toContain("cmd.exe"); + }); +});