From cb493832692503234bcbe917aae4d5425fb50572 Mon Sep 17 00:00:00 2001 From: morluto <76467478+morluto@users.noreply.github.com> Date: Mon, 16 Nov 2026 04:27:07 +0800 Subject: [PATCH] refactor(browser): take the host in Chromium, Electron and capture adapters (#11130) * refactor(browser): take the host in Chromium, Electron and capture adapters chromiumSandboxEnabled and safeElectronEnvironment take a required platform. The scenario browser, native module resolver, Electron provider and capture cleanup, mitmproxy adapter and web script artifacts take an optional platform seam (default HOST_PLATFORM); Electron fuses read the host architecture from HOST_PLATFORM. Their tests inject the platform instead of redefining process.platform. src/browser no longer reads process.platform or process.arch. * refactor(pcap): take the host platform in the packet tools, native bound and batch launch (#11141) * refactor(pcap): take the host platform in the packet tools, native bound and batch launch * test(pcap): cover the selected host in batch launch and capture-host support * refactor(apktool): take the host platform in launcher selection, version probe and decode (#11164) * refactor(apktool): take the host platform in launcher selection, version probe and decode * test(apktool): cover the provider's selected host in launcher selection * refactor(hopper): give the launcher the provider's host platform * refactor(native): inject the host into the pwntools decoders and native capability defaults (#11173) * refactor(native): inject the host into the pwntools decoders and native capability defaults * fix(native): give composed pwntools services the capability host and drop empty test hooks * refactor(adb): take the host platform in binary selection and pulled file names (#11176) * refactor(adb): take the host platform in binary selection and pulled file names * refactor(cli): pass the resolved host platform through rea mcp add (#11179) * refactor(cli): pass the resolved host platform through rea mcp add * refactor(composition): default composition entry points to HOST_PLATFORM and pass it to Hopper and IDA (#11183) * refactor(kuna): require the host platform in admission and installation, and give it to the session client (#11186) * refactor(kuna): require the host platform in admission and installation, and give it to the session client * fix(kuna): pass the host platform from the JavaScript installation callers verify-real-kuna, both native oracle helpers and the command-lifetime child script call inspectKunaInstallation from dist, where TypeScript cannot see the now-required platform. They passed undefined and got unsupported_host on supported hosts. * refactor(server): give createServer a host option and pass it to session tools, sigrok and EVM (#11203) * refactor(server): give createServer a host option and pass it to session tools, sigrok and EVM createServer read process.platform and process.arch live for its capability services, and registerSessionTools read process.platform for process capture. A host option (default HOST_PLATFORM) now selects both, and composition passes the capability host to the sigrok provider and the EVM provider (execution gate, limiter probe and environment rules), as it does for pwntools. hostRestrictedAvailabilityMcp selects its host through the option instead of redefining process.platform and process.arch, and moves to the MCP boundary lane since it no longer touches process-global state. evmCleanupRetry passes SIMULATED_LINUX_X64 to the provider instead of 52 property redefinitions; the fixture moves to tests/fixtures/simulatedHost.ts. * refactor(desktop): require the host platform in build computer and secret folder paths (#11210) * refactor(desktop): require the host platform in build computer and secret folder paths buildComputerArchiveDirectory, defaultBuildComputerArchive, resolveBuildComputerEnvironment and buildSecretsDirectory defaulted to process.platform. Every caller but DesktopBuildComputers' secret folder already passed the platform; it now passes HOST_PLATFORM.platform, which it reads for the build environment. * refactor(filesystem): default caller paths and ChangeTime settling to HOST_PLATFORM (#11212) appendCallerPath, absoluteCallerPath and the ChangeTime settle seams defaulted to a live process.platform read. Their defaults now come from HOST_PLATFORM: the 59 callers that omit the platform join or settle paths they open on this host, and callers describing another host's layout already pass it. The webScriptExport case that redefined process.platform to reach the Windows settle budget moves to its own file, which selects Windows by mocking HostPlatform. * fix(server): report process capture availability for the server's host sessionAvailabilityPolicy imported platform from node:process, so with a selected host binary_session reported capture_process_scenario from the running host while planning and capture used the selected one. It takes the platform from createServer and registerSessionTools. hostRestrictedAvailabilityMcp checks discovery against a dry-run plan on win32 and linux hosts. * build(guards): count platform and arch imports from node:process and node:os as ambient host reads sessionAvailabilityPolicy's named import of platform from node:process escaped the ambient-host-platform guard. The guards now also match named platform/arch imports from node:process or node:os and os.platform()/os.arch(). The one other site, DesktopApplicationCapture's os.arch(), records the capturing host and now reads HOST_PLATFORM.architecture. * refactor(config): take the host platform in parseConfig and give debugger managers the capability host (#11237) * refactor(config): take the host platform in parseConfig and give debugger managers the capability host parseConfig read process.platform for the default Hopper launcher; it takes the platform (default HOST_PLATFORM). GdbSessionManager and RizinDebugSessionManager default their platform to HOST_PLATFORM, and composition passes the capability host that already decides their availability. GDB's /proc descriptor check reads HOST_PLATFORM explicitly: it inspects this host's /proc whatever host the manager models. * refactor(firmware): give the firmware and Wakaru providers the capability host (#11239) * refactor(firmware): give the firmware and Wakaru providers the capability host resolveFirmwareCommand and resolveWakaruCommand read process.platform (and process.arch) for their host gate. They take the platform or host as a parameter; FirmwareProvider and WakaruProvider take a host (default HOST_PLATFORM) for the gate and their environment snapshots, and composition passes the capability host that already decides their availability. The JavaScript analysis source transfer defaults to HOST_PLATFORM. artifactSelectedCommand passes SIMULATED_LINUX_X64 to both providers instead of redefining process.platform and process.arch, and the Wakaru limiter configuration cases now run on any POSIX host. * refactor(captures): give tshark the capability host and default Cutter to HOST_PLATFORM (#11240) * refactor(captures): give tshark the capability host and default Cutter to HOST_PLATFORM TsharkCaptureProvider and CutterBridgeClient defaulted their platform to process.platform. Both default to HOST_PLATFORM now, and composition passes the capability host to the packet capture service, which already decides its availability. * refactor(platform): read HOST_PLATFORM explicitly in host-only path checks (#11241) * refactor(platform): read HOST_PLATFORM explicitly in host-only path checks Electron's readlink target split, IDA's host path comparison, the inspector's reported runtime path, the server identity check and WABT's executable names all describe paths on the running host. They read HOST_PLATFORM instead of process.platform. * test(native): select the native UI verifier's host through HostPlatform (#11242) verify-native-ui.mjs reads its macOS requirement from HOST_PLATFORM, and its action test resolves the script's HostPlatform import to a simulated darwin host instead of redefining process.platform in the child preload. Simulating linux there fails the macOS requirement, so the redirect is effective. * test(mcp): check that composition forwards the selected host to execution hostRestrictedAvailabilityMcp ran execution only on darwin, where the runner's own host also refuses. The new case calls the firmware, Wakaru, tshark, sigrok and EVM tools under a darwin and a linux x64 host and requires different outcomes, so dropping a provider's host forwarding fails on any runner (checked by removing the firmware forwarding). * fix(composition): give the pcap, Apktool and ADB providers the capability host createServer's selected host decided pcap capture discovery, but the default pcap, Apktool and ADB factories built their providers with HOST_PLATFORM. The factories take the platform (default HOST_PLATFORM) and capabilityServices passes its context platform, so availability and execution follow one host. * test: import moved resources owners in host-platform fixtures * refactor(config): drop the unused host parameter from parseConfig --- .../lib/kuna-native-reference-verifier.mjs | 3 +- scripts/lib/kuna-string-verifier.mjs | 3 +- scripts/verify-native-ui.mjs | 3 +- scripts/verify-real-kuna.mjs | 3 +- scripts/verify/architecture-guards.mjs | 11 +- .../baselines/ambient-host-architecture.json | 7 - .../baselines/ambient-host-platform.json | 54 -- .../baselines/test-host-platform-stub.json | 19 +- src/adb/AdbConfiguration.test.ts | 8 +- src/adb/AdbConfiguration.ts | 2 +- src/adb/AdbDeviceOutput.test.ts | 12 +- src/adb/AdbDeviceOutput.ts | 2 +- src/adb/AdbHostFileName.test.ts | 2 +- src/adb/AdbHostFileName.ts | 2 +- src/adb/AdbProvider.test.ts | 37 ++ src/adb/AdbProvider.ts | 12 +- src/apktool/ApktoolConfiguration.test.ts | 30 +- src/apktool/ApktoolConfiguration.ts | 16 +- src/apktool/ApktoolProvider.test.ts | 20 + src/apktool/ApktoolProvider.ts | 23 +- .../ApktoolVersionProbe.lifecycle.test.ts | 7 +- .../McpClientRegistration.formats.test.ts | 37 +- .../McpClientRegistration.layers.test.ts | 14 +- ...McpClientRegistration.nativeFields.test.ts | 8 +- src/application/McpClientRegistration.test.ts | 28 +- src/application/McpClientRegistration.ts | 18 +- .../McpRegistrationConfiguration.ts | 17 +- .../desktop/DesktopApplicationCapture.ts | 9 +- .../desktop/DesktopBuildComputers.ts | 4 +- src/browser/ChromiumSandbox.ts | 2 +- src/browser/ElectronCaptureCleanup.test.ts | 21 +- src/browser/ElectronCaptureCleanup.ts | 11 +- src/browser/ElectronProcessCleanup.ts | 27 +- src/browser/PlaywrightElectronActiveFuses.ts | 5 +- .../PlaywrightElectronActiveProvider.test.ts | 57 +- .../PlaywrightElectronActiveProvider.ts | 14 +- src/browser/PlaywrightScenarioBrowser.test.ts | 7 +- src/browser/PlaywrightScenarioBrowser.ts | 13 +- src/browser/assets/LocalWebScriptArtifacts.ts | 5 +- .../history/MitmproxyCaptureAdapter.ts | 11 +- .../modules/NativeModuleResolver.test.ts | 9 +- src/browser/modules/NativeModuleResolver.ts | 9 +- src/captures/TsharkCaptureProvider.ts | 3 +- src/cli/desktopCaptureCommands.ts | 3 +- src/cli/mcpRegistration.ts | 7 +- src/composition/adb.ts | 4 +- src/composition/apktool.ts | 5 +- src/composition/auxiliaryAnalysisProviders.ts | 3 +- src/composition/binary.ts | 8 +- src/composition/binaryDiagnostics.ts | 11 +- src/composition/capabilityServices.ts | 67 +- src/composition/captures.ts | 6 +- src/composition/evm.ts | 6 +- src/composition/firmware.ts | 4 +- src/composition/javascriptRecovery.ts | 4 +- src/composition/pcap.ts | 4 +- src/composition/reverseEngineering.ts | 3 +- src/composition/signals.ts | 6 +- src/cutter/CutterBridgeClient.ts | 3 +- src/desktop/BuildComputerEnvironment.ts | 6 +- src/desktop/BuildSecretFiles.test.ts | 14 +- src/desktop/BuildSecretFiles.ts | 2 +- src/electron/ElectronFusePath.ts | 8 +- src/evm/EvmoleInterfaceProvider.ts | 30 +- src/filesystem/ChangeTimeBaseline.ts | 6 +- src/filesystem/callerPath.ts | 9 +- src/firmware/FirmwareCommand.test.ts | 4 + src/firmware/FirmwareCommand.ts | 4 +- src/firmware/FirmwareProvider.ts | 7 +- src/gdb/GdbSessionManager.ts | 6 +- src/hopper/BridgeLauncher.ts | 16 +- src/hopper/HopperClient.ts | 3 +- src/hopper/HopperProvider.ts | 20 +- src/ida/IdaWorkspace.ts | 4 +- src/inspector/JavaScriptRuntimeScope.ts | 4 +- .../JavaScriptAnalysisSourceTransfer.ts | 4 +- src/javascript/recovery/WakaruCommand.test.ts | 8 +- src/javascript/recovery/WakaruCommand.ts | 5 +- src/javascript/recovery/WakaruProvider.ts | 10 +- src/kuna/KunaAdmission.ts | 2 +- src/kuna/KunaConfiguration.ts | 2 +- src/kuna/KunaDoctor.ts | 2 +- src/kuna/KunaInstallation.ts | 3 +- src/kuna/KunaProvider.ts | 4 +- src/kuna/KunaSessionClient.ts | 4 + src/native/NativeMacOSProvider.ts | 3 +- src/native/NativeMacOSProviderMetadata.ts | 2 +- src/native/pwntools/PwntoolsDecoder.ts | 15 +- src/native/pwntools/PwntoolsLayoutProvider.ts | 3 + .../pwntools/PwntoolsRecordedCrashProvider.ts | 3 + src/native/windows/WindowsShortcutProvider.ts | 5 +- src/pcap/PcapCommand.ts | 4 +- src/pcap/PcapConfiguration.test.ts | 23 +- src/pcap/PcapConfiguration.ts | 2 +- src/pcap/PcapNativeBound.test.ts | 258 ++++---- src/pcap/PcapNativeBound.ts | 5 +- src/pcap/PcapProvider.ts | 12 +- src/rizin/RizinDebugSessionManager.ts | 3 +- src/server/createServer.ts | 18 +- src/server/providerEnvironment.ts | 7 +- src/server/registerSessionTools.ts | 12 +- src/server/sessionAvailabilityPolicy.ts | 3 +- src/serverIdentity.ts | 4 +- src/signals/SigrokRecordingProvider.ts | 3 +- src/wasm/WabtArtifactProvider.ts | 2 +- .../browser/historicalCaptureDecoder.test.ts | 15 +- tests/boundary/evm/evmCleanupRetry.test.ts | 139 +--- .../clientNativeConnectionAdmission.test.ts | 4 +- .../filesystem/kiloClientLocation.test.ts | 6 +- .../filesystem/mcpAddClientLifecycle.test.ts | 10 +- .../filesystem/webScriptExport.test.ts | 22 - .../webScriptExportWindowsChangeTime.test.ts | 41 ++ .../filesystem/webScriptManifestPaths.test.ts | 13 +- .../wakaruCommandConfiguration.test.ts | 29 +- .../mcp/hostRestrictedAvailabilityMcp.test.ts | 250 +++++++ .../native/pwntoolsArtifactCleanup.test.ts | 610 +++++++++--------- tests/boundary/pcap/pcapCommand.test.ts | 47 ++ .../pcap/pcapCredentialErrors.test.ts | 4 + .../pcap/pcapProviderCrossPlatform.test.ts | 18 + .../process/artifactSelectedCommand.test.ts | 83 +-- .../process/nativeUiVerifierActions.test.ts | 4 +- .../boundary/process/providerOutcome.test.ts | 3 + .../windowsExecutableSelection.test.ts | 14 +- .../adb/adbCommandFinalization.test.ts | 21 +- .../providers/apktoolProcessFixture.test.ts | 7 +- .../kuna/kunaCommandLifetime.test.ts | 2 + .../kuna/kunaInstallationLifetime.test.ts | 7 +- .../providers/kuna/kunaResourceScope.ts | 13 +- .../kuna/kunaVersionProbeOwnership.test.ts | 4 + .../readinessRemediationInventory.test.ts | 3 +- tests/fixtures/mcpRegistration.ts | 41 ++ tests/fixtures/simulatedHost.ts | 12 + .../hostRestrictedAvailabilityMcp.test.ts | 207 ------ tests/process-global/pwntoolsCleanup.test.ts | 30 +- .../pwntoolsCliFinalization.test.ts | 38 +- .../pwntoolsCliRemediation.test.ts | 30 +- .../pwntoolsStageRetirement.test.ts | 29 +- 137 files changed, 1674 insertions(+), 1405 deletions(-) delete mode 100644 scripts/verify/baselines/ambient-host-architecture.json delete mode 100644 scripts/verify/baselines/ambient-host-platform.json create mode 100644 tests/boundary/filesystem/webScriptExportWindowsChangeTime.test.ts create mode 100644 tests/boundary/mcp/hostRestrictedAvailabilityMcp.test.ts create mode 100644 tests/fixtures/mcpRegistration.ts create mode 100644 tests/fixtures/simulatedHost.ts delete mode 100644 tests/process-global/hostRestrictedAvailabilityMcp.test.ts diff --git a/scripts/lib/kuna-native-reference-verifier.mjs b/scripts/lib/kuna-native-reference-verifier.mjs index fd78668d0c..513db39829 100644 --- a/scripts/lib/kuna-native-reference-verifier.mjs +++ b/scripts/lib/kuna-native-reference-verifier.mjs @@ -4,6 +4,7 @@ import { realpath } from "node:fs/promises"; import { runKunaCommand } from "../../dist/kuna/KunaCommand.js"; import { kunaProjectDeadline } from "../../dist/kuna/KunaConfiguration.js"; import { inspectKunaInstallation } from "../../dist/kuna/KunaInstallation.js"; +import { HOST_PLATFORM } from "../../dist/platform/HostPlatform.js"; import { KUNA_XREF_OUTPUT_BYTES } from "../../dist/kuna/KunaReferenceFiles.js"; /** Independent projection of native exact-target rows, bypassing REA's parser. */ @@ -21,7 +22,7 @@ export const nativeKunaIncomingSites = async ({ REA_KUNA_COMMAND: executable, REA_KUNA_CACHE_DIR: cacheRoot, }, - { resourceScope }, + { platform: HOST_PLATFORM.platform, resourceScope }, ); assert.ok(installed.ok, "Native reference oracle could not inspect Kuna"); const input = await realpath(binary); diff --git a/scripts/lib/kuna-string-verifier.mjs b/scripts/lib/kuna-string-verifier.mjs index d85f6ed20c..3642edffba 100644 --- a/scripts/lib/kuna-string-verifier.mjs +++ b/scripts/lib/kuna-string-verifier.mjs @@ -5,6 +5,7 @@ import { join } from "node:path"; import { runKunaCommand } from "../../dist/kuna/KunaCommand.js"; import { kunaProjectDeadline } from "../../dist/kuna/KunaConfiguration.js"; import { inspectKunaInstallation } from "../../dist/kuna/KunaInstallation.js"; +import { HOST_PLATFORM } from "../../dist/platform/HostPlatform.js"; const entries = (path) => readdir(path).catch((cause) => { @@ -26,7 +27,7 @@ export const nativeKunaStrings = async ({ REA_KUNA_COMMAND: executable, REA_KUNA_CACHE_DIR: cacheRoot, }, - { resourceScope }, + { platform: HOST_PLATFORM.platform, resourceScope }, ); assert.ok(installed.ok, "Native string oracle could not inspect Kuna"); const input = await realpath(binary); diff --git a/scripts/verify-native-ui.mjs b/scripts/verify-native-ui.mjs index 2f606974be..35b0869ddf 100644 --- a/scripts/verify-native-ui.mjs +++ b/scripts/verify-native-ui.mjs @@ -9,9 +9,10 @@ import { observeNativeUi } from "../dist/native/NativeUiObservation.js"; import { NATIVE_UI_HELPER_MAX_BUFFER } from "../dist/native/NativeUiOutputBudget.js"; import { artifactMcpResult, withArtifactMcp } from "./lib/artifact-e2e.mjs"; import { observeProcessStartIdentity } from "../dist/process/ProcessOwnershipObservation.js"; +import { HOST_PLATFORM } from "../dist/platform/HostPlatform.js"; import { VerifierFixture } from "./lib/verifier-fixture.mjs"; -if (process.platform !== "darwin") +if (HOST_PLATFORM.platform !== "darwin") throw new Error( "Native UI verification requires macOS, an interactive desktop and Xcode command-line tools", ); diff --git a/scripts/verify-real-kuna.mjs b/scripts/verify-real-kuna.mjs index 7f9278ece9..2ea9bcddf3 100644 --- a/scripts/verify-real-kuna.mjs +++ b/scripts/verify-real-kuna.mjs @@ -17,6 +17,7 @@ import { parseArgs, promisify } from "node:util"; import { Client } from "@modelcontextprotocol/client"; import { StdioClientTransport } from "@modelcontextprotocol/client/stdio"; import { inspectKunaInstallation } from "../dist/kuna/KunaInstallation.js"; +import { HOST_PLATFORM } from "../dist/platform/HostPlatform.js"; import { KUNA_RELEASE_VERIFICATION_EXPLANATION, KUNA_UNVERIFIED_VERSION_REMEDIATION, @@ -739,7 +740,7 @@ let inspectionResourcesClean = true; try { const installation = await inspectKunaInstallation( { REA_KUNA_COMMAND: kuna, REA_KUNA_CACHE_DIR: cacheRoot }, - { resourceScope }, + { platform: HOST_PLATFORM.platform, resourceScope }, ); assert.ok( installation.ok, diff --git a/scripts/verify/architecture-guards.mjs b/scripts/verify/architecture-guards.mjs index b675c9eaf6..cbf1129498 100644 --- a/scripts/verify/architecture-guards.mjs +++ b/scripts/verify/architecture-guards.mjs @@ -713,18 +713,25 @@ checkCounted( // takes it from there and passes the platform or architecture on as a // required parameter. An ambient read elsewhere mixes the host REA runs on // with the host a caller asked about, and cannot be selected by a test. +// Named imports from node:process or node:os and os.platform()/os.arch() are +// the same read under another spelling. +const ambientHostRead = (property, osFunction) => + new RegExp( + String.raw`\bprocess\.${property}\b|\bos\.${osFunction}\(\)|\bimport\s*(?:type\s*)?\{[^}]*\b(?:${property}|${osFunction})\b[^}]*\}\s*from\s*["'](?:node:)?(?:process|os)["']`, + "gu", + ); checkCounted( "ambient process.platform read (take HOST_PLATFORM from src/platform/HostPlatform at composition and pass the platform as a parameter)", "ambient-host-platform", files, - /\bprocess\.platform\b/gu, + ambientHostRead("platform", "platform"), ["src/platform/HostPlatform.ts"], ); checkCounted( "ambient process.arch read (take HOST_PLATFORM from src/platform/HostPlatform at composition and pass the architecture as a parameter)", "ambient-host-architecture", files, - /\bprocess\.arch\b/gu, + ambientHostRead("arch", "arch"), ["src/platform/HostPlatform.ts"], ); diff --git a/scripts/verify/baselines/ambient-host-architecture.json b/scripts/verify/baselines/ambient-host-architecture.json deleted file mode 100644 index d4931b61e1..0000000000 --- a/scripts/verify/baselines/ambient-host-architecture.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "src/browser/PlaywrightElectronActiveFuses.ts": 2, - "src/evm/EvmoleInterfaceProvider.ts": 2, - "src/javascript/recovery/WakaruCommand.ts": 1, - "src/native/pwntools/PwntoolsDecoder.ts": 2, - "src/server/createServer.ts": 1 -} diff --git a/scripts/verify/baselines/ambient-host-platform.json b/scripts/verify/baselines/ambient-host-platform.json deleted file mode 100644 index 99e83169dd..0000000000 --- a/scripts/verify/baselines/ambient-host-platform.json +++ /dev/null @@ -1,54 +0,0 @@ -{ - "src/adb/AdbConfiguration.ts": 1, - "src/adb/AdbDeviceOutput.ts": 1, - "src/adb/AdbHostFileName.ts": 1, - "src/adb/AdbProvider.ts": 1, - "src/apktool/ApktoolConfiguration.ts": 4, - "src/apktool/ApktoolProvider.ts": 2, - "src/browser/ChromiumSandbox.ts": 1, - "src/browser/ElectronCaptureCleanup.ts": 1, - "src/browser/ElectronProcessCleanup.ts": 1, - "src/browser/PlaywrightElectronActiveProvider.ts": 1, - "src/browser/PlaywrightScenarioBrowser.ts": 2, - "src/browser/assets/LocalWebScriptArtifacts.ts": 1, - "src/browser/history/MitmproxyCaptureAdapter.ts": 1, - "src/captures/TsharkCaptureProvider.ts": 1, - "src/cli/desktopCaptureCommands.ts": 1, - "src/cli/mcpRegistration.ts": 2, - "src/composition/auxiliaryAnalysisProviders.ts": 1, - "src/composition/binary.ts": 2, - "src/composition/reverseEngineering.ts": 1, - "src/cutter/CutterBridgeClient.ts": 1, - "src/desktop/BuildComputerEnvironment.ts": 3, - "src/desktop/BuildSecretFiles.ts": 1, - "src/electron/ElectronFusePath.ts": 1, - "src/evm/EvmoleInterfaceProvider.ts": 2, - "src/filesystem/ChangeTimeBaseline.ts": 2, - "src/filesystem/callerPath.ts": 2, - "src/firmware/FirmwareCommand.ts": 1, - "src/gdb/GdbSessionManager.ts": 2, - "src/hopper/BridgeLauncher.ts": 4, - "src/hopper/HopperClient.ts": 1, - "src/hopper/HopperProvider.ts": 1, - "src/ida/IdaWorkspace.ts": 1, - "src/inspector/JavaScriptRuntimeScope.ts": 1, - "src/javascript/analysis/JavaScriptAnalysisSourceTransfer.ts": 1, - "src/javascript/recovery/WakaruCommand.ts": 1, - "src/kuna/KunaConfiguration.ts": 1, - "src/kuna/KunaDoctor.ts": 1, - "src/kuna/KunaProvider.ts": 1, - "src/native/NativeMacOSProvider.ts": 1, - "src/native/NativeMacOSProviderMetadata.ts": 1, - "src/native/pwntools/PwntoolsDecoder.ts": 2, - "src/native/windows/WindowsShortcutProvider.ts": 1, - "src/pcap/PcapCommand.ts": 1, - "src/pcap/PcapConfiguration.ts": 1, - "src/pcap/PcapNativeBound.ts": 2, - "src/pcap/PcapProvider.ts": 1, - "src/rizin/RizinDebugSessionManager.ts": 1, - "src/server/createServer.ts": 1, - "src/server/registerSessionTools.ts": 3, - "src/serverIdentity.ts": 1, - "src/signals/SigrokRecordingProvider.ts": 1, - "src/wasm/WabtArtifactProvider.ts": 1 -} diff --git a/scripts/verify/baselines/test-host-platform-stub.json b/scripts/verify/baselines/test-host-platform-stub.json index 7c8e2d9731..c9347077a6 100644 --- a/scripts/verify/baselines/test-host-platform-stub.json +++ b/scripts/verify/baselines/test-host-platform-stub.json @@ -1,20 +1,3 @@ { - "src/browser/ElectronCaptureCleanup.test.ts": 2, - "src/browser/PlaywrightElectronActiveProvider.test.ts": 2, - "src/browser/PlaywrightScenarioBrowser.test.ts": 3, - "src/browser/modules/NativeModuleResolver.test.ts": 3, - "src/pcap/PcapNativeBound.test.ts": 2, - "tests/boundary/browser/historicalCaptureDecoder.test.ts": 2, - "tests/boundary/cli/debuggerOneShotExit.test.ts": 1, - "tests/boundary/evm/evmCleanupRetry.test.ts": 52, - "tests/boundary/filesystem/webScriptExport.test.ts": 2, - "tests/boundary/filesystem/webScriptManifestPaths.test.ts": 2, - "tests/boundary/native/pwntoolsArtifactCleanup.test.ts": 4, - "tests/boundary/process/artifactSelectedCommand.test.ts": 6, - "tests/boundary/process/nativeUiVerifierActions.test.ts": 1, - "tests/process-global/hostRestrictedAvailabilityMcp.test.ts": 4, - "tests/process-global/pwntoolsCleanup.test.ts": 4, - "tests/process-global/pwntoolsCliFinalization.test.ts": 4, - "tests/process-global/pwntoolsCliRemediation.test.ts": 4, - "tests/process-global/pwntoolsStageRetirement.test.ts": 4 + "tests/boundary/cli/debuggerOneShotExit.test.ts": 1 } diff --git a/src/adb/AdbConfiguration.test.ts b/src/adb/AdbConfiguration.test.ts index c95a9cf74d..43aeeaa14f 100644 --- a/src/adb/AdbConfiguration.test.ts +++ b/src/adb/AdbConfiguration.test.ts @@ -20,12 +20,14 @@ describe("resolveAdbBinary", () => { it.skipIf(process.platform === "win32")( "falls back to POSIX PATH resolution without the environment key", async () => { - expect(await resolveAdbBinary({})).toEqual({ + expect(await resolveAdbBinary({}, "linux")).toEqual({ binary: "adb", pathSource: "path", environment: {}, }); - expect(await resolveAdbBinary({ [ADB_BINARY_ENV]: " " })).toEqual({ + expect( + await resolveAdbBinary({ [ADB_BINARY_ENV]: " " }, "linux"), + ).toEqual({ binary: "adb", pathSource: "path", environment: { [ADB_BINARY_ENV]: " " }, @@ -41,7 +43,7 @@ describe("resolveAdbBinary", () => { it("rejects a relative environment path explicitly", async () => { await expect( - resolveAdbBinary({ [ADB_BINARY_ENV]: "tools/adb" }), + resolveAdbBinary({ [ADB_BINARY_ENV]: "tools/adb" }, "linux"), ).rejects.toThrow(/must be an absolute path/u); }); }); diff --git a/src/adb/AdbConfiguration.ts b/src/adb/AdbConfiguration.ts index edaece23a0..e01b7da989 100644 --- a/src/adb/AdbConfiguration.ts +++ b/src/adb/AdbConfiguration.ts @@ -52,7 +52,7 @@ export interface AdbBinarySelection { */ export const resolveAdbBinary = async ( environment: Readonly>, - platform: NodeJS.Platform = process.platform, + platform: NodeJS.Platform, signal?: AbortSignal, ): Promise => { const selectedEnvironment = snapshotEnvironment(environment, platform); diff --git a/src/adb/AdbDeviceOutput.test.ts b/src/adb/AdbDeviceOutput.test.ts index a733b54dfa..3bfa37cb56 100644 --- a/src/adb/AdbDeviceOutput.test.ts +++ b/src/adb/AdbDeviceOutput.test.ts @@ -423,7 +423,7 @@ describe("parsePmPathOutput", () => { "package:/data/app/~~a==/com.example.b==/split_config.en.apk", "", ].join("\n"); - const { paths, unparsedLines } = parsePmPathOutput(output); + const { paths, unparsedLines } = parsePmPathOutput(output, "linux"); expect(unparsedLines).toEqual({ sample: [], total: 0 }); expect(paths).toEqual([ { @@ -446,7 +446,10 @@ describe("parsePmPathOutput", () => { }); it("reports an unknown role for names that follow neither convention", () => { - const { paths } = parsePmPathOutput("package:/system/app/X/Y.apk\n"); + const { paths } = parsePmPathOutput( + "package:/system/app/X/Y.apk\n", + "linux", + ); expect(paths[0]).toEqual({ device_path: "/system/app/X/Y.apk", file_name: "Y.apk", @@ -473,7 +476,7 @@ describe("parsePmPathOutput", () => { it("rejects an empty final component without normalizing the source", () => { const devicePath = "/data/app/pkg/base.apk/"; - const parsed = parsePmPathOutput(`package:${devicePath}\n`); + const parsed = parsePmPathOutput(`package:${devicePath}\n`, "linux"); expect(parsed.paths).toEqual([]); expect(parsed.rejectedPaths).toEqual([ { device_path: devicePath, reason: "empty_file_name" }, @@ -482,7 +485,8 @@ describe("parsePmPathOutput", () => { it("retains malformed lines including surrounding whitespace", () => { expect( - parsePmPathOutput(" package:/data/app/pkg/base.apk \n").unparsedLines, + parsePmPathOutput(" package:/data/app/pkg/base.apk \n", "linux") + .unparsedLines, ).toEqual({ sample: [" package:/data/app/pkg/base.apk "], total: 1 }); }); }); diff --git a/src/adb/AdbDeviceOutput.ts b/src/adb/AdbDeviceOutput.ts index 2253b1607e..9dfad6070f 100644 --- a/src/adb/AdbDeviceOutput.ts +++ b/src/adb/AdbDeviceOutput.ts @@ -275,7 +275,7 @@ export interface AdbPackagePathEntry { */ export const parsePmPathOutput = ( stdout: string, - platform: NodeJS.Platform = process.platform, + platform: NodeJS.Platform, ): { paths: readonly AdbPackagePathEntry[]; rejectedPaths: readonly { diff --git a/src/adb/AdbHostFileName.test.ts b/src/adb/AdbHostFileName.test.ts index 945fa85287..214845cd75 100644 --- a/src/adb/AdbHostFileName.test.ts +++ b/src/adb/AdbHostFileName.test.ts @@ -34,7 +34,7 @@ describe("adbHostFileName", () => { ["/data\0/local/tmp/file", "unsupported_character"], ["/data/local/tmp/a\0b", "unsupported_character"], ] as const)("refuses %s as %s", (devicePath, reason) => { - expect(adbHostFileName(devicePath)).toEqual({ ok: false, reason }); + expect(adbHostFileName(devicePath, "linux")).toEqual({ ok: false, reason }); }); it.each([ diff --git a/src/adb/AdbHostFileName.ts b/src/adb/AdbHostFileName.ts index 4ffd7cec10..4caaeaafcf 100644 --- a/src/adb/AdbHostFileName.ts +++ b/src/adb/AdbHostFileName.ts @@ -21,7 +21,7 @@ const WINDOWS_RESERVED_BASENAME = */ export const adbHostFileName = ( devicePath: string, - platform: NodeJS.Platform = process.platform, + platform: NodeJS.Platform, ): AdbHostFileNameResult => { if (devicePath === "" || devicePath.endsWith("/")) return { ok: false, reason: "empty_file_name" }; diff --git a/src/adb/AdbProvider.test.ts b/src/adb/AdbProvider.test.ts index 5b071f5fb1..1ead20e6f3 100644 --- a/src/adb/AdbProvider.test.ts +++ b/src/adb/AdbProvider.test.ts @@ -1,5 +1,6 @@ import { createHash } from "node:crypto"; import { + access, chmod, lstat, mkdir, @@ -2705,3 +2706,39 @@ it("attributes version capture failures to the public operation and retains the }, }); }); + +it("refuses a device file name the selected Windows host cannot store before pulling", async () => { + const { binary, root } = await writeAdbStub( + (root) => `if [ "$1" = "version" ]; then ${VERSION_BLOCK}; exit 0; fi +: > "${join(root, "pull-ran")}" +exit 0`, + ); + const provider = new AdbProvider({ + environment: { REA_ADB_PATH: binary }, + platform: "win32", + }); + const result = await provider.execute({ + operation: "pull_adb_file", + input: { + serial: "emulator-5554", + device_path: "/data/local/tmp/CON", + output_directory: join(root, "pulls"), + }, + }); + expect(result.ok).toBe(false); + if (result.ok) return; + expect(projectAnalysisError(result.error)).toMatchObject({ + code: "invalid_request", + details: { + issues: [ + { + path: ["device_path"], + message: expect.stringContaining("(reserved_name)"), + }, + ], + }, + }); + await expect(access(join(root, "pull-ran"))).rejects.toMatchObject({ + code: "ENOENT", + }); +}); diff --git a/src/adb/AdbProvider.ts b/src/adb/AdbProvider.ts index 1045ada048..df0adf2931 100644 --- a/src/adb/AdbProvider.ts +++ b/src/adb/AdbProvider.ts @@ -647,6 +647,8 @@ export interface AdbProviderOptions { readonly createRuntimeRoot?: ( options?: PrivateRuntimeRootOptions, ) => Promise; + /** The host adb and its pulled files live on; defaults to the running host. */ + readonly platform?: NodeJS.Platform; } type AdbRuntimeRoot = Pick; @@ -822,6 +824,7 @@ const reservePackageDestinations = async ( */ export class AdbProvider { private readonly environment: Readonly>; + private readonly platform: NodeJS.Platform; readonly #createRuntimeRoot: ( options?: PrivateRuntimeRootOptions, ) => Promise; @@ -838,9 +841,10 @@ export class AdbProvider { #outputCleanupPromise: Promise | undefined; constructor(options: AdbProviderOptions = {}) { + this.platform = options.platform ?? HOST_PLATFORM.platform; this.environment = snapshotEnvironment( options.environment ?? process.env, - HOST_PLATFORM.platform, + this.platform, ); this.#createRuntimeRoot = options.createRuntimeRoot ?? @@ -848,7 +852,7 @@ export class AdbProvider { } private selection(signal?: AbortSignal): Promise { - return resolveAdbBinary(this.environment, process.platform, signal); + return resolveAdbBinary(this.environment, this.platform, signal); } /** Probe the selected adb binary; never contacts devices or the server. */ @@ -1864,7 +1868,7 @@ export class AdbProvider { signal, ); if (!paths.ok) return paths; - const parsed = parsePmPathOutput(paths.value.stdout); + const parsed = parsePmPathOutput(paths.value.stdout, this.platform); const capturedOutput = { stdout: paths.value.stdout, stderr: paths.value.stderr, @@ -2243,7 +2247,7 @@ export class AdbProvider { }, signal: AbortSignal | undefined, ): Promise> { - const derived = adbHostFileName(input.device_path); + const derived = adbHostFileName(input.device_path, this.platform); if (!derived.ok) return err( new AnalysisInputError(operation, undefined, [ diff --git a/src/apktool/ApktoolConfiguration.test.ts b/src/apktool/ApktoolConfiguration.test.ts index a3c4f49c1b..573519351c 100644 --- a/src/apktool/ApktoolConfiguration.test.ts +++ b/src/apktool/ApktoolConfiguration.test.ts @@ -58,39 +58,39 @@ describe("resolveApktoolCommand", () => { it("rejects a relative environment path explicitly", async () => { await expect( - resolveApktoolCommand({ [APKTOOL_COMMAND_ENV]: "bin/apktool" }), + resolveApktoolCommand({ [APKTOOL_COMMAND_ENV]: "bin/apktool" }, "linux"), ).rejects.toThrow(/must be an absolute path/u); }); }); describe("parseApktoolVersionOutput", () => { it("reads the version from real apktool output", () => { - expect(parseApktoolVersionOutput("2.7.0-dirty\n")).toMatchObject({ + expect(parseApktoolVersionOutput("2.7.0-dirty\n", "linux")).toMatchObject({ version: "2.7.0-dirty", }); }); it("reports null when the launcher prints nothing usable", () => { - expect(parseApktoolVersionOutput(" \n")).toEqual({ + expect(parseApktoolVersionOutput(" \n", "linux")).toEqual({ version: null, reportedVersion: null, }); - expect(parseApktoolVersionOutput("successful but not a version\n")).toEqual( - { - version: null, - reportedVersion: "successful but not a version", - }, - ); + expect( + parseApktoolVersionOutput("successful but not a version\n", "linux"), + ).toEqual({ + version: null, + reportedVersion: "successful but not a version", + }); }); it("parses semantic prerelease versions without claiming they meet the minimum", () => { - expect(parseApktoolVersionOutput("2.7.0-beta.1\n")).toMatchObject({ + expect(parseApktoolVersionOutput("2.7.0-beta.1\n", "linux")).toMatchObject({ version: "2.7.0-beta.1", }); }); it("validates normalized semantic versions while preserving caller spelling", () => { - expect(parseApktoolVersionOutput("v2.7.0\n")).toMatchObject({ + expect(parseApktoolVersionOutput("v2.7.0\n", "linux")).toMatchObject({ version: "v2.7.0", }); }); @@ -107,7 +107,7 @@ describe("reported Apktool version policy", () => { ])( "discloses the upstream advisory for %s without claiming engine patch identity", (version) => { - const identity = parseApktoolVersionOutput(version); + const identity = parseApktoolVersionOutput(version, "linux"); if (identity.version === null) throw new Error("Expected parsed version"); expect(identity.version).toBe(version); const warnings = identity.limitations.filter((limitation) => @@ -129,7 +129,7 @@ describe("reported Apktool version policy", () => { ])( "does not attach CVE-2024-21633 to a reported version at or beyond its fix: %s", (version) => { - const identity = parseApktoolVersionOutput(version); + const identity = parseApktoolVersionOutput(version, "linux"); if (identity.version === null) throw new Error("Expected parsed version"); expect(identity).toMatchObject({ version, @@ -153,7 +153,7 @@ describe("reported Apktool version policy", () => { ] as const)( "preserves the documented release floor for %s", (version, supported) => { - expect(parseApktoolVersionOutput(version)).toMatchObject({ + expect(parseApktoolVersionOutput(version, "linux")).toMatchObject({ version, supportsDocumentedVersion: supported, }); @@ -589,6 +589,7 @@ it.each([false, true])( const result: unknown = await inspectApktoolClient( { command: "/selected/apktool", commandSource: "environment" }, commands, + { platform: "linux" }, ).catch((cause: unknown) => cause); expect(result).toBeInstanceOf(AnalysisError); if (!(result instanceof AnalysisError)) throw result; @@ -641,6 +642,7 @@ it("keeps a recorded command timeout primary with its actual inspection stop fac const result: unknown = await inspectApktoolClient( { command: "/selected/apktool", commandSource: "environment" }, commands, + { platform: "linux" }, ).catch((cause: unknown) => cause); expect(result).toMatchObject({ _tag: "AnalysisTimeoutError", diff --git a/src/apktool/ApktoolConfiguration.ts b/src/apktool/ApktoolConfiguration.ts index 021afc4589..73cabc3ad9 100644 --- a/src/apktool/ApktoolConfiguration.ts +++ b/src/apktool/ApktoolConfiguration.ts @@ -71,7 +71,7 @@ export interface ApktoolCommandSelection { */ export const resolveApktoolCommand = async ( environment: Readonly>, - platform: NodeJS.Platform = process.platform, + platform: NodeJS.Platform, signal?: AbortSignal, ): Promise => { if (signal?.aborted === true) @@ -195,7 +195,7 @@ export const apktoolInvocation = ( selection: ApktoolCommandSelection, arguments_: readonly string[], environment: Readonly, - platform: NodeJS.Platform = process.platform, + platform: NodeJS.Platform, ): ApktoolInvocation => platform === "win32" && isWindowsBatchFile(selection.command) ? { @@ -215,7 +215,7 @@ export const apktoolInvocation = ( /** Read the version from Apktool's single-line `--version` response. */ export const parseApktoolVersionOutput = ( stdout: string, - platform: NodeJS.Platform = process.platform, + platform: NodeJS.Platform, ): | ApktoolClientIdentity | { readonly version: null; readonly reportedVersion: string | null } => { @@ -278,14 +278,10 @@ export const inspectApktoolClient = async ( options: { readonly signal?: AbortSignal; readonly environment?: Readonly>; - readonly platform?: NodeJS.Platform; - } = {}, + readonly platform: NodeJS.Platform; + }, ): Promise => { - const { - signal, - environment = process.env, - platform = process.platform, - } = options; + const { signal, environment = process.env, platform } = options; const hostEnvironment = snapshotEnvironment(environment, platform); let invocation: ApktoolInvocation; try { diff --git a/src/apktool/ApktoolProvider.test.ts b/src/apktool/ApktoolProvider.test.ts index 273ed72318..7530f53736 100644 --- a/src/apktool/ApktoolProvider.test.ts +++ b/src/apktool/ApktoolProvider.test.ts @@ -1780,3 +1780,23 @@ it("reports the owned-process prerequisite as Apktool unavailability, not a prob reason: expect.stringContaining("spawn ps ENOENT") as unknown, }); }); + +it("matches the launcher variable by the selected host's environment rules", async () => { + const stub = await writeApktoolStub(() => VERSION_BLOCK); + // Windows environment names are case-insensitive; POSIX names are exact. + const environment = { rea_apktool_command: stub.command, PATH: "" }; + const windows = new ApktoolProvider({ environment, platform: "win32" }); + onTestFinished(() => windows.close()); + expect(await windows.inspectAvailability()).toMatchObject({ + status: "available", + diagnostics: { + selected_command: stub.command, + command_source: "environment", + }, + }); + const posix = new ApktoolProvider({ environment, platform: "linux" }); + onTestFinished(() => posix.close()); + expect(await posix.inspectAvailability()).not.toMatchObject({ + diagnostics: { selected_command: stub.command }, + }); +}); diff --git a/src/apktool/ApktoolProvider.ts b/src/apktool/ApktoolProvider.ts index fca410a3c1..3a05b8f001 100644 --- a/src/apktool/ApktoolProvider.ts +++ b/src/apktool/ApktoolProvider.ts @@ -139,11 +139,17 @@ const runApktool = async ( environment: Readonly>, commands: ApktoolCommandCleanup, root: string, + platform: NodeJS.Platform, ): Promise> => { if (signal?.aborted === true) return err(cancelledBy(operation, signal)); let invocation: ReturnType; try { - invocation = apktoolInvocation(selection, arguments_, environment); + invocation = apktoolInvocation( + selection, + arguments_, + environment, + platform, + ); } catch (cause) { if (!(cause instanceof WindowsBatchCommandError)) throw cause; const reason = `The apktool batch launcher cannot receive REA's decode paths through cmd.exe: ${cause.message}`; @@ -273,6 +279,8 @@ const apktoolCommandFailure = ( export interface ApktoolProviderOptions { readonly environment?: Readonly>; readonly removeWorkspace?: (path: string) => Promise; + /** The host apktool runs on; defaults to the running host. */ + readonly platform?: NodeJS.Platform; } type DecodeFacts = Pick & @@ -290,6 +298,7 @@ type DecodeFacts = Pick & * (`--no-src`) because Java-source recovery belongs to the JADX family. */ export class ApktoolProvider { + private readonly platform: NodeJS.Platform; private readonly selectedEnvironment: | Readonly> | undefined; @@ -305,17 +314,18 @@ export class ApktoolProvider { #closePromise: Promise | undefined; constructor(options: ApktoolProviderOptions = {}) { + this.platform = options.platform ?? HOST_PLATFORM.platform; this.selectedEnvironment = options.environment === undefined ? undefined - : snapshotEnvironment(options.environment, HOST_PLATFORM.platform); + : snapshotEnvironment(options.environment, this.platform); this.removeWorkspace = options.removeWorkspace; } private operationEnvironment(): Readonly { return ( this.selectedEnvironment ?? - snapshotEnvironment(process.env, HOST_PLATFORM.platform) + snapshotEnvironment(process.env, this.platform) ); } @@ -355,12 +365,13 @@ export class ApktoolProvider { try { const selection = await resolveApktoolCommand( environment, - process.platform, + this.platform, signal, ); await inspectApktoolClient(selection, this.#commands, { signal, environment, + platform: this.platform, }); throwIfCancelled("inspect_apktool_client", signal); return { @@ -435,12 +446,13 @@ export class ApktoolProvider { try { selection = await resolveApktoolCommand( environment, - process.platform, + this.platform, signal, ); identity = await inspectApktoolClient(selection, this.#commands, { signal, environment, + platform: this.platform, }); } catch (cause) { if (cause instanceof AnalysisError) @@ -594,6 +606,7 @@ export class ApktoolProvider { environment, this.#commands, root, + this.platform, ); if (!decoded.ok) { throw decoded.error; diff --git a/src/apktool/ApktoolVersionProbe.lifecycle.test.ts b/src/apktool/ApktoolVersionProbe.lifecycle.test.ts index 7bea2db37b..459773ea98 100644 --- a/src/apktool/ApktoolVersionProbe.lifecycle.test.ts +++ b/src/apktool/ApktoolVersionProbe.lifecycle.test.ts @@ -1,3 +1,4 @@ +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { ApktoolCommandCleanup } from "./ApktoolCommandCleanup.js"; import { afterEach, expect, it } from "vitest"; @@ -22,7 +23,11 @@ it.skipIf(process.platform === "win32")( const probe = inspectApktoolClient( { command: fixture.command, commandSource: "environment" }, commands, - { signal: controller.signal, environment: process.env }, + { + signal: controller.signal, + environment: process.env, + platform: HOST_PLATFORM.platform, + }, ).catch((cause: unknown) => cause); try { let launched: readonly number[] = []; diff --git a/src/application/McpClientRegistration.formats.test.ts b/src/application/McpClientRegistration.formats.test.ts index a1d78b543c..87c9bf50fc 100644 --- a/src/application/McpClientRegistration.formats.test.ts +++ b/src/application/McpClientRegistration.formats.test.ts @@ -1,3 +1,4 @@ +import { registerMcpClientOnHost } from "../../tests/fixtures/mcpRegistration.js"; import { chmod, readFile, stat, symlink, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { basename, dirname, join } from "node:path"; @@ -95,7 +96,7 @@ it.each([ "publishes native $format launcher facts without retaining obsolete remote selection", async ({ format, id, text, expected }) => { const { path } = await settingsFixture(text); - const result = await registerMcpClient( + const result = await registerMcpClientOnHost( clientFor(path, format, id), launcher, undefined, @@ -130,7 +131,7 @@ it("secures fx permissions on owned directory and staged file, including a seman ...clientFor(path, "fx", "fx"), privateProfile: { home: tmpdir() }, } as const; - const result = await registerMcpClient( + const result = await registerMcpClientOnHost( client, launcher, undefined, @@ -151,7 +152,7 @@ it("secures fx permissions on owned directory and staged file, including a seman expect((await stat(path)).mode & 0o777).toBe(0o600); const before = await stat(path); expect( - await registerMcpClient(client, launcher, undefined, resources), + await registerMcpClientOnHost(client, launcher, undefined, resources), ).toMatchObject({ ok: true, value: { status: "unchanged" }, @@ -185,7 +186,7 @@ it.each([ "retains OpenCode activation policy from $name", async ({ text, native, ...control }) => { const { path } = await settingsFixture(text); - const result = await registerMcpClient( + const result = await registerMcpClientOnHost( clientFor(path, "opencode", "opencode"), launcher, undefined, @@ -229,7 +230,7 @@ it.each([ `extensions:\n rea: ${entry}\nfeature: on\n`, ); expect( - await registerMcpClient( + await registerMcpClientOnHost( clientFor(path, "goose", "goose"), launcher, undefined, @@ -262,7 +263,7 @@ it.runIf(process.platform === "win32")( ...clientFor(path, "fx", "fx"), privateProfile: { home: tmpdir() }, } as const; - const result = await registerMcpClient( + const result = await registerMcpClientOnHost( client, launcher, undefined, @@ -286,7 +287,7 @@ it.runIf(process.platform === "win32")( ]); const before = await stat(path); expect( - await registerMcpClient(client, launcher, undefined, resources), + await registerMcpClientOnHost(client, launcher, undefined, resources), ).toMatchObject({ ok: true, value: { status: "unchanged" } }); expect(await readFile(path, "utf8")).toBe(published); expect((await stat(path)).ino).toBe(before.ino); @@ -312,7 +313,7 @@ it.each([ ...clientFor(path, format, "github-copilot-cli"), scope, } as const; - const first = await registerMcpClient( + const first = await registerMcpClientOnHost( client, launcher, undefined, @@ -325,7 +326,7 @@ it.each([ expect(await readFile(`${path}.rea.backup`, "utf8")).toBe(original); const beforeRepeat = await stat(path); expect( - await registerMcpClient(client, launcher, undefined, resources), + await registerMcpClientOnHost(client, launcher, undefined, resources), ).toMatchObject({ ok: true, value: { status: "unchanged" } }); expect((await stat(path)).ino).toBe(beforeRepeat.ino); }, @@ -339,7 +340,7 @@ it.skipIf(process.platform === "win32")( const links = await createTestTempDirectory("rea-private-profile-link-"); await symlink(dirname(directory), join(links, "parent")); const linked = join(links, "parent", basename(directory), basename(path)); - const result = await registerMcpClient( + const result = await registerMcpClientOnHost( { ...clientFor(linked, "fx", "fx"), privateProfile: { home: directory } }, launcher, undefined, @@ -361,7 +362,7 @@ it("retains the private directory close owner during a semantic no-op", async () privateProfile: { home: tmpdir() }, } as const; expect( - await registerMcpClient(client, launcher, undefined, resources), + await registerMcpClientOnHost(client, launcher, undefined, resources), ).toMatchObject({ ok: true }); const originalClose = OwnedFileHandle.prototype.close; const close = vi @@ -372,7 +373,7 @@ it("retains the private directory close owner during a semantic no-op", async () return originalClose.call(this); }); try { - const result = await registerMcpClient( + const result = await registerMcpClientOnHost( client, launcher, undefined, @@ -409,7 +410,7 @@ it.each(["mcp", "mcpServers"])( theme: "dark", }; const { path } = await settingsFixture(JSON.stringify(original)); - const result = await registerMcpClient( + const result = await registerMcpClientOnHost( clientFor(path, "fx", "fx"), launcher, undefined, @@ -435,7 +436,7 @@ it.each(["mcp", "mcpServers"])( ]); const before = await stat(path); expect( - await registerMcpClient( + await registerMcpClientOnHost( clientFor(path, "fx", "fx"), launcher, undefined, @@ -449,7 +450,7 @@ it.each(["mcp", "mcpServers"])( it("creates Fx registrations in the native writer's mcpServers profile table", async () => { const { path } = await settingsFixture("{}"); expect( - await registerMcpClient( + await registerMcpClientOnHost( clientFor(path, "fx", "fx"), launcher, undefined, @@ -478,7 +479,7 @@ it.each([ async (document) => { const original = JSON.stringify(document); const { path } = await settingsFixture(original); - const result = await registerMcpClient( + const result = await registerMcpClientOnHost( clientFor(path, "fx", "fx"), launcher, undefined, @@ -509,7 +510,7 @@ it.each(["mcp", "mcpServers"])( const { path } = await settingsFixture(original); const client = clientFor(path, "fx", "fx"); expect( - await registerMcpClient(client, launcher, undefined, resources), + await registerMcpClientOnHost(client, launcher, undefined, resources), ).toMatchObject({ ok: true, value: { status: "configured" } }); expect(JSON.parse(await readFile(path, "utf8"))).toEqual({ [key]: { rea: entry, peer: { command: "peer" } }, @@ -518,7 +519,7 @@ it.each(["mcp", "mcpServers"])( expect(await readFile(`${path}.rea.backup`, "utf8")).toBe(original); const beforeRepeat = await stat(path); expect( - await registerMcpClient(client, launcher, undefined, resources), + await registerMcpClientOnHost(client, launcher, undefined, resources), ).toMatchObject({ ok: true, value: { status: "unchanged" } }); expect((await stat(path)).ino).toBe(beforeRepeat.ino); }, diff --git a/src/application/McpClientRegistration.layers.test.ts b/src/application/McpClientRegistration.layers.test.ts index dce01dd53e..d35f25973d 100644 --- a/src/application/McpClientRegistration.layers.test.ts +++ b/src/application/McpClientRegistration.layers.test.ts @@ -1,3 +1,4 @@ +import { registerMcpClientOnHost } from "../../tests/fixtures/mcpRegistration.js"; import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { lstat, mkdir, readFile, writeFile } from "node:fs/promises"; import { dirname, join } from "node:path"; @@ -10,7 +11,6 @@ import { parseClientConfiguration, } from "./ClientConfigurationDocument.js"; import { mergeClientConfigurationDocuments } from "./ClientConfigurationFiles.js"; -import { registerMcpClient } from "./McpClientRegistration.js"; import { mcpClientRegistrationProfile, type McpRegistrationClient, @@ -81,7 +81,7 @@ it("retains lower Kilo disable/environment policy without copying its source int const originalTarget = await write(target, targetDocument); const client = clientFor(target, [missing, lower, target]); expect( - await registerMcpClient(client, launcher, undefined, resources), + await registerMcpClientOnHost(client, launcher, undefined, resources), ).toMatchObject({ ok: true }); const targetText = await readFile(target, "utf8"); expect(JSON.parse(targetText)).toEqual({ @@ -115,7 +115,7 @@ it("refuses a higher Kilo file launcher before creating the lower selected targe rea: { type: "local", command: ["higher-server", "higher-argument"] }, }, }); - const result = await registerMcpClient( + const result = await registerMcpClientOnHost( clientFor(target, [join(root, "absent", "config.json"), target, higher]), launcher, undefined, @@ -148,7 +148,7 @@ it("refuses a conflicting KILO_CONFIG_CONTENT launcher without mutating the inli ), } as const; const beforeInline = structuredClone(inline); - const result = await registerMcpClient( + const result = await registerMcpClientOnHost( { ...clientFor(target, [target]), inlineConfiguration: inline }, launcher, undefined, @@ -207,7 +207,7 @@ it("retains harmless higher file and inline metadata as read-only inherited fact inlineConfiguration: inline, }; expect( - await registerMcpClient(client, launcher, undefined, resources), + await registerMcpClientOnHost(client, launcher, undefined, resources), ).toMatchObject({ ok: true }); const targetText = await readFile(target, "utf8"); expect(JSON.parse(targetText)).toEqual({ @@ -248,7 +248,7 @@ it("uses the effective OpenCode V2 dialect in its target fragment while preservi const peer = { type: "local", command: ["peer"] }; await write(target, { mcp: { peer } }); expect( - await registerMcpClient( + await registerMcpClientOnHost( clientFor(target, [lower, target], "opencode"), launcher, undefined, @@ -294,7 +294,7 @@ it("publishes through the last repeated target layer without copying intervening }, }, }); - const result = await registerMcpClient( + const result = await registerMcpClientOnHost( clientFor(target, [target, middle, target]), launcher, undefined, diff --git a/src/application/McpClientRegistration.nativeFields.test.ts b/src/application/McpClientRegistration.nativeFields.test.ts index 0801c0a0d8..a0056d0be7 100644 --- a/src/application/McpClientRegistration.nativeFields.test.ts +++ b/src/application/McpClientRegistration.nativeFields.test.ts @@ -1,3 +1,4 @@ +import { registerMcpClientOnHost } from "../../tests/fixtures/mcpRegistration.js"; import { readFile, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { beforeEach, afterEach, expect, it } from "vitest"; @@ -5,7 +6,6 @@ import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory import { ArtifactResourceScope } from "../resources/ArtifactResourceScope.js"; import { clientConfigurationRecordSchema } from "./ClientConfigurationDocument.js"; import { parseGooseConfigurationYaml } from "./GooseConfigurationYaml.js"; -import { registerMcpClient } from "./McpClientRegistration.js"; import { mcpClientRegistrationProfile, type McpRegistrationClient, @@ -62,7 +62,7 @@ it.each([ "preserves non-selector $format metadata through native document publication", async ({ format, id, text, key, metadata }) => { const { path } = await settingsFixture(text); - const result = await registerMcpClient( + const result = await registerMcpClientOnHost( clientFor(path, format, id), launcher, undefined, @@ -132,7 +132,7 @@ it.each([ const original = JSON.stringify({ mcpServers: { rea: previous } }) + "\n"; const { path } = await settingsFixture(original); expect( - await registerMcpClient( + await registerMcpClientOnHost( clientFor(path, "json", id), launcher, undefined, @@ -197,7 +197,7 @@ it.each([ }) + "\n"; const { path } = await settingsFixture(original); expect( - await registerMcpClient( + await registerMcpClientOnHost( clientFor(path, "json", id), launcher, undefined, diff --git a/src/application/McpClientRegistration.test.ts b/src/application/McpClientRegistration.test.ts index e222944d83..82cc937f7a 100644 --- a/src/application/McpClientRegistration.test.ts +++ b/src/application/McpClientRegistration.test.ts @@ -1,3 +1,7 @@ +import { + registerMcpClientOnHost, + registerMcpClientsOnHost, +} from "../../tests/fixtures/mcpRegistration.js"; import { lstat, mkdir, @@ -21,11 +25,7 @@ beforeEach(() => { resources = new ArtifactResourceScope(); }); import { OwnedStagedOutput } from "../filesystem/OwnedStagedOutput.js"; -import { - mcpClientRegistrationWritten, - registerMcpClient, - registerMcpClients, -} from "./McpClientRegistration.js"; +import { mcpClientRegistrationWritten } from "./McpClientRegistration.js"; import { mcpClientRegistrationProfile, resolveMcpRegistrationClients, @@ -49,7 +49,7 @@ const register = ( path: string, launcher: { command: string; args: readonly string[] }, signal?: AbortSignal, -) => registerMcpClient(clientFor(path), launcher, signal, resources); +) => registerMcpClientOnHost(clientFor(path), launcher, signal, resources); import { ClientConfigurationPublication } from "./ClientConfigurationPublication.js"; import * as regularReads from "../process/RegularFileRead.js"; @@ -140,7 +140,7 @@ it("registers Cline CLI in the settings file selected by its environment", async if (client === undefined) throw new Error("Missing selected Cline CLI client"); expect( - await registerMcpClient(client, launcher, undefined, resources), + await registerMcpClientOnHost(client, launcher, undefined, resources), ).toEqual(ok({ status: unchanged ? "unchanged" : "configured" })); expect(JSON.parse(await readFile(expected, "utf8"))).toMatchObject({ mcpServers: { rea: launcher }, @@ -341,7 +341,7 @@ it("refuses global Junie registration when known configuration disables or obscu if (!selected.ok) throw selected.error; const [client] = selected.value; if (client === undefined) throw new Error("Junie was not selected"); - return registerMcpClient(client, launcher, undefined, resources); + return registerMcpClientOnHost(client, launcher, undefined, resources); }; await writeFile(config, JSON.stringify({ "mcp-default-locations": false })); expect(await register({})).toMatchObject({ @@ -593,7 +593,7 @@ describe("Registration cancellation with independent failures", () => { throw physical; }, ); - const outcomes = await registerMcpClients( + const outcomes = await registerMcpClientsOnHost( [clientFor(first.path), clientFor(second.path)], launcher, controller.signal, @@ -629,7 +629,7 @@ describe("Registration cancellation with independent failures", () => { } throw new Error("Unexpected staging owner"); }); - const outcomes = await registerMcpClients( + const outcomes = await registerMcpClientsOnHost( [clientFor(first.path), clientFor(second.path)], launcher, controller.signal, @@ -689,7 +689,7 @@ describe("Registration cancellation and sibling outcomes", () => { clientFor(bad.path), clientFor(good.path, "json", "cursor"), ]; - const outcomes = await registerMcpClients( + const outcomes = await registerMcpClientsOnHost( clients, launcher, undefined, @@ -704,7 +704,7 @@ describe("Registration cancellation and sibling outcomes", () => { ]); const controller = new AbortController(); controller.abort("before batch"); - const cancelled = await registerMcpClients( + const cancelled = await registerMcpClientsOnHost( clients, launcher, controller.signal, @@ -727,7 +727,7 @@ describe("Registration cancellation and sibling outcomes", () => { return publication; }, ); - const partial = await registerMcpClients( + const partial = await registerMcpClientsOnHost( [clients[1]!, clients[0]!], { command: "next", args: [] }, late.signal, @@ -834,7 +834,7 @@ describe("Client registration publication recovery", () => { }, ]; const outcomes = await resources.run(() => - registerMcpClients(clients, launcher, undefined, resources), + registerMcpClientsOnHost(clients, launcher, undefined, resources), ); expect(outcomes).toMatchObject([ { diff --git a/src/application/McpClientRegistration.ts b/src/application/McpClientRegistration.ts index 26583c630e..dcbee59365 100644 --- a/src/application/McpClientRegistration.ts +++ b/src/application/McpClientRegistration.ts @@ -86,6 +86,8 @@ export const registerMcpClients = async ( launcher: ClientRegistrationCommand, signal: AbortSignal | undefined, resources: ArtifactResourceScope, + /** The host the clients were resolved for; it decides document semantics. */ + platform: NodeJS.Platform, ): Promise => { const outcomes: McpClientRegistrationOutcome[] = []; let cancelled = false; @@ -99,7 +101,13 @@ export const registerMcpClients = async ( outcomes.push({ ...labels, status: "not_started" }); continue; } - const result = await registerMcpClient(client, launcher, signal, resources); + const result = await registerMcpClient( + client, + launcher, + signal, + resources, + platform, + ); outcomes.push({ ...labels, status: "completed", result }); cancelled = signal?.aborted === true || @@ -117,6 +125,7 @@ export const registerMcpClient = async ( launcher: ClientRegistrationCommand, signal: AbortSignal | undefined, resources: ArtifactResourceScope, + platform: NodeJS.Platform, ): Promise< Result > => { @@ -148,7 +157,12 @@ export const registerMcpClient = async ( ); return await withClientConfigurationTransaction(path, async () => { checkCancellation(); - const prepared = await prepareRegistration(path, client, launcher); + const prepared = await prepareRegistration( + path, + client, + launcher, + platform, + ); const { snapshot, original, contents } = prepared; checkCancellation(); const unchanged = await unchangedRegistration( diff --git a/src/application/McpRegistrationConfiguration.ts b/src/application/McpRegistrationConfiguration.ts index 284044347d..a2df07f6b6 100644 --- a/src/application/McpRegistrationConfiguration.ts +++ b/src/application/McpRegistrationConfiguration.ts @@ -1,7 +1,6 @@ import { ConfigurationError } from "../domain/configurationErrors.js"; import type { ClientRegistrationCommand } from "../domain/clientRegistrationCommand.js"; import { PRODUCT_IDENTITY } from "../identity.js"; -import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { clientConfigurationValuesEqual, clientServerPath, @@ -24,16 +23,19 @@ import { admitClientStdioConnection } from "./ClientRegistrationConnection.js"; import type { McpRegistrationClient } from "./McpRegistrationCatalog.js"; import { readRegularFileTextSnapshot } from "../process/RegularFileRead.js"; -// `rea mcp add` writes and verifies this host's client files. -const { platform } = HOST_PLATFORM; - const isMissing = (cause: unknown): boolean => cause instanceof Error && "code" in cause && cause.code === "ENOENT"; +/** + * Merge REA's entry into one selected client document. `platform` is the host + * the catalog resolved the client for; it decides the document's environment + * name rules. + */ export const prepareRegistration = async ( path: string, client: McpRegistrationClient, launcher: ClientRegistrationCommand, + platform: NodeJS.Platform, ) => { const snapshot = await readRegularFileTextSnapshot(path, { symlinks: "reject", @@ -113,11 +115,12 @@ export const prepareRegistration = async ( const candidateLayers = layers.map((document, index) => paths[index] === client.configPath ? candidate : document, ); - assertEffectiveLauncher(client, candidateLayers, launcher); + assertEffectiveLauncher(client, candidateLayers, launcher, platform); return { path, client, launcher, + platform, snapshot, original, parsed, @@ -167,6 +170,7 @@ const assertEffectiveLauncher = ( client: McpRegistrationClient, layers: readonly ClientConfigurationDocument[], launcher: ClientRegistrationCommand, + platform: NodeJS.Platform, ): void => { const effective = mergeClientConfigurationDocuments(layers, platform); const admitted = admitClientStdioConnection( @@ -204,7 +208,7 @@ export const verifyEffectiveRegistration = async ( prepared: Awaited>, targetText: string, ): Promise => { - const { client, launcher } = prepared; + const { client, launcher, platform } = prepared; assertEffectiveLauncher( client, await readRegistrationLayers( @@ -212,5 +216,6 @@ export const verifyEffectiveRegistration = async ( parseClientConfiguration(targetText, client.format), ), launcher, + platform, ); }; diff --git a/src/application/desktop/DesktopApplicationCapture.ts b/src/application/desktop/DesktopApplicationCapture.ts index 069e797a67..3e45f3ef71 100644 --- a/src/application/desktop/DesktopApplicationCapture.ts +++ b/src/application/desktop/DesktopApplicationCapture.ts @@ -1,7 +1,8 @@ import { processInspectionCleanupFailures } from "../../process/ProcessInspectionCleanup.js"; import { samplingInspectionFailures } from "../../process/capture/ProcessSamplingObservation.js"; import type { DesktopLibraryPolicyInput } from "../../domain/desktop/libraryPolicy.js"; -import { arch, hostname, userInfo } from "node:os"; +import { hostname, userInfo } from "node:os"; +import { HOST_PLATFORM } from "../../platform/HostPlatform.js"; import { cancelledBy } from "../../domain/analysisErrorCore.js"; import { @@ -190,9 +191,9 @@ const captureEvidence = ( confidence: "observed", authority: "controlled-replay", environment: { - id: `linux-${arch()}`, + id: `linux-${HOST_PLATFORM.architecture}`, platform: "linux", - architecture: arch(), + architecture: HOST_PLATFORM.architecture, isolation: "none", }, limitations: capture.limitations, @@ -313,7 +314,7 @@ const recordCapture = async ( const capture: DesktopApplicationCapture = { host: { platform: "linux", - architecture: arch(), + architecture: HOST_PLATFORM.architecture, display: admitted.display, home, ...hostIdentity(), diff --git a/src/application/desktop/DesktopBuildComputers.ts b/src/application/desktop/DesktopBuildComputers.ts index 2cdbfd81e0..eb6ef7e3b6 100644 --- a/src/application/desktop/DesktopBuildComputers.ts +++ b/src/application/desktop/DesktopBuildComputers.ts @@ -422,7 +422,9 @@ export class DesktopBuildComputers { private readonly defaults: BuildComputerDefaults = {}, private readonly startTiming: ComputerStartTiming = COMPUTER_START_TIMING, ) { - this.#secrets = new DesktopBuildSecrets(buildSecretsDirectory(environment)); + this.#secrets = new DesktopBuildSecrets( + buildSecretsDirectory(environment, HOST_PLATFORM.platform), + ); this.#shared = { settle, secrets: this.#secrets }; } diff --git a/src/browser/ChromiumSandbox.ts b/src/browser/ChromiumSandbox.ts index e5949c11ec..e92e0469a7 100644 --- a/src/browser/ChromiumSandbox.ts +++ b/src/browser/ChromiumSandbox.ts @@ -10,7 +10,7 @@ export const CHROMIUM_NO_SANDBOX_VARIABLE = "REA_BROWSER_NO_SANDBOX"; */ export const chromiumSandboxEnabled = ( environment: Readonly>, - platform: NodeJS.Platform = process.platform, + platform: NodeJS.Platform, ): boolean => platform !== "android" && environment[CHROMIUM_NO_SANDBOX_VARIABLE] !== "true"; diff --git a/src/browser/ElectronCaptureCleanup.test.ts b/src/browser/ElectronCaptureCleanup.test.ts index 23f303b40d..f461f455a3 100644 --- a/src/browser/ElectronCaptureCleanup.test.ts +++ b/src/browser/ElectronCaptureCleanup.test.ts @@ -198,8 +198,6 @@ it("retains unknown process identity even after its exact transport closes", asy }); it("refreshes Windows lineage and never authorizes retry from a cached verified snapshot", async () => { - const platform = Object.getOwnPropertyDescriptor(process, "platform")!; - Object.defineProperty(process, "platform", { value: "win32" }); vi.spyOn( ownershipObservation, "observeOwnedProcessLineage", @@ -217,19 +215,16 @@ it("refreshes Windows lineage and never authorizes retry from a cached verified { close: async () => undefined }, ownership, verified, + "win32", ); const scope = new ArtifactResourceScope(); - try { - await owner.release(scope); - const error = bindFailure(owner); - expect(error.cleanupIncomplete).toBe(true); - absence.mockResolvedValue({ cleaned: true, signaled: false }); - await scope.close(); - expect(error.cleanupIncomplete).toBe(false); - expect(terminate).not.toHaveBeenCalled(); - } finally { - Object.defineProperty(process, "platform", platform); - } + await owner.release(scope); + const error = bindFailure(owner); + expect(error.cleanupIncomplete).toBe(true); + absence.mockResolvedValue({ cleaned: true, signaled: false }); + await scope.close(); + expect(error.cleanupIncomplete).toBe(false); + expect(terminate).not.toHaveBeenCalled(); }); it.skipIf(process.platform === "win32")( diff --git a/src/browser/ElectronCaptureCleanup.ts b/src/browser/ElectronCaptureCleanup.ts index 62190c45a6..1a79d72348 100644 --- a/src/browser/ElectronCaptureCleanup.ts +++ b/src/browser/ElectronCaptureCleanup.ts @@ -1,3 +1,4 @@ +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import type { _electron as electron } from "playwright-core"; import { AnalysisCleanupLease, @@ -13,7 +14,10 @@ import type { ProcessLineageObservation, } from "../process/ProcessOwnership.js"; import { runWithExecutionLimits } from "./PlaywrightElectronExecution.js"; -import { cleanupElectronProcesses } from "./ElectronProcessCleanup.js"; +import { + cleanupElectronProcesses, + systemElectronCleanupHost, +} from "./ElectronProcessCleanup.js"; type ElectronApplication = Awaited>; @@ -30,6 +34,8 @@ export class ElectronCaptureCleanup { application: Pick, ownership: PersistentOwnedProcessGroup | undefined, lineage: ProcessLineageObservation | undefined, + // The host whose process tree this cleanup releases. + private readonly platform: NodeJS.Platform = HOST_PLATFORM.platform, ) { this.#ownership = ownership; this.#lineage = lineage; @@ -113,7 +119,8 @@ export class ElectronCaptureCleanup { // current tokens/start identities. Windows requires this attempt's lineage. return cleanupElectronProcesses( ownership, - process.platform === "win32" ? current : (this.#lineage ?? current), + this.platform === "win32" ? current : (this.#lineage ?? current), + systemElectronCleanupHost(this.platform), ); } } diff --git a/src/browser/ElectronProcessCleanup.ts b/src/browser/ElectronProcessCleanup.ts index ac12a1857d..eed3c9b9d8 100644 --- a/src/browser/ElectronProcessCleanup.ts +++ b/src/browser/ElectronProcessCleanup.ts @@ -1,3 +1,4 @@ +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { cleanupOwnedProcessGroup, cleanupWindowsProcessTree, @@ -10,19 +11,27 @@ import { import { systemProcessOwnershipHost } from "../process/ProcessOwnershipObservation.js"; import { selectCapturedProcessGroupIds } from "../process/ProcessOwnershipProcessTree.js"; +/** The process operations an Electron cleanup uses on one host. */ +export interface ElectronCleanupHost { + readonly platform: NodeJS.Platform; + readonly terminateTree: typeof cleanupWindowsProcessTree; + readonly processOwnershipHost?: ProcessOwnershipHost; +} + +/** System process operations for the selected (by default the running) host. */ +export const systemElectronCleanupHost = ( + platform: NodeJS.Platform = HOST_PLATFORM.platform, +): ElectronCleanupHost => ({ + platform, + terminateTree: cleanupWindowsProcessTree, + processOwnershipHost: systemProcessOwnershipHost, +}); + /** Clean up an Electron launch. Windows signals a process only after lineage is verified. */ export const cleanupElectronProcesses = async ( ownership: PersistentOwnedProcessGroup, lineage: ProcessLineageObservation | undefined, - host: { - readonly platform: NodeJS.Platform; - readonly terminateTree: typeof cleanupWindowsProcessTree; - readonly processOwnershipHost?: ProcessOwnershipHost; - } = { - platform: process.platform, - terminateTree: cleanupWindowsProcessTree, - processOwnershipHost: systemProcessOwnershipHost, - }, + host: ElectronCleanupHost = systemElectronCleanupHost(), ): Promise => { if ( lineage?.status === "verified" && diff --git a/src/browser/PlaywrightElectronActiveFuses.ts b/src/browser/PlaywrightElectronActiveFuses.ts index adda1ce875..e8b0665e12 100644 --- a/src/browser/PlaywrightElectronActiveFuses.ts +++ b/src/browser/PlaywrightElectronActiveFuses.ts @@ -1,3 +1,4 @@ +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { assertArtifactReadActive, ArtifactReaderFailure, @@ -72,7 +73,9 @@ export const assertNodeCliInspectArgumentsSupported = async ( }); if (image.slices.length === 0) return; - const hostArchitecture = process.arch === "x64" ? "x86_64" : process.arch; + // The fuses that matter are the ones in the slice this host launches. + const { architecture } = HOST_PLATFORM; + const hostArchitecture = architecture === "x64" ? "x86_64" : architecture; const targetSlice = image.slices.find((slice) => slice.architecture === hostArchitecture) ?? image.slices[0]; diff --git a/src/browser/PlaywrightElectronActiveProvider.test.ts b/src/browser/PlaywrightElectronActiveProvider.test.ts index b9b2c84270..5f2c956d16 100644 --- a/src/browser/PlaywrightElectronActiveProvider.test.ts +++ b/src/browser/PlaywrightElectronActiveProvider.test.ts @@ -588,8 +588,6 @@ it("retains the partial capture without taskkill when Windows lineage is unavail cleaned: false, reason: "authored census unavailable", }); - const originalPlatform = Object.getOwnPropertyDescriptor(process, "platform"); - Object.defineProperty(process, "platform", { value: "win32" }); const terminateTree = vi .spyOn(processOwnership, "cleanupWindowsProcessTree") .mockResolvedValue({ cleaned: true, signaled: true }); @@ -614,40 +612,37 @@ it("retains the partial capture without taskkill when Windows lineage is unavail application as unknown as Awaited< ReturnType >, + undefined, + "win32", ); - try { - const result = await provider.capture({ - ...electronActiveObservationInputSchema.parse({ - executable_path: process.execPath, - application_path: process.execPath, - }), - application_root: dirname(process.execPath), - }); + const result = await provider.capture({ + ...electronActiveObservationInputSchema.parse({ + executable_path: process.execPath, + application_path: process.execPath, + }), + application_root: dirname(process.execPath), + }); - if (result.ok) throw new Error("Expected unverified cleanup to fail"); - expect(terminateTree).not.toHaveBeenCalled(); - expect(result.error).toMatchObject({ - _tag: "BrowserObservationError", - reason: "cleanup_failed", - cleanup: { - reason: expect.stringContaining( - "process table permission denied; helper cleanup was not proven", - ), - }, - partialObservation: { - kind: "electron-active-observation", - capture: { - application: { - cleanup: "unverified", - }, + if (result.ok) throw new Error("Expected unverified cleanup to fail"); + expect(terminateTree).not.toHaveBeenCalled(); + expect(result.error).toMatchObject({ + _tag: "BrowserObservationError", + reason: "cleanup_failed", + cleanup: { + reason: expect.stringContaining( + "process table permission denied; helper cleanup was not proven", + ), + }, + partialObservation: { + kind: "electron-active-observation", + capture: { + application: { + cleanup: "unverified", }, }, - }); - } finally { - if (originalPlatform !== undefined) - Object.defineProperty(process, "platform", originalPlatform); - } + }, + }); }); it("retains the initial snapshot when the final state read fails", async () => { diff --git a/src/browser/PlaywrightElectronActiveProvider.ts b/src/browser/PlaywrightElectronActiveProvider.ts index 6e6ab47e8a..4b13ab9d91 100644 --- a/src/browser/PlaywrightElectronActiveProvider.ts +++ b/src/browser/PlaywrightElectronActiveProvider.ts @@ -1,3 +1,4 @@ +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { retainProcessInspectionCleanup, processInspectionCancellationError, @@ -96,6 +97,8 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservati private readonly launch: typeof electron.launch = async (options) => (await import("playwright-core"))._electron.launch(options), private readonly readFuseImage: typeof readElectronFuseImage = readElectronFuseImage, + // The host the application launches and is cleaned up on. + private readonly platform: NodeJS.Platform = HOST_PLATFORM.platform, ) {} identity(): ProviderIdentity { @@ -193,7 +196,7 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservati executablePath: paths.executable, cwd: paths.root, env: { - ...safeElectronEnvironment(this.environment, runId), + ...safeElectronEnvironment(this.environment, runId, this.platform), REA_ELECTRON_CAPTURE_ARGV: JSON.stringify({ length: applicationArgs.length, sha256: createHash("sha256") @@ -294,7 +297,12 @@ export class PlaywrightElectronActiveProvider implements ElectronActiveObservati outcome = err(error); } if (application !== undefined) { - const owner = new ElectronCaptureCleanup(application, ownership, lineage); + const owner = new ElectronCaptureCleanup( + application, + ownership, + lineage, + this.platform, + ); const released = await owner.release(this.#resources); const cleanup = owner.processResult; outcome = captureOutcomeWithCancellation(outcome, options.signal); @@ -439,7 +447,7 @@ const cancelledCapture = ( export const safeElectronEnvironment = ( environment: Readonly>, runId: string, - platform = process.platform, + platform: NodeJS.Platform, ): Record => Object.fromEntries([ ...[ diff --git a/src/browser/PlaywrightScenarioBrowser.test.ts b/src/browser/PlaywrightScenarioBrowser.test.ts index a583519bfb..9c373a4a12 100644 --- a/src/browser/PlaywrightScenarioBrowser.test.ts +++ b/src/browser/PlaywrightScenarioBrowser.test.ts @@ -25,11 +25,8 @@ import { PlaywrightScenarioBrowserCleanupOwner, } from "./PlaywrightScenarioBrowser.js"; -const hostPlatform = process.platform; - afterEach(() => { vi.unstubAllEnvs(); - Object.defineProperty(process, "platform", { value: hostPlatform }); }); it("locks one attached browser for spellings that discover the same endpoint", () => { @@ -143,7 +140,6 @@ it.skipIf(process.platform === "win32")( ); it("keeps Termux execution support when launching Chromium on Android", async () => { - Object.defineProperty(process, "platform", { value: "android" }); vi.stubEnv("PREFIX", "/data/data/com.termux/files/usr"); const selected = { LANG: "selected-language", PREFIX: process.env.PREFIX }; let launchOptions: Parameters< @@ -159,6 +155,7 @@ it("keeps Termux execution support when launching Chromium on Android", async () await expect( openPlaywrightScenarioBrowser(scenario, selected, { + platform: "android", launcher: { connectOverCDP: async () => { throw new Error("Unexpected connection"); @@ -290,13 +287,13 @@ it.each([ ])( "launches Chromium with sandbox $sandbox for $environment", async ({ environment, sandbox }) => { - Object.defineProperty(process, "platform", { value: "linux" }); let launchOptions: Parameters< typeof import("playwright-core").chromium.launchPersistentContext >[1]; await expect( openPlaywrightScenarioBrowser(launchScenario, environment, { + platform: "linux", launcher: { connectOverCDP: async () => { throw new Error("Unexpected connection"); diff --git a/src/browser/PlaywrightScenarioBrowser.ts b/src/browser/PlaywrightScenarioBrowser.ts index 6fee76dd30..e58d6e2f9a 100644 --- a/src/browser/PlaywrightScenarioBrowser.ts +++ b/src/browser/PlaywrightScenarioBrowser.ts @@ -1,3 +1,4 @@ +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { PLAYWRIGHT_BROWSER_SCENARIO_PROVIDER_IDENTITY } from "./providerIdentities.js"; import { chromiumLaunchRemediation, @@ -348,6 +349,7 @@ const acquireAttachedScenario = ( const allowedBrowserEnvironment = ( environment: Readonly>, + platform: NodeJS.Platform, ): Record => { const allowed = [ "DBUS_SESSION_BUS_ADDRESS", @@ -371,7 +373,7 @@ const allowedBrowserEnvironment = ( (entry): entry is readonly [string, string] => entry[1] !== undefined, ), ); - if (process.platform !== "android") return selected; + if (platform !== "android") return selected; // Android rejects execve() for binaries below Termux's application data // directory. Termux supplies an exec interceptor that rewrites those calls @@ -875,9 +877,12 @@ export const openPlaywrightScenarioBrowser = async ( readonly launcher?: ScenarioBrowserLauncher; readonly signal?: AbortSignal | undefined; readonly retainCleanup?: (lease: AnalysisCleanupLease) => void; + /** The host Chromium launches on; defaults to the running host. */ + readonly platform?: NodeJS.Platform; } = {}, ): Promise => { throwIfScenarioCancelled(options.signal); + const platform = options.platform ?? HOST_PLATFORM.platform; // Load Playwright only when a scenario opens; MCP startup stays off its module graph. const launcher = options.launcher ?? (await import("playwright-core")).chromium; @@ -897,7 +902,7 @@ export const openPlaywrightScenarioBrowser = async ( let context: BrowserContext; const executablePath = scenario.browser.executable_path; const headless = scenario.browser.headless; - const chromiumSandbox = chromiumSandboxEnabled(environment); + const chromiumSandbox = chromiumSandboxEnabled(environment, platform); let launchStarted = false; try { await chmod(profilePath, 0o700); @@ -919,7 +924,7 @@ export const openPlaywrightScenarioBrowser = async ( colorScheme: scenario.environment.color_scheme, reducedMotion: scenario.environment.reduced_motion, serviceWorkers: scenario.environment.service_workers, - env: allowedBrowserEnvironment(environment), + env: allowedBrowserEnvironment(environment, platform), handleSIGHUP: false, handleSIGINT: false, handleSIGTERM: false, @@ -928,7 +933,7 @@ export const openPlaywrightScenarioBrowser = async ( // Termux's Chromium cannot create its renderer process through Android's // executable boundary. Single-process mode keeps the browser and page in // the Termux-launched process so scenario navigation remains available. - args: process.platform === "android" ? ["--single-process"] : [], + args: platform === "android" ? ["--single-process"] : [], }), commandTimeoutMs, "launch", diff --git a/src/browser/assets/LocalWebScriptArtifacts.ts b/src/browser/assets/LocalWebScriptArtifacts.ts index 8182651ace..d2049ed0f7 100644 --- a/src/browser/assets/LocalWebScriptArtifacts.ts +++ b/src/browser/assets/LocalWebScriptArtifacts.ts @@ -1,3 +1,4 @@ +import { HOST_PLATFORM } from "../../platform/HostPlatform.js"; import { lstat, realpath } from "node:fs/promises"; import { dirname, join } from "node:path"; import { @@ -27,6 +28,8 @@ export class LocalWebScriptArtifacts implements WebScriptArtifactPort { constructor( readonly operation: WebArtifactReadContext["operation"], readonly resources = new ArtifactResourceScope(), + // The host whose filesystem holds the selected manifest. + readonly platform: NodeJS.Platform = HOST_PLATFORM.platform, ) {} close(): Promise { @@ -121,7 +124,7 @@ export class LocalWebScriptArtifacts implements WebScriptArtifactPort { "path", `Selected source path changes during normalization: ${selected.content.relative_path}`, ); - if (process.platform === "win32" && portable.includes("\\")) + if (this.platform === "win32" && portable.includes("\\")) throw new ArtifactReaderFailure( "path", `Windows source path cannot contain backslashes as literal name characters: ${JSON.stringify(portable)}`, diff --git a/src/browser/history/MitmproxyCaptureAdapter.ts b/src/browser/history/MitmproxyCaptureAdapter.ts index 7d0340f4d7..08a5852652 100644 --- a/src/browser/history/MitmproxyCaptureAdapter.ts +++ b/src/browser/history/MitmproxyCaptureAdapter.ts @@ -15,10 +15,15 @@ const MITMDUMP_REQUIREMENT = export class MitmproxyCaptureAdapter implements HistoricalCaptureFormatAdapter { readonly format = "mitmproxy"; readonly identity = MITMPROXY_CAPTURE_PROVIDER_IDENTITY; - constructor(readonly environment: Readonly) {} + constructor( + readonly environment: Readonly, + // The host mitmdump runs on; defaults to the running host. + readonly platform: NodeJS.Platform = HOST_PLATFORM.platform, + ) {} snapshotConfiguration(): HistoricalCaptureFormatAdapter { return new MitmproxyCaptureAdapter( - snapshotEnvironment(this.environment, HOST_PLATFORM.platform), + snapshotEnvironment(this.environment, this.platform), + this.platform, ); } async command( @@ -27,7 +32,7 @@ export class MitmproxyCaptureAdapter implements HistoricalCaptureFormatAdapter { ): Promise<{ command: string; arguments: readonly string[] }> { const command = this.environment.REA_MITMDUMP_COMMAND; if ( - process.platform !== "linux" || + this.platform !== "linux" || command === undefined || !isAbsolute(command) ) diff --git a/src/browser/modules/NativeModuleResolver.test.ts b/src/browser/modules/NativeModuleResolver.test.ts index b7aaa1aa2b..e479cf6b2d 100644 --- a/src/browser/modules/NativeModuleResolver.test.ts +++ b/src/browser/modules/NativeModuleResolver.test.ts @@ -240,11 +240,6 @@ describe("optional native resolution acquisition", () => { }); describe("native resolution Chromium sandbox", () => { - const hostPlatform = process.platform; - afterEach(() => { - Object.defineProperty(process, "platform", { value: hostPlatform }); - }); - it.each([ { environment: {}, sandbox: true }, { environment: { REA_BROWSER_NO_SANDBOX: "false" }, sandbox: true }, @@ -252,7 +247,6 @@ describe("native resolution Chromium sandbox", () => { ])( "launches Chromium with sandbox $sandbox for $environment", async ({ environment, sandbox }) => { - Object.defineProperty(process, "platform", { value: "linux" }); let launchOptions: Parameters[0] | undefined; const provider = new NativeModuleResolver( { REA_BROWSER_EXECUTABLE: "/browser", ...environment }, @@ -260,6 +254,7 @@ describe("native resolution Chromium sandbox", () => { launchOptions = options; return Promise.reject(new Error("launch boundary reached")); }, + "linux", ); const result = await provider.resolve(input); if (result.ok) throw new Error("expected startup failure"); @@ -274,7 +269,6 @@ describe("native resolution Chromium sandbox", () => { ); it("keeps the default recovery for engine failures after a sandboxed launch", async () => { - Object.defineProperty(process, "platform", { value: "linux" }); const provider = new NativeModuleResolver( { REA_BROWSER_EXECUTABLE: "/browser" }, () => @@ -284,6 +278,7 @@ describe("native resolution Chromium sandbox", () => { Promise.reject(new Error("fixture context failure")), close: () => Promise.resolve(), }), + "linux", ); const result = await provider.resolve(input); if (result.ok) throw new Error("expected engine failure"); diff --git a/src/browser/modules/NativeModuleResolver.ts b/src/browser/modules/NativeModuleResolver.ts index f507a1faf9..b76a37b9ee 100644 --- a/src/browser/modules/NativeModuleResolver.ts +++ b/src/browser/modules/NativeModuleResolver.ts @@ -105,8 +105,10 @@ export class NativeModuleResolver implements WebModuleResolutionPort { constructor( environment: Readonly>, readonly launcher: ModuleResolverLauncher = launch, + // The host Chromium launches on; defaults to the running host. + private readonly platform: NodeJS.Platform = HOST_PLATFORM.platform, ) { - this.environment = snapshotEnvironment(environment, HOST_PLATFORM.platform); + this.environment = snapshotEnvironment(environment, platform); } resolve( @@ -150,7 +152,10 @@ export class NativeModuleResolver implements WebModuleResolutionPort { }, ), ); - const chromiumSandbox = chromiumSandboxEnabled(this.environment); + const chromiumSandbox = chromiumSandboxEnabled( + this.environment, + this.platform, + ); const deadline = new ProviderStartupDeadline(TIMEOUT_MS, options?.signal); let activeCall: | { settled: boolean; interruption?: AnalysisError } diff --git a/src/captures/TsharkCaptureProvider.ts b/src/captures/TsharkCaptureProvider.ts index 48550613b1..f46135acb2 100644 --- a/src/captures/TsharkCaptureProvider.ts +++ b/src/captures/TsharkCaptureProvider.ts @@ -1,3 +1,4 @@ +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { capturedProviderOutput } from "../process/capturedProviderOutput.js"; import { ArtifactReaderFailure, @@ -108,7 +109,7 @@ export class TsharkCaptureProvider implements PacketCapturePort { readonly launcher?: Launcher, readonly createRuntime: () => Promise = () => PrivateRuntimeRoot.create({ prefix: "rea-tshark-" }), - readonly platform: NodeJS.Platform = process.platform, + readonly platform: NodeJS.Platform = HOST_PLATFORM.platform, readonly readArtifact: typeof readStableArtifact = readStableArtifact, readonly readLimits: typeof readLinuxResourceLimits = readLinuxResourceLimits, ) { diff --git a/src/cli/desktopCaptureCommands.ts b/src/cli/desktopCaptureCommands.ts index bb7b442473..a73946cfbd 100644 --- a/src/cli/desktopCaptureCommands.ts +++ b/src/cli/desktopCaptureCommands.ts @@ -1,3 +1,4 @@ +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { desktopLibraryPolicyInputSchema } from "../domain/desktop/libraryPolicy.js"; import { desktopViewPolicyInputSchema } from "../domain/desktop/desktopViewPolicy.js"; import { safeParseJson } from "../domain/safeJson.js"; @@ -553,7 +554,7 @@ export const registerDesktopCaptureCommands = ( : absoluteCallerPath(options.packageFile), }, { - platform: process.platform, + platform: HOST_PLATFORM.platform, environment, callerDirectory: process.cwd(), nextRequest: () => requests.next(), diff --git a/src/cli/mcpRegistration.ts b/src/cli/mcpRegistration.ts index 08c0305bc3..6d7b4af90b 100644 --- a/src/cli/mcpRegistration.ts +++ b/src/cli/mcpRegistration.ts @@ -1,3 +1,4 @@ +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { Writable } from "node:stream"; import { Help, z } from "incur"; @@ -309,13 +310,14 @@ const executeRegistration = async ( const resources = (retainedResources ??= new ArtifactResourceScope()); const outcomes = await resources .run(async () => { + const { platform } = HOST_PLATFORM; const targets = await resolveMcpRegistrationClients( { agents: request.agents, global: request.global, cwd: process.cwd(), - home: homeDirectoryFromEnvironment(environment, process.platform), - platform: process.platform, + home: homeDirectoryFromEnvironment(environment, platform), + platform, environment, signal, }, @@ -336,6 +338,7 @@ const executeRegistration = async ( request.launcher, signal, resources, + platform, ), }; }) diff --git a/src/composition/adb.ts b/src/composition/adb.ts index b88d8b9710..16f98f2b9e 100644 --- a/src/composition/adb.ts +++ b/src/composition/adb.ts @@ -1,7 +1,9 @@ import type { AdbDeviceAnalysisPort } from "../application/adb/AdbDeviceAnalysisPort.js"; import { AdbProvider } from "../adb/AdbProvider.js"; +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; /** Construct one ADB provider bound to the caller-selected binary. */ export const createAdbDeviceAnalysisProvider = ( environment: Readonly> = process.env, -): AdbDeviceAnalysisPort => new AdbProvider({ environment }); + platform: NodeJS.Platform = HOST_PLATFORM.platform, +): AdbDeviceAnalysisPort => new AdbProvider({ environment, platform }); diff --git a/src/composition/apktool.ts b/src/composition/apktool.ts index 16652cae63..7470d50af9 100644 --- a/src/composition/apktool.ts +++ b/src/composition/apktool.ts @@ -1,7 +1,10 @@ import type { ApktoolResourceAnalysisPort } from "../application/apktool/ApktoolResourceAnalysisPort.js"; import { ApktoolProvider } from "../apktool/ApktoolProvider.js"; +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; /** Construct one Apktool provider bound to the caller-selected launcher. */ export const createApktoolResourceAnalysisProvider = ( environment: Readonly> = process.env, -): ApktoolResourceAnalysisPort => new ApktoolProvider({ environment }); + platform: NodeJS.Platform = HOST_PLATFORM.platform, +): ApktoolResourceAnalysisPort => + new ApktoolProvider({ environment, platform }); diff --git a/src/composition/auxiliaryAnalysisProviders.ts b/src/composition/auxiliaryAnalysisProviders.ts index ed58abcac2..7c91aa74e5 100644 --- a/src/composition/auxiliaryAnalysisProviders.ts +++ b/src/composition/auxiliaryAnalysisProviders.ts @@ -1,3 +1,4 @@ +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import type { AnalysisSettingsReader } from "../domain/analysisSettings.js"; import { snapshotEnvironment } from "../process/snapshotEnvironment.js"; import type { LazyAnalysisProvider } from "../application/binary/LazyAnalysisProvider.js"; @@ -17,7 +18,7 @@ type AuxiliaryProviderDeclaration = ConstructorParameters< /** Wire the three existing auxiliary AnalysisProvider implementations lazily. */ export const auxiliaryAnalysisProviderDeclarations = ( selectedEnvironment: Readonly, - platform: NodeJS.Platform = process.platform, + platform: NodeJS.Platform = HOST_PLATFORM.platform, settings?: AnalysisSettingsReader, ): readonly AuxiliaryProviderDeclaration[] => { const environment = snapshotEnvironment(selectedEnvironment, platform); diff --git a/src/composition/binary.ts b/src/composition/binary.ts index 335078531d..5017b74aed 100644 --- a/src/composition/binary.ts +++ b/src/composition/binary.ts @@ -73,9 +73,7 @@ const composeDeepBinarySession = ( ); const ghidra = new GhidraProvider(config, logger, environment); const ida = new IdaProvider(config, environment, (registration, selected) => - createIdaMcpConnection(registration, selected, { - platform: HOST_PLATFORM.platform, - }), + createIdaMcpConnection(registration, selected, { platform }), ); const kuna = new KunaProvider(environment, { regexMatchingDeadline: config.regexMatchingDeadline, @@ -155,7 +153,7 @@ export const createManagedBinarySession = (): BinarySession => /** Compose the artifact operations without candidates for deep analysis engines. */ export const createArtifactBinarySession = ( selectedEnvironment: Readonly, - platform: NodeJS.Platform = process.platform, + platform: NodeJS.Platform = HOST_PLATFORM.platform, ): Promise => import("../artifacts/ArtifactProvider.js").then(({ ArtifactProvider }) => composeBinarySession( @@ -176,7 +174,7 @@ export const createArtifactBinarySession = ( /** Compose native inspection utilities without candidates for deep analysis. */ export const createNativeBinarySession = ( selectedEnvironment: Readonly, - platform: NodeJS.Platform = process.platform, + platform: NodeJS.Platform = HOST_PLATFORM.platform, ): Promise => import("../native/NativeMacOSProvider.js").then(({ NativeMacOSProvider }) => composeBinarySession( diff --git a/src/composition/binaryDiagnostics.ts b/src/composition/binaryDiagnostics.ts index 43db3c08fa..8f3fdb18dd 100644 --- a/src/composition/binaryDiagnostics.ts +++ b/src/composition/binaryDiagnostics.ts @@ -1,3 +1,4 @@ +import { HOST_PLATFORM, type HostPlatform } from "../platform/HostPlatform.js"; import { PeLoadConfigService } from "../application/binaryDiagnostics/PeLoadConfigService.js"; import { PeLoadConfigProvider } from "../native/pe/PeLoadConfigProvider.js"; import { BinaryHardeningService } from "../application/binaryDiagnostics/BinaryHardeningService.js"; @@ -79,14 +80,20 @@ export const createKernelBuildConfigService = (): KernelBuildConfigService => /** Compose the offline adapter without import-time I/O or dependency acquisition. */ export const createBinaryLayoutService = ( environment: Readonly = process.env, + host: HostPlatform = HOST_PLATFORM, ): BinaryLayoutService => - new BinaryLayoutService(new PwntoolsLayoutProvider(environment)); + new BinaryLayoutService( + new PwntoolsLayoutProvider(environment, undefined, undefined, host), + ); /** Compose recorded-core inspection without acquiring a debugger or toolchain. */ export const createRecordedCrashService = ( environment: Readonly = process.env, + host: HostPlatform = HOST_PLATFORM, ): RecordedCrashService => - new RecordedCrashService(new PwntoolsRecordedCrashProvider(environment)); + new RecordedCrashService( + new PwntoolsRecordedCrashProvider(environment, undefined, undefined, host), + ); /** Provider-free local byte analysis. */ export const createByteEntropyService = ( diff --git a/src/composition/capabilityServices.ts b/src/composition/capabilityServices.ts index 50f901cf45..dbca631f94 100644 --- a/src/composition/capabilityServices.ts +++ b/src/composition/capabilityServices.ts @@ -187,7 +187,7 @@ export interface CapabilityHostContext { readonly settings: AnalysisSettingsReader; readonly options: CapabilityServiceOptions; readonly platform: NodeJS.Platform; - readonly arch: string; + readonly arch: NodeJS.Architecture; } interface CapabilityInstance { @@ -257,8 +257,9 @@ const modules = { apkSignatureModule.create(environment, options.apkSignature), ), evmInterface: service( - ({ environment, options }) => - options.evmInterface ?? evmInterfaceModule.create(environment), + ({ environment, options, platform, arch }) => + options.evmInterface ?? + evmInterfaceModule.create(environment, { platform, architecture: arch }), ({ environment, options, platform, arch }) => ({ hostUnsupported: { evmInterface: outsideHost( @@ -277,7 +278,7 @@ const modules = { : { probes: { evmLimiterAvailability: (signal: AbortSignal) => - evmLimiterAvailability(environment, { signal }), + evmLimiterAvailability(environment, { platform, arch, signal }), }, }), }), @@ -287,8 +288,9 @@ const modules = { options.sqliteDatabase ?? createSqliteDatabaseService(environment), ), binaryLayout: service( - ({ environment, options }) => - options.binaryLayout ?? createBinaryLayoutService(environment), + ({ environment, options, platform, arch }) => + options.binaryLayout ?? + createBinaryLayoutService(environment, { platform, architecture: arch }), (context) => ({ hostUnsupported: { binaryLayout: outsideHost( @@ -304,8 +306,12 @@ const modules = { }), ), recordedCrash: service( - ({ environment, options }) => - options.recordedCrash ?? createRecordedCrashService(environment), + ({ environment, options, platform, arch }) => + options.recordedCrash ?? + createRecordedCrashService(environment, { + platform, + architecture: arch, + }), (context) => ({ hostUnsupported: { recordedCrash: outsideHost( @@ -392,9 +398,12 @@ const modules = { createWebNetworkCaptureService(environment, settings), ), javascriptRecovery: capability( - ({ environment, options }) => + ({ environment, options, platform, arch }) => options.javascriptRecovery ?? - createJavaScriptRecoveryProvider(environment), + createJavaScriptRecoveryProvider(environment, undefined, { + platform, + architecture: arch, + }), (value) => value.close?.() ?? Promise.resolve(), ({ environment, options, platform, arch }) => ({ hostUnsupported: { @@ -421,9 +430,13 @@ const modules = { }), ), firmwareAnalysis: service( - ({ environment, options }) => + ({ environment, options, platform, arch }) => new FirmwareAnalysisService( - options.firmwareAnalysis ?? createFirmwareAnalysisProvider(environment), + options.firmwareAnalysis ?? + createFirmwareAnalysisProvider(environment, undefined, { + platform, + architecture: arch, + }), ), ({ environment, options, platform }) => ({ hostUnsupported: { @@ -449,7 +462,8 @@ const modules = { }), ), gdbSessions: capability( - ({ providerEnvironment }) => createGdbSessionManager(providerEnvironment), + ({ providerEnvironment, platform }) => + createGdbSessionManager(providerEnvironment, { platform }), (value) => value.closeAll(), ({ platform }) => ({ hostUnsupported: { @@ -458,8 +472,8 @@ const modules = { }), ), rizinDebugSessions: capability( - ({ providerEnvironment }) => - createRizinDebugSessionManager(providerEnvironment), + ({ providerEnvironment, platform }) => + createRizinDebugSessionManager(providerEnvironment, { platform }), (value) => value.closeAll(), ), android: service( @@ -474,8 +488,8 @@ const modules = { }), ), pcap: service( - ({ environment, options }) => - options.pcapAnalysis ?? createPcapAnalysisProvider(environment), + ({ environment, options, platform }) => + options.pcapAnalysis ?? createPcapAnalysisProvider(environment, platform), ({ options, platform }) => ({ hostUnsupported: { pcapCapture: outsideHost( @@ -503,8 +517,9 @@ const modules = { }), ), packetCapture: service( - ({ environment, options }) => - options.packetCapture ?? createPacketCaptureService(environment), + ({ environment, options, platform }) => + options.packetCapture ?? + createPacketCaptureService(environment, platform), ({ environment, options, platform }) => ({ hostUnsupported: { packetCapture: outsideHost( @@ -520,8 +535,9 @@ const modules = { }), ), signalRecording: service( - ({ environment, options }) => - options.signalRecording ?? createSignalRecordingService(environment), + ({ environment, options, platform }) => + options.signalRecording ?? + createSignalRecordingService(environment, platform), ({ environment, options, platform }) => ({ hostUnsupported: { signalRecording: outsideHost( @@ -542,9 +558,9 @@ const modules = { (value) => value.provider.close?.() ?? Promise.resolve(), ), apktool: service( - ({ environment, options }) => + ({ environment, options, platform }) => options.apktoolAnalysis ?? - createApktoolResourceAnalysisProvider(environment), + createApktoolResourceAnalysisProvider(environment, platform), (_context, value) => ({ probes: { apktoolAnalysisAvailability: (signal: AbortSignal) => @@ -563,8 +579,9 @@ const modules = { }), ), adbDevice: service( - ({ environment, options }) => - options.adbDeviceAnalysis ?? createAdbDeviceAnalysisProvider(environment), + ({ environment, options, platform }) => + options.adbDeviceAnalysis ?? + createAdbDeviceAnalysisProvider(environment, platform), (_context, value) => ({ probes: { adbAnalysisAvailability: (signal: AbortSignal) => diff --git a/src/composition/captures.ts b/src/composition/captures.ts index b8f41a0ef5..fa9f510771 100644 --- a/src/composition/captures.ts +++ b/src/composition/captures.ts @@ -1,7 +1,11 @@ import { PacketCaptureService } from "../application/captures/PacketCaptureService.js"; import { TsharkCaptureProvider } from "../captures/TsharkCaptureProvider.js"; +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; export const createPacketCaptureService = ( environment: Readonly = process.env, + platform: NodeJS.Platform = HOST_PLATFORM.platform, ): PacketCaptureService => - new PacketCaptureService(new TsharkCaptureProvider(environment)); + new PacketCaptureService( + new TsharkCaptureProvider(environment, undefined, undefined, platform), + ); diff --git a/src/composition/evm.ts b/src/composition/evm.ts index 3c9bc4fb5f..7ce0dc109b 100644 --- a/src/composition/evm.ts +++ b/src/composition/evm.ts @@ -1,13 +1,17 @@ import { EvmInterfaceService } from "../application/evm/EvmInterfaceService.js"; import { EvmoleInterfaceProvider } from "../evm/EvmoleInterfaceProvider.js"; +import { HOST_PLATFORM, type HostPlatform } from "../platform/HostPlatform.js"; import { cliCommandFor } from "../cliCommandNames.js"; import { INSPECT_EVM_INTERFACE_CONTRACT } from "../contracts/evm/evmToolContracts.js"; /** Compose offline interface analysis without import-time I/O or dependency acquisition. */ export const createEvmInterfaceService = ( environment: Readonly = process.env, + host: HostPlatform = HOST_PLATFORM, ): EvmInterfaceService => - new EvmInterfaceService(new EvmoleInterfaceProvider(environment)); + new EvmInterfaceService( + new EvmoleInterfaceProvider(environment, undefined, undefined, host), + ); /** * Static binding of the existing operation, command and fresh service factory. diff --git a/src/composition/firmware.ts b/src/composition/firmware.ts index 84952b9123..ecd5c44ec9 100644 --- a/src/composition/firmware.ts +++ b/src/composition/firmware.ts @@ -1,9 +1,11 @@ import type { FirmwareAnalysisPort } from "../ports/firmware/FirmwareAnalysisPort.js"; import type { FirmwareLauncher } from "../firmware/FirmwareCommand.js"; import { FirmwareProvider } from "../firmware/FirmwareProvider.js"; +import { HOST_PLATFORM, type HostPlatform } from "../platform/HostPlatform.js"; /** Construct one firmware provider without launching or acquiring an engine. */ export const createFirmwareAnalysisProvider = ( environment: Readonly> = process.env, launcher?: FirmwareLauncher, -): FirmwareAnalysisPort => new FirmwareProvider(environment, launcher); + host: HostPlatform = HOST_PLATFORM, +): FirmwareAnalysisPort => new FirmwareProvider(environment, launcher, host); diff --git a/src/composition/javascriptRecovery.ts b/src/composition/javascriptRecovery.ts index cac9a9d85f..38321dbb02 100644 --- a/src/composition/javascriptRecovery.ts +++ b/src/composition/javascriptRecovery.ts @@ -1,9 +1,11 @@ import type { JavaScriptRecoveryPort } from "../ports/javascript/JavaScriptRecoveryPort.js"; import { WakaruProvider } from "../javascript/recovery/WakaruProvider.js"; import type { WakaruLauncher } from "../javascript/recovery/WakaruCommand.js"; +import { HOST_PLATFORM, type HostPlatform } from "../platform/HostPlatform.js"; /** Construct optional recovery without acquiring tools, processes or workspaces. */ export const createJavaScriptRecoveryProvider = ( environment: Readonly> = process.env, launcher?: WakaruLauncher, -): JavaScriptRecoveryPort => new WakaruProvider(environment, launcher); + host: HostPlatform = HOST_PLATFORM, +): JavaScriptRecoveryPort => new WakaruProvider(environment, launcher, host); diff --git a/src/composition/pcap.ts b/src/composition/pcap.ts index f3aaa3915e..cbe42c629a 100644 --- a/src/composition/pcap.ts +++ b/src/composition/pcap.ts @@ -1,7 +1,9 @@ import type { PcapAnalysisPort } from "../application/pcap/PcapAnalysisPort.js"; import { PcapProvider } from "../pcap/PcapProvider.js"; +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; /** Construct one pcap provider bound to the caller-selected tools. */ export const createPcapAnalysisProvider = ( environment: Readonly> = process.env, -): PcapAnalysisPort => new PcapProvider({ environment }); + platform: NodeJS.Platform = HOST_PLATFORM.platform, +): PcapAnalysisPort => new PcapProvider({ environment, platform }); diff --git a/src/composition/reverseEngineering.ts b/src/composition/reverseEngineering.ts index 4dbdd77a2c..74a00bc9b6 100644 --- a/src/composition/reverseEngineering.ts +++ b/src/composition/reverseEngineering.ts @@ -1,3 +1,4 @@ +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import type { ReverseEngineeringServiceRuntimeOptions } from "../application/reverse/ReverseEngineeringService.js"; import type { ReverseEngineeringCommandPort, @@ -27,7 +28,7 @@ import { resolveWindowsProviderExecutable } from "./resolveWindowsProviderExecut export const createReverseEngineeringCommandPort = ( environment: Readonly, - platform: NodeJS.Platform = process.platform, + platform: NodeJS.Platform = HOST_PLATFORM.platform, ): ReverseEngineeringCommandPort => ({ objdump: (input) => selectCommand( diff --git a/src/composition/signals.ts b/src/composition/signals.ts index 0bcfbfdb9a..5da314c4df 100644 --- a/src/composition/signals.ts +++ b/src/composition/signals.ts @@ -1,7 +1,11 @@ import { SignalRecordingService } from "../application/signals/SignalRecordingService.js"; +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { SigrokRecordingProvider } from "../signals/SigrokRecordingProvider.js"; export const createSignalRecordingService = ( environment: Readonly = process.env, + platform: NodeJS.Platform = HOST_PLATFORM.platform, ): SignalRecordingService => - new SignalRecordingService(new SigrokRecordingProvider(environment)); + new SignalRecordingService( + new SigrokRecordingProvider(environment, undefined, undefined, platform), + ); diff --git a/src/cutter/CutterBridgeClient.ts b/src/cutter/CutterBridgeClient.ts index cefc988f3d..ecf393dae9 100644 --- a/src/cutter/CutterBridgeClient.ts +++ b/src/cutter/CutterBridgeClient.ts @@ -1,3 +1,4 @@ +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; import { ProviderAdapterError } from "../domain/providerAdapterError.js"; import { @@ -310,7 +311,7 @@ export class CutterBridgeClient { this.#read = options.read; const configured = environment.REA_CUTTER_BRIDGE_DIR; const localAppData = environment.LOCALAPPDATA; - this.#platform = options.platform ?? process.platform; + this.#platform = options.platform ?? HOST_PLATFORM.platform; this.#windowsPrivateReader = options.windowsPrivateReader ?? (this.#platform === "win32" diff --git a/src/desktop/BuildComputerEnvironment.ts b/src/desktop/BuildComputerEnvironment.ts index b774ab25fd..55c4e4c9d7 100644 --- a/src/desktop/BuildComputerEnvironment.ts +++ b/src/desktop/BuildComputerEnvironment.ts @@ -16,7 +16,7 @@ export type BuildComputerSetting = (typeof BUILD_COMPUTER_SETTINGS)[number]; /** The REA-owned folder `rea setup --desktop-build` packs runtime archives into. */ export const buildComputerArchiveDirectory = ( environment: Readonly, - platform: NodeJS.Platform = process.platform, + platform: NodeJS.Platform, ): string => reaCacheDirectory( homeDirectoryFromEnvironment(environment, platform), @@ -28,7 +28,7 @@ export const buildComputerArchiveDirectory = ( /** The runtime archive packed for this REA version, named by that version. */ export const defaultBuildComputerArchive = ( environment: Readonly, - platform: NodeJS.Platform = process.platform, + platform: NodeJS.Platform, directory = buildComputerArchiveDirectory(environment, platform), ): string => appendCallerPath( @@ -94,7 +94,7 @@ export interface BuildComputerDefaults { */ export const resolveBuildComputerEnvironment = async ( environment: Readonly, - platform: NodeJS.Platform = process.platform, + platform: NodeJS.Platform, sources: BuildComputerDefaults = {}, ): Promise> => { const defaults: Record = {}; diff --git a/src/desktop/BuildSecretFiles.test.ts b/src/desktop/BuildSecretFiles.test.ts index 5e1925cdc1..5ab387beb6 100644 --- a/src/desktop/BuildSecretFiles.test.ts +++ b/src/desktop/BuildSecretFiles.test.ts @@ -34,13 +34,13 @@ const refusal = async (directory: string, handle: string) => { describe("build secret files", () => { it("keeps secrets under the XDG config folder, or ~/.config without one", () => { - expect(buildSecretsDirectory({ XDG_CONFIG_HOME: "/cfg", HOME: "/h" })).toBe( - "/cfg/rea/build-secrets", - ); - expect(buildSecretsDirectory({ XDG_CONFIG_HOME: "cfg", HOME: "/h" })).toBe( - "/h/.config/rea/build-secrets", - ); - expect(buildSecretsDirectory({ HOME: "/h" })).toBe( + expect( + buildSecretsDirectory({ XDG_CONFIG_HOME: "/cfg", HOME: "/h" }, "linux"), + ).toBe("/cfg/rea/build-secrets"); + expect( + buildSecretsDirectory({ XDG_CONFIG_HOME: "cfg", HOME: "/h" }, "linux"), + ).toBe("/h/.config/rea/build-secrets"); + expect(buildSecretsDirectory({ HOME: "/h" }, "linux")).toBe( "/h/.config/rea/build-secrets", ); // An absolute XDG_CONFIG_HOME decides the folder without consulting the diff --git a/src/desktop/BuildSecretFiles.ts b/src/desktop/BuildSecretFiles.ts index 27c58ea8fc..783ec64856 100644 --- a/src/desktop/BuildSecretFiles.ts +++ b/src/desktop/BuildSecretFiles.ts @@ -42,7 +42,7 @@ const maxFileBytes = (characters: number) => characters * 4 + 2; /** The folder of secret files on the build host: `rea/build-secrets` under the XDG config folder, or `~/.config`. */ export const buildSecretsDirectory = ( environment: Readonly, - platform: NodeJS.Platform = process.platform, + platform: NodeJS.Platform, ): string => { const root = xdgBase(environment.XDG_CONFIG_HOME, () => // Resolve the home fallback only when it is the one that applies: on a host diff --git a/src/electron/ElectronFusePath.ts b/src/electron/ElectronFusePath.ts index c863ecfd26..9b0a4d40b5 100644 --- a/src/electron/ElectronFusePath.ts +++ b/src/electron/ElectronFusePath.ts @@ -1,3 +1,4 @@ +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { decodeStrictUtf8 } from "../domain/strictUtf8.js"; import { assertArtifactReadActive } from "../resources/index.js"; import type { BigIntStats } from "node:fs"; @@ -372,9 +373,12 @@ const isMissing = (cause: unknown): boolean => "code" in cause && ["ENOENT", "ENOTDIR"].includes(String(cause.code)); -/** Preserve a link target's terminal separator as a directory requirement. */ +/** + * Preserve a link target's terminal separator as a directory requirement. + * The target came from this host's readlink, so this host's separators apply. + */ const symlinkTargetSegments = (target: string): readonly string[] => { - const separator = process.platform === "win32" ? /[\\/]/u : /\//u; + const separator = HOST_PLATFORM.platform === "win32" ? /[\\/]/u : /\//u; const parts = target.split(separator).filter((part) => part !== ""); if (separator.test(target.slice(-1))) parts.push("."); return parts; diff --git a/src/evm/EvmoleInterfaceProvider.ts b/src/evm/EvmoleInterfaceProvider.ts index 2858acf858..0619150458 100644 --- a/src/evm/EvmoleInterfaceProvider.ts +++ b/src/evm/EvmoleInterfaceProvider.ts @@ -3,7 +3,7 @@ import { providerResultDiagnostics, } from "../process/capturedProviderOutput.js"; import { EvmAdmissionError } from "./EvmAdmissionError.js"; -import { HOST_PLATFORM } from "../platform/HostPlatform.js"; +import { HOST_PLATFORM, type HostPlatform } from "../platform/HostPlatform.js"; import type { ProviderRejectionCode } from "../domain/providerSelection.js"; import { snapshotEnvironment } from "../process/snapshotEnvironment.js"; import type { JsonValue } from "../domain/jsonValue.js"; @@ -122,8 +122,9 @@ interface EvmLimiterProbeFileSystem { } interface EvmLimiterProbeOptions { - readonly platform?: NodeJS.Platform; - readonly arch?: string; + /** The host the limiter would run on; it decides whether EVM analysis is supported. */ + readonly platform: NodeJS.Platform; + readonly arch: string; readonly fs?: EvmLimiterProbeFileSystem; readonly signal?: AbortSignal; } @@ -141,9 +142,9 @@ type EvmLimiterUnavailable = EvmLimiterSelection & { /** Select and validate the exact limiter using the same owner check at discovery and admission. */ const selectEvmLimiter = async ( environment: Readonly, - probes?: { - readonly platform?: NodeJS.Platform; - readonly arch?: string; + probes: { + readonly platform: NodeJS.Platform; + readonly arch: string; readonly fs?: EvmLimiterProbeFileSystem; }, signal?: AbortSignal, @@ -153,8 +154,7 @@ const selectEvmLimiter = async ( if (signal?.aborted) throw cancelledBy(operation, signal); }; throwIfAborted(); - const platform = probes?.platform ?? process.platform; - const arch = probes?.arch ?? process.arch; + const { platform, arch } = probes; if (!evmHostSupported(platform, arch)) return undefined; const path = @@ -165,7 +165,7 @@ const selectEvmLimiter = async ( throw new EvmAdmissionError("prlimit_not_absolute", { setting: "REA_EVM_PRLIMIT_COMMAND", }); - const fs = probes?.fs ?? { access, stat }; + const fs = probes.fs ?? { access, stat }; await fs.access(path, constants.X_OK); throwIfAborted(); if (!(await fs.stat(path)).isFile()) @@ -216,12 +216,12 @@ const selectEvmLimiter = async ( /** Fresh, process-free observation of the limiter prerequisite used by EVM execution. */ export const evmLimiterAvailability = async ( environment: Readonly, - probes?: EvmLimiterProbeOptions, + probes: EvmLimiterProbeOptions, ): Promise => { const selected = await selectEvmLimiter( environment, probes, - probes?.signal, + probes.signal, "binary_session", ); if (selected === undefined) return undefined; @@ -439,6 +439,8 @@ export class EvmoleInterfaceProvider implements EvmInterfacePort { readonly createRuntime: () => Promise< Pick > = () => PrivateRuntimeRoot.create({ prefix: "rea-evm-interface-" }), + /** The host the worker runs on; selects the supported-host gate and environment rules. */ + readonly host: HostPlatform = HOST_PLATFORM, ) {} /** Bind recovered interface candidates to both original carrier and decoded byte identity. */ @@ -451,7 +453,7 @@ export class EvmoleInterfaceProvider implements EvmInterfacePort { if (this.#closing) return err(this.#closedError()); const environment = snapshotEnvironment( this.environment, - HOST_PLATFORM.platform, + this.host.platform, ); try { return await this.#resources.run(() => @@ -544,7 +546,7 @@ export class EvmoleInterfaceProvider implements EvmInterfacePort { try { if (options?.signal?.aborted) throw cancelledBy(OPERATION, options.signal); - if (!evmHostSupported(process.platform, process.arch)) + if (!evmHostSupported(this.host.platform, this.host.architecture)) throw new AnalysisCapabilityUnavailableError( EVMOLE_PROVIDER_IDENTITY.id, OPERATION, @@ -553,7 +555,7 @@ export class EvmoleInterfaceProvider implements EvmInterfacePort { ); const selectedLimiter = await selectEvmLimiter( environment, - undefined, + { platform: this.host.platform, arch: this.host.architecture }, options?.signal, ); if (selectedLimiter === undefined) diff --git a/src/filesystem/ChangeTimeBaseline.ts b/src/filesystem/ChangeTimeBaseline.ts index 3e85aec7cd..feebc10e6a 100644 --- a/src/filesystem/ChangeTimeBaseline.ts +++ b/src/filesystem/ChangeTimeBaseline.ts @@ -5,6 +5,7 @@ import { resolveWindowsChangeTimeSettle, type WindowsChangeTimeSettleLimits, } from "../config/windowsChangeTimeSettle.js"; +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; /** * Windows advances a file's ChangeTime shortly after it is written, without any @@ -23,6 +24,7 @@ import { */ export interface ChangeTimeSettleSeams { + /** The host whose filesystem produced the stats; omission is the running host. */ readonly platform?: NodeJS.Platform | undefined; readonly now?: (() => number) | undefined; readonly sleep?: ((delayMs: number) => Promise) | undefined; @@ -74,7 +76,7 @@ const changeTimeMayStillDrift = ( stats: Stats, seams: ChangeTimeSettleSeams = {}, ): boolean => { - const platform = seams.platform ?? process.platform; + const platform = seams.platform ?? HOST_PLATFORM.platform; if (platform !== "win32") return false; const changeTime = changeTimeMs(stats); // An unreadable ChangeTime cannot establish that it has settled; re-observation @@ -102,7 +104,7 @@ export const settleChangeTimeBaseline = async ( seams: ChangeTimeSettleSeams = {}, ): Promise => { throwIfAborted(seams); - if ((seams.platform ?? process.platform) !== "win32") { + if ((seams.platform ?? HOST_PLATFORM.platform) !== "win32") { const observed = await read(); throwIfAborted(seams); return observed; diff --git a/src/filesystem/callerPath.ts b/src/filesystem/callerPath.ts index 1e17b24a90..8ec8e69556 100644 --- a/src/filesystem/callerPath.ts +++ b/src/filesystem/callerPath.ts @@ -1,12 +1,16 @@ import { posix, win32 } from "node:path"; +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; + /** Append a relative child without collapsing POSIX symlink/.. traversal. * Preserve relative parents too: configuration admission owns absolute-path validation. + * The platform defaults to the running host because most callers then open the + * joined path on this host; a caller describing another host's layout passes it. */ export const appendCallerPath = ( parent: string, child: string, - platform: NodeJS.Platform = process.platform, + platform: NodeJS.Platform = HOST_PLATFORM.platform, ): string => platform === "win32" ? win32.join(parent, child) @@ -24,12 +28,13 @@ export const appendCallerPath = ( * A relative `cwd` is made absolute the same way. Win32 resolves `..` * lexically, so normalizing there is exact. Absolute POSIX paths never need * the ambient cwd, which may already have been removed during cleanup. + * Without `platform` the running host's rules apply, as they do to its cwd. */ export const absoluteCallerPath = ( path: string, { cwd, - platform = process.platform, + platform = HOST_PLATFORM.platform, }: { readonly cwd?: string; readonly platform?: NodeJS.Platform } = {}, ): string => { if (platform === "win32") return win32.resolve(cwd ?? process.cwd(), path); diff --git a/src/firmware/FirmwareCommand.test.ts b/src/firmware/FirmwareCommand.test.ts index ac8d3c261a..fb0cf5651d 100644 --- a/src/firmware/FirmwareCommand.test.ts +++ b/src/firmware/FirmwareCommand.test.ts @@ -218,6 +218,7 @@ test("names the host and tool requirement of an unconfigured engine", async () = "binwalk", "inspect_firmware_regions", new FirmwareFileAccess(), + "linux", ).catch((cause: unknown) => cause); expect(refusal).toMatchObject({ @@ -248,6 +249,7 @@ it("rejects a directory configured as the firmware engine executable", async () "binwalk", "inspect_firmware_regions", new FirmwareFileAccess(), + "linux", ), ).rejects.toMatchObject({ _tag: "AnalysisCapabilityUnavailableError", @@ -272,6 +274,7 @@ it("classifies an unusable firmware engine as an unavailable capability", async "binwalk", "inspect_firmware_regions", new FirmwareFileAccess(), + "linux", ), ).rejects.toMatchObject({ _tag: "AnalysisCapabilityUnavailableError", @@ -294,6 +297,7 @@ it("rejects a directory configured as the resource limiter executable", async () "binwalk", "inspect_firmware_regions", new FirmwareFileAccess(), + "linux", ), ).rejects.toMatchObject({ _tag: "AnalysisCapabilityUnavailableError", diff --git a/src/firmware/FirmwareCommand.ts b/src/firmware/FirmwareCommand.ts index 02fe6f2be3..8e8def3a2c 100644 --- a/src/firmware/FirmwareCommand.ts +++ b/src/firmware/FirmwareCommand.ts @@ -102,12 +102,14 @@ export const resolveFirmwareCommand = async ( engine: FirmwareEngineName, operation: string, files: FirmwareFileAccess, + /** The host the engine runs on; firmware engines are admitted on Linux only. */ + platform: NodeJS.Platform, signal?: AbortSignal, ) => { const variable = FIRMWARE_TOOL_REQUIREMENTS[engine].commandEnvironment; const configured = environment[variable]; if ( - !firmwareHostSupported(process.platform) || + !firmwareHostSupported(platform) || configured === undefined || !isAbsolute(configured) ) diff --git a/src/firmware/FirmwareProvider.ts b/src/firmware/FirmwareProvider.ts index 828bf6b44a..04919da691 100644 --- a/src/firmware/FirmwareProvider.ts +++ b/src/firmware/FirmwareProvider.ts @@ -1,5 +1,5 @@ import { FIRMWARE_OPERATION_ENGINES } from "../contracts/firmware/firmwareToolRequirements.js"; -import { HOST_PLATFORM } from "../platform/HostPlatform.js"; +import { HOST_PLATFORM, type HostPlatform } from "../platform/HostPlatform.js"; import { snapshotEnvironment } from "../process/snapshotEnvironment.js"; import { assertArtifactCommandPath } from "../process/ArtifactCommandPath.js"; import { join } from "node:path"; @@ -168,6 +168,8 @@ export class FirmwareProvider implements FirmwareAnalysisPort { Record > = process.env, readonly launcher?: FirmwareLauncher, + /** The host the engines run on; selects the supported-host gate and environment rules. */ + readonly host: HostPlatform = HOST_PLATFORM, ) {} /** Inspect regions or explicitly extract selected bytes without changing the source. */ @@ -350,7 +352,7 @@ export class FirmwareProvider implements FirmwareAnalysisPort { // Capture configuration after queue admission; later operations may select updates. const environment = snapshotEnvironment( this.environment, - HOST_PLATFORM.platform, + this.host.platform, ); let root: PrivateRuntimeRoot | undefined; let rootLease: AnalysisCleanupLease | undefined; @@ -384,6 +386,7 @@ export class FirmwareProvider implements FirmwareAnalysisPort { engineName, request.operation, this.#files, + this.host.platform, signal, ); root = await PrivateRuntimeRoot.create({ prefix: "rea-firmware-" }); diff --git a/src/gdb/GdbSessionManager.ts b/src/gdb/GdbSessionManager.ts index 13893f3b69..959a6b0711 100644 --- a/src/gdb/GdbSessionManager.ts +++ b/src/gdb/GdbSessionManager.ts @@ -12,6 +12,7 @@ import { type GdbProviderIdentity, } from "./GdbProviderIdentity.js"; import { persistentDebuggerHostSupported } from "../process/PersistentDebuggerHost.js"; +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { AbortedWait, waitForAbortable } from "../process/AbortablePromise.js"; import { classifyLaunchFailure } from "../process/launchFailure.js"; import { snapshotGdbCommandRecords } from "./GdbCommandRecords.js"; @@ -247,7 +248,8 @@ const verifyGdbInferiorOutputSink = async ( selectedTty: string, rememberIdentity: (identity: OwnedInferiorIdentity) => void, ): Promise => { - if (process.platform !== "linux") + // The descriptors live in this host's /proc, whichever host the manager models. + if (HOST_PLATFORM.platform !== "linux") throw new Error( "GDB cannot confirm live inferior output descriptors outside Linux /proc.", ); @@ -420,7 +422,7 @@ export class GdbSessionManager { const limits = debuggerConstructionLimits(this.#environment); this.#launchCommandDeadline = limits.commandDeadline; this.#startupTimeoutMs = options.startupTimeoutMs ?? STARTUP_TIMEOUT_MS; - this.#platform = options.platform ?? process.platform; + this.#platform = options.platform ?? HOST_PLATFORM.platform; const stopProcess = options.stopProcess ?? stopOwnedDebuggerProcess; this.#sessions = new OwnedDebuggerSessionRegistry({ provider: "gdb", diff --git a/src/hopper/BridgeLauncher.ts b/src/hopper/BridgeLauncher.ts index 2f0a85b44c..1433170c44 100644 --- a/src/hopper/BridgeLauncher.ts +++ b/src/hopper/BridgeLauncher.ts @@ -1,3 +1,4 @@ +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { execFile } from "node:child_process"; import { chmod, rm, writeFile } from "node:fs/promises"; import { basename, dirname, extname, join } from "node:path"; @@ -202,7 +203,12 @@ export class HopperApplicationLauncher implements BridgeLauncher { constructor( readonly options: HopperApplicationLauncherOptions, readonly dependencies: HopperApplicationLauncherDependencies = {}, - ) {} + ) { + this.#platform = dependencies.platform ?? HOST_PLATFORM.platform; + } + + /** The host Hopper runs on; defaults to the running host. */ + readonly #platform: NodeJS.Platform; async cleanup(): Promise> { const failures: ProviderCleanupError[] = []; @@ -411,7 +417,7 @@ export class HopperApplicationLauncher implements BridgeLauncher { let launched = false; try { if (signal?.aborted === true) return err(hopperCancelledBySignal(signal)); - if ((this.dependencies.platform ?? process.platform) === "darwin") { + if (this.#platform === "darwin") { // The vendor helper embeds argv in AppleScript quoted literals. Check // the actual prepared paths before even starting the application. Do // not rewrite caller names or double-escape values passed to the helper. @@ -460,7 +466,7 @@ export class HopperApplicationLauncher implements BridgeLauncher { const display = await this.#privateDisplay(signal); if (!display.ok) return display; const nativeHelperVerified = - (this.dependencies.platform ?? process.platform) === "darwin" && + this.#platform === "darwin" && this.options.launchMode === "native" && (await ( this.dependencies.verifyNativeHelper ?? verifyMacHopperNativeHelper @@ -523,7 +529,7 @@ export class HopperApplicationLauncher implements BridgeLauncher { ? { nativeHelperVerified: true as const } : {}), // Argument admission above established literal handoff semantics. - ...((this.dependencies.platform ?? process.platform) === "darwin" + ...(this.#platform === "darwin" ? { authorizationDenialBeforeHandoff: true as const } : {}), }); @@ -541,7 +547,7 @@ export class HopperApplicationLauncher implements BridgeLauncher { async #acquireLaunchLease( runId: string, ): Promise> { - const platform = this.dependencies.platform ?? process.platform; + const platform = this.#platform; const applicationLease = platform === "linux" && usesLinuxDemo(this.options); if (!applicationLease && platform !== "darwin") return ok(undefined); diff --git a/src/hopper/HopperClient.ts b/src/hopper/HopperClient.ts index c548939827..dbeabb341b 100644 --- a/src/hopper/HopperClient.ts +++ b/src/hopper/HopperClient.ts @@ -1,3 +1,4 @@ +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { JsonLineBridgeReader, type JsonLineBridgeFailure, @@ -113,7 +114,7 @@ import { /** Aggregate in-memory retention budget for this provider's launcher output. */ const HOPPER_PROCESS_DIAGNOSTIC_BYTES = 8 * 1024 * 1024; -const SESSION_ROOT = process.platform === "darwin" ? "/tmp" : tmpdir(); +const SESSION_ROOT = HOST_PLATFORM.platform === "darwin" ? "/tmp" : tmpdir(); /** Dependencies, deadlines, and redacted diagnostics for one bridge client. */ export interface HopperClientOptions< diff --git a/src/hopper/HopperProvider.ts b/src/hopper/HopperProvider.ts index 832ac10deb..7e5e9503e6 100644 --- a/src/hopper/HopperProvider.ts +++ b/src/hopper/HopperProvider.ts @@ -1,3 +1,4 @@ +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { bindArtifactFileCleanup, AnalysisCleanupLease, @@ -92,7 +93,7 @@ export class HopperProvider implements AnalysisProviderCandidate { private readonly config: AppConfig, private readonly logger: Logger, environment: Readonly, - private readonly platform: NodeJS.Platform = process.platform, + private readonly platform: NodeJS.Platform = HOST_PLATFORM.platform, /** * Linux launcher authentication from Hopper setup, supplied by * composition. Without it a Linux launch is refused before Hopper runs. @@ -350,13 +351,16 @@ export class HopperProvider implements AnalysisProviderCandidate { } : { launchMode: "native" as const }), }, - this.linuxLauncherVerification === undefined - ? {} - : { - verifyLinuxLauncher: this.linuxLauncherVerification.inspect, - retryPublisherCleanup: - this.linuxLauncherVerification.retryCleanup, - }, + { + platform: this.platform, + ...(this.linuxLauncherVerification === undefined + ? {} + : { + verifyLinuxLauncher: this.linuxLauncherVerification.inspect, + retryPublisherCleanup: + this.linuxLauncherVerification.retryCleanup, + }), + }, ), ...(context === undefined ? {} : { runId: context.runId }), readStartupTimeoutMs: () => this.config.hopperStartupTimeoutMs, diff --git a/src/ida/IdaWorkspace.ts b/src/ida/IdaWorkspace.ts index 67494a82d9..7d8367fdb7 100644 --- a/src/ida/IdaWorkspace.ts +++ b/src/ida/IdaWorkspace.ts @@ -1,5 +1,7 @@ import { createHash, randomUUID } from "node:crypto"; import { createReadStream } from "node:fs"; + +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { open, realpath, stat, type FileHandle } from "node:fs/promises"; import { tmpdir } from "node:os"; import { basename, isAbsolute, join, normalize } from "node:path"; @@ -24,7 +26,7 @@ export const idaFileDigest = async (path: string): Promise => { /** Compare host-local spellings without collapsing POSIX symlink/.. traversal. */ export const sameIdaHostPath = (left: string, right: string): boolean => - process.platform === "win32" + HOST_PLATFORM.platform === "win32" ? normalize(left).toLowerCase() === normalize(right).toLowerCase() : isAbsolute(left) === isAbsolute(right) && absoluteCallerPath(left) === absoluteCallerPath(right); diff --git a/src/inspector/JavaScriptRuntimeScope.ts b/src/inspector/JavaScriptRuntimeScope.ts index ed46d46347..10689f8613 100644 --- a/src/inspector/JavaScriptRuntimeScope.ts +++ b/src/inspector/JavaScriptRuntimeScope.ts @@ -2,6 +2,7 @@ import { DEFAULT_ASAR_HEADER_ADMISSION, type AsarHeaderAdmission, } from "../config/asarHeaderAdmission.js"; +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { pathToFileURL } from "node:url"; import { @@ -151,7 +152,8 @@ export const authorizeRuntimeTargetLocation = async ( // Node concatenates the pathname, then replaces quotes and backslashes with // underscores. A remaining underscore cannot prove which pathname was used. - if (process.platform !== "win32" && !/[_"\\]/u.test(reportedPath)) { + // The runtime runs on this host and reports one of this host's paths. + if (HOST_PLATFORM.platform !== "win32" && !/[_"\\]/u.test(reportedPath)) { if (reportedPath.startsWith("/")) { const decision = await authorizeRuntimeLocation( pathToFileURL(reportedPath).href, diff --git a/src/javascript/analysis/JavaScriptAnalysisSourceTransfer.ts b/src/javascript/analysis/JavaScriptAnalysisSourceTransfer.ts index 6abef49857..817993d83a 100644 --- a/src/javascript/analysis/JavaScriptAnalysisSourceTransfer.ts +++ b/src/javascript/analysis/JavaScriptAnalysisSourceTransfer.ts @@ -1,6 +1,7 @@ import { writeFile } from "node:fs/promises"; import { win32 } from "node:path"; +import { HOST_PLATFORM } from "../../platform/HostPlatform.js"; import { windowsPrivateRuntime } from "../../windows/WindowsPrivateRuntime.js"; /** @@ -16,11 +17,12 @@ export const writeJavaScriptAnalysisSourceTransfer = async ( path: string, source: string, options: { + /** The host whose filesystem holds the runtime root; defaults to the running host. */ readonly platform?: NodeJS.Platform; readonly signal?: AbortSignal; } = {}, ): Promise => { - const platform = options.platform ?? process.platform; + const platform = options.platform ?? HOST_PLATFORM.platform; options.signal?.throwIfAborted(); if (platform === "win32") { // Yield through a timer phase so ProviderStartupDeadline setTimeout diff --git a/src/javascript/recovery/WakaruCommand.test.ts b/src/javascript/recovery/WakaruCommand.test.ts index 8d509b03bc..531a01b4ac 100644 --- a/src/javascript/recovery/WakaruCommand.test.ts +++ b/src/javascript/recovery/WakaruCommand.test.ts @@ -1,4 +1,5 @@ import { createTestArtifactResourceScope } from "../../../tests/fixtures/artifactResourceScope.js"; +import { SIMULATED_LINUX_X64 } from "../../../tests/fixtures/simulatedHost.js"; import { ProcessOwnershipInspectionCancelled, ProcessOwnershipIdentityBatchFailure, @@ -32,9 +33,10 @@ import { prlimitArgumentVector } from "../../process/LinuxResourceLimits.js"; import { RECOVERY_LIMITS } from "./WakaruRelease.js"; it("names the Wakaru configuration requirement when it is not configured", async () => { - const refusal: unknown = await resolveWakaruCommand({}).catch( - (cause: unknown) => cause, - ); + const refusal: unknown = await resolveWakaruCommand( + {}, + SIMULATED_LINUX_X64, + ).catch((cause: unknown) => cause); if (!(refusal instanceof AnalysisCapabilityUnavailableError)) throw new Error("Expected a capability refusal"); diff --git a/src/javascript/recovery/WakaruCommand.ts b/src/javascript/recovery/WakaruCommand.ts index 4d9bcedbaf..2c1ed2d95b 100644 --- a/src/javascript/recovery/WakaruCommand.ts +++ b/src/javascript/recovery/WakaruCommand.ts @@ -1,5 +1,6 @@ import { capturedProviderOutput } from "../../process/capturedProviderOutput.js"; import { selectArtifactCommandPath } from "../../process/ArtifactCommandPath.js"; +import type { HostPlatform } from "../../platform/HostPlatform.js"; import { randomUUID } from "node:crypto"; import { constants } from "node:fs"; import { access, stat } from "node:fs/promises"; @@ -89,12 +90,14 @@ export class WakaruCleanupFailure extends ProviderCleanupError { /** Resolve and fingerprint explicitly configured tools; acquire nothing at startup. */ export const resolveWakaruCommand = async ( environment: Readonly>, + /** The host Wakaru runs on; it is admitted on Linux x64 only. */ + host: HostPlatform, resources?: ArtifactResourceScope, signal?: AbortSignal, ) => { const configured = environment.REA_WAKARU_COMMAND; if ( - !wakaruHostSupported(process.platform, process.arch) || + !wakaruHostSupported(host.platform, host.architecture) || configured === undefined || !isAbsolute(configured) ) diff --git a/src/javascript/recovery/WakaruProvider.ts b/src/javascript/recovery/WakaruProvider.ts index cfba3df7fe..2804203c1e 100644 --- a/src/javascript/recovery/WakaruProvider.ts +++ b/src/javascript/recovery/WakaruProvider.ts @@ -1,5 +1,8 @@ import { snapshotEnvironment } from "../../process/snapshotEnvironment.js"; -import { HOST_PLATFORM } from "../../platform/HostPlatform.js"; +import { + HOST_PLATFORM, + type HostPlatform, +} from "../../platform/HostPlatform.js"; import { mkdir, mkdtemp, rm } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; @@ -76,6 +79,8 @@ export class WakaruProvider implements JavaScriptRecoveryPort { Record > = process.env, readonly launcher?: WakaruLauncher, + /** The host Wakaru runs on; selects the supported-host gate and environment rules. */ + readonly host: HostPlatform = HOST_PLATFORM, ) {} /** Recover selected scripts using validated reports and verified output bytes. */ @@ -111,7 +116,7 @@ export class WakaruProvider implements JavaScriptRecoveryPort { // Capture configuration after queue/cleanup admission; later requests may select updates. const environment = snapshotEnvironment( this.environment, - HOST_PLATFORM.platform, + this.host.platform, ); let root: string | undefined; let tree: SafeOutputTree | undefined; @@ -122,6 +127,7 @@ export class WakaruProvider implements JavaScriptRecoveryPort { checkRecoveryCancellation(options?.signal); const engine = await resolveWakaruCommand( environment, + this.host, this.#resources, options?.signal, ); diff --git a/src/kuna/KunaAdmission.ts b/src/kuna/KunaAdmission.ts index efa07b914a..8ac40db37f 100644 --- a/src/kuna/KunaAdmission.ts +++ b/src/kuna/KunaAdmission.ts @@ -27,7 +27,7 @@ export interface KunaAdmissionRefusal { */ export const admitKunaCommand = ( environment: Readonly, - platform?: NodeJS.Platform, + platform: NodeJS.Platform, ): Result => { const configuration = readKunaConfiguration(environment, platform); if (!configuration.ok) { diff --git a/src/kuna/KunaConfiguration.ts b/src/kuna/KunaConfiguration.ts index 3fab61be63..1c960bbd47 100644 --- a/src/kuna/KunaConfiguration.ts +++ b/src/kuna/KunaConfiguration.ts @@ -181,7 +181,7 @@ const refuseInvalidLaunch = ( /** Parse the Kuna settings without touching the filesystem or the executable. */ export const readKunaConfiguration = ( environment: Readonly, - platform: NodeJS.Platform = process.platform, + platform: NodeJS.Platform, ): Result => { const command = environment.REA_KUNA_COMMAND; if (command === undefined || command.length === 0) diff --git a/src/kuna/KunaDoctor.ts b/src/kuna/KunaDoctor.ts index 1b2af90313..ee0f7be376 100644 --- a/src/kuna/KunaDoctor.ts +++ b/src/kuna/KunaDoctor.ts @@ -63,7 +63,7 @@ export const KUNA_REGISTRATION_SETTINGS = KUNA_DOCTOR_SETTINGS.filter( */ export const inspectKunaProvider = async ( environment: Readonly, - platform: NodeJS.Platform = process.platform, + platform: NodeJS.Platform, options: { readonly resourceScope: RetainedResourceScope; readonly signal?: AbortSignal; diff --git a/src/kuna/KunaInstallation.ts b/src/kuna/KunaInstallation.ts index 4529a847e6..b03e560725 100644 --- a/src/kuna/KunaInstallation.ts +++ b/src/kuna/KunaInstallation.ts @@ -130,7 +130,8 @@ export interface KunaReadinessFailure { } export interface KunaInstallationOptions { - readonly platform?: NodeJS.Platform; + /** The host Kuna runs on; it decides launcher and path rules. */ + readonly platform: NodeJS.Platform; readonly signal?: AbortSignal; /** Probe deadline; tests shorten it. */ readonly probeTimeoutMs?: number; diff --git a/src/kuna/KunaProvider.ts b/src/kuna/KunaProvider.ts index 068e62d8d3..c6e3399a56 100644 --- a/src/kuna/KunaProvider.ts +++ b/src/kuna/KunaProvider.ts @@ -1,3 +1,4 @@ +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { KUNA_STRING_MIN_LENGTH } from "./KunaLimits.js"; import type { @@ -90,7 +91,7 @@ export class KunaProvider implements AnalysisProviderCandidate { readonly regexWorkerHeapRequest?: RegexWorkerHeapRequest; } = {}, ) { - this.#platform = options.platform ?? process.platform; + this.#platform = options.platform ?? HOST_PLATFORM.platform; this.#environment = snapshotEnvironment(environment, this.#platform); this.#deadline = options.regexMatchingDeadline ?? @@ -305,6 +306,7 @@ export class KunaProvider implements AnalysisProviderCandidate { cache: this.#projectCache(configuration.value), runSlots: this.#foregroundSlots(configuration.value), environment: this.#environment, + platform: this.#platform, deadline: this.#deadline, heapRequest: this.#heapRequest, ...(this.#launcher === undefined ? {} : { launcher: this.#launcher }), diff --git a/src/kuna/KunaSessionClient.ts b/src/kuna/KunaSessionClient.ts index 1172ed04b6..34fe4f1857 100644 --- a/src/kuna/KunaSessionClient.ts +++ b/src/kuna/KunaSessionClient.ts @@ -379,6 +379,7 @@ export class KunaSessionClient implements AnalysisClient { readonly #profile: AnalysisProfileCommitment | undefined; readonly #cache: KunaProjectCache; readonly #environment: Readonly; + readonly #platform: NodeJS.Platform; readonly #runSlots: KunaRunSlots; readonly #launcher: KunaProcessLauncher | undefined; readonly #resourceScope = new ArtifactResourceScope(); @@ -446,6 +447,7 @@ export class KunaSessionClient implements AnalysisClient { readonly cache: KunaProjectCache; readonly runSlots: KunaRunSlots; readonly environment: Readonly; + readonly platform: NodeJS.Platform; readonly deadline: RegexMatchingDeadline; readonly heapRequest: RegexWorkerHeapRequest; readonly launcher?: KunaProcessLauncher; @@ -456,6 +458,7 @@ export class KunaSessionClient implements AnalysisClient { this.#cache = dependencies.cache; this.#runSlots = dependencies.runSlots; this.#environment = dependencies.environment; + this.#platform = dependencies.platform; this.#launcher = dependencies.launcher; this.#commands = new KunaTargetCommands(target, { signal: this.#session.signal, @@ -2029,6 +2032,7 @@ export class KunaSessionClient implements AnalysisClient { const kunaResources = createKunaResourceScope(parentResourceScope); try { const inspected = await inspectKunaInstallation(this.#environment, { + platform: this.#platform, resourceScope: kunaResources.owner, signal, ...(this.#launcher === undefined diff --git a/src/native/NativeMacOSProvider.ts b/src/native/NativeMacOSProvider.ts index 7ac7f669b3..2ad3ec7a1a 100644 --- a/src/native/NativeMacOSProvider.ts +++ b/src/native/NativeMacOSProvider.ts @@ -1,3 +1,4 @@ +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { readerIntegrityFailure, bindArtifactFileCleanup, @@ -196,7 +197,7 @@ export class NativeMacOSProvider implements AnalysisProvider { private readonly runner: NativeCommandRunner = new XcrunCommandRunner( environment, ), - platform: NodeJS.Platform = process.platform, + platform: NodeJS.Platform = HOST_PLATFORM.platform, tracerFactory?: () => NativeCallTracer, privateRuntimeRootFactory?: SignatureRuntimeRootFactory, ) { diff --git a/src/native/NativeMacOSProviderMetadata.ts b/src/native/NativeMacOSProviderMetadata.ts index 9e3a2da4fb..d414fd6c99 100644 --- a/src/native/NativeMacOSProviderMetadata.ts +++ b/src/native/NativeMacOSProviderMetadata.ts @@ -25,7 +25,7 @@ const OWNED_PROCESS_OPERATIONS: ReadonlySet = new Set([ /** Declare native host coverage without creating a command runner. */ export const nativeMacOSCapabilities = ( - platform: NodeJS.Platform = process.platform, + platform: NodeJS.Platform, ): readonly CapabilityDescriptor[] => { const available = platform === "darwin"; return Object.freeze( diff --git a/src/native/pwntools/PwntoolsDecoder.ts b/src/native/pwntools/PwntoolsDecoder.ts index 5394398777..a891305f98 100644 --- a/src/native/pwntools/PwntoolsDecoder.ts +++ b/src/native/pwntools/PwntoolsDecoder.ts @@ -3,7 +3,10 @@ import { providerResultDiagnostics, } from "../../process/capturedProviderOutput.js"; import { classifyProviderFailure } from "../../providers/classifyProviderFailure.js"; -import { HOST_PLATFORM } from "../../platform/HostPlatform.js"; +import { + HOST_PLATFORM, + type HostPlatform, +} from "../../platform/HostPlatform.js"; import { snapshotEnvironment } from "../../process/snapshotEnvironment.js"; import { invariantViolation } from "../../domain/internalInvariant.js"; import { safeParseUtf8Json } from "../../domain/safeJson.js"; @@ -187,6 +190,8 @@ export class PwntoolsDecoder< readonly createRuntime: () => Promise< Pick > = () => PrivateRuntimeRoot.create({ prefix: "rea-artifact-decoder-" }), + /** The host the decoder runs on; selects the supported-host gate. */ + readonly host: HostPlatform = HOST_PLATFORM, ) { this.identity = profile.identity; } @@ -252,7 +257,7 @@ export class PwntoolsDecoder< ): Promise> { const environment = snapshotEnvironment( this.environment, - HOST_PLATFORM.platform, + this.host.platform, ); const selectedLimits = pwntoolsProducerLimitsSchema.safeParse( input.producer_limits === undefined ? {} : input.producer_limits, @@ -336,10 +341,10 @@ export class PwntoolsDecoder< try { if (options?.signal?.aborted) throw cancelledBy(OPERATION, options.signal); - if (!pwntoolsHostSupported(process.platform, process.arch)) { + if (!pwntoolsHostSupported(this.host.platform, this.host.architecture)) { const requirement = pwntoolsHostRequirement( - process.platform, - process.arch, + this.host.platform, + this.host.architecture, ); throw new AnalysisCapabilityUnavailableError( this.identity.id, diff --git a/src/native/pwntools/PwntoolsLayoutProvider.ts b/src/native/pwntools/PwntoolsLayoutProvider.ts index d0c49e47d7..02a3c89418 100644 --- a/src/native/pwntools/PwntoolsLayoutProvider.ts +++ b/src/native/pwntools/PwntoolsLayoutProvider.ts @@ -1,3 +1,4 @@ +import type { HostPlatform } from "../../platform/HostPlatform.js"; import { binaryLayoutPayloadSchema, binaryLayoutSchema, @@ -26,6 +27,7 @@ export class PwntoolsLayoutProvider createRuntime: () => Promise< Pick > = () => PrivateRuntimeRoot.create({ prefix: "rea-elf-layout-" }), + host?: HostPlatform, ) { super( { @@ -69,6 +71,7 @@ export class PwntoolsLayoutProvider environment, launcher, createRuntime, + host, ); } } diff --git a/src/native/pwntools/PwntoolsRecordedCrashProvider.ts b/src/native/pwntools/PwntoolsRecordedCrashProvider.ts index e27e579ce7..08ce511425 100644 --- a/src/native/pwntools/PwntoolsRecordedCrashProvider.ts +++ b/src/native/pwntools/PwntoolsRecordedCrashProvider.ts @@ -1,3 +1,4 @@ +import type { HostPlatform } from "../../platform/HostPlatform.js"; import { AnalysisOutputError, cancelledBy, @@ -39,6 +40,7 @@ export class PwntoolsRecordedCrashProvider createRuntime: () => Promise< Pick > = () => PrivateRuntimeRoot.create({ prefix: "rea-recorded-crash-" }), + host?: HostPlatform, ) { super( { @@ -195,6 +197,7 @@ export class PwntoolsRecordedCrashProvider environment, launcher, createRuntime, + host, ); } } diff --git a/src/native/windows/WindowsShortcutProvider.ts b/src/native/windows/WindowsShortcutProvider.ts index 364767f151..2e8b41459f 100644 --- a/src/native/windows/WindowsShortcutProvider.ts +++ b/src/native/windows/WindowsShortcutProvider.ts @@ -1,3 +1,4 @@ +import { HOST_PLATFORM } from "../../platform/HostPlatform.js"; import { parseFailureAnalysisError } from "../../domain/parseFailureAnalysisError.js"; import { lstat, open } from "node:fs/promises"; import { @@ -139,7 +140,9 @@ export class WindowsShortcutProvider implements WindowsShortcutPort { readonly identity = WINDOWS_SHORTCUT_PROVIDER; readonly #resources = new ArtifactResourceScope(); - constructor(private readonly platform: NodeJS.Platform = process.platform) {} + constructor( + private readonly platform: NodeJS.Platform = HOST_PLATFORM.platform, + ) {} async close(): Promise { try { diff --git a/src/pcap/PcapCommand.ts b/src/pcap/PcapCommand.ts index c14b56e066..f857b4bb4d 100644 --- a/src/pcap/PcapCommand.ts +++ b/src/pcap/PcapCommand.ts @@ -74,6 +74,8 @@ export interface PcapCommandLimits { /** Owned process execution shared by version probes and capture reads. */ export const runPcapCommand = async (options: { readonly operation: string; + /** The host the command runs on; Windows launches batch files through cmd. */ + readonly platform: NodeJS.Platform; readonly command: string; readonly arguments: readonly string[]; readonly limits: PcapCommandLimits; @@ -140,7 +142,7 @@ export const runPcapCommand = async (options: { let cleanup: PcapCommandCleanup | undefined; let commandAttempted = false; try { - const batch = process.platform === "win32" && isWindowsBatchFile(command); + const batch = options.platform === "win32" && isWindowsBatchFile(command); const invocation = batch ? windowsBatchCommand({ environment: hostEnvironment, diff --git a/src/pcap/PcapConfiguration.test.ts b/src/pcap/PcapConfiguration.test.ts index efaffa2534..155b8e7f7f 100644 --- a/src/pcap/PcapConfiguration.test.ts +++ b/src/pcap/PcapConfiguration.test.ts @@ -18,10 +18,13 @@ import { parseCapinfosOutput, parseTsharkJsonOutput } from "./PcapOutput.js"; describe("resolvePcapTools", () => { it("prefers absolute environment paths for both tools", () => { expect( - resolvePcapTools({ - [TSHARK_COMMAND_ENV]: "/usr/bin/tshark", - [CAPINFOS_COMMAND_ENV]: "/usr/bin/capinfos", - }), + resolvePcapTools( + { + [TSHARK_COMMAND_ENV]: "/usr/bin/tshark", + [CAPINFOS_COMMAND_ENV]: "/usr/bin/capinfos", + }, + "linux", + ), ).toEqual({ tshark: { command: "/usr/bin/tshark", source: "environment" }, capinfos: { command: "/usr/bin/capinfos", source: "environment" }, @@ -75,13 +78,13 @@ describe("resolvePcapTools", () => { it("rejects a relative tshark path explicitly", () => { expect(() => - resolvePcapTools({ [TSHARK_COMMAND_ENV]: "bin/tshark" }), + resolvePcapTools({ [TSHARK_COMMAND_ENV]: "bin/tshark" }, "linux"), ).toThrow(/must be an absolute path/u); }); it("rejects a relative capinfos path explicitly", () => { expect(() => - resolvePcapTools({ [CAPINFOS_COMMAND_ENV]: "capinfos" }), + resolvePcapTools({ [CAPINFOS_COMMAND_ENV]: "capinfos" }, "linux"), ).toThrow(/must be an absolute path/u); }); }); @@ -408,11 +411,11 @@ it.skipIf(process.platform === "win32")( for (const directory of [root, intended]) for (const tool of ["tshark", "capinfos"]) await writeFile(join(directory, tool), "", { mode: 0o755 }); - const selected = resolvePcapTools({ PATH: `${root}/alias/..` }); + const selected = resolvePcapTools({ PATH: `${root}/alias/..` }, "linux"); for (const tool of ["tshark", "capinfos"] as const) expect(await realpath(selected[tool].command)).toBe(join(intended, tool)); - expect(() => resolvePcapTools({ PATH: `${root}/missing/..` })).toThrow( - /tshark was not found/u, - ); + expect(() => + resolvePcapTools({ PATH: `${root}/missing/..` }, "linux"), + ).toThrow(/tshark was not found/u); }, ); diff --git a/src/pcap/PcapConfiguration.ts b/src/pcap/PcapConfiguration.ts index 9b89ffedf2..8fd856d8d8 100644 --- a/src/pcap/PcapConfiguration.ts +++ b/src/pcap/PcapConfiguration.ts @@ -112,7 +112,7 @@ export const selectWiresharkTool = ( */ export const resolvePcapTools = ( environment: Readonly>, - platform: NodeJS.Platform = process.platform, + platform: NodeJS.Platform, ): PcapToolSelection => { // Report every configuration error before consulting PATH for either tool. const selected = { diff --git a/src/pcap/PcapNativeBound.test.ts b/src/pcap/PcapNativeBound.test.ts index 5e5572cd64..a6629a0f7c 100644 --- a/src/pcap/PcapNativeBound.test.ts +++ b/src/pcap/PcapNativeBound.test.ts @@ -25,34 +25,13 @@ const resources = { readLimits: (limits: LinuxResourceLimits) => Promise.resolve(limits), } as ArtifactAnalysisResources; -const withPlatform = async ( - platform: NodeJS.Platform, - run: () => Promise, -) => { - const previousPlatform = process.platform; - Object.defineProperty(process, "platform", { - configurable: true, - value: platform, - }); - try { - await run(); - } finally { - Object.defineProperty(process, "platform", { - configurable: true, - value: previousPlatform, - }); - } -}; - it("uses the shared 1 GiB ceiling for the Windows job memory limit", async () => { - await withPlatform("win32", async () => { - await expect( - preparePcapNativeBound({}, resources, async () => probeResult("")), - ).resolves.toMatchObject({ - nativeBound: { - memoryLimitBytes: BOUNDED_PRODUCER_LIMITS.address_space_bytes, - }, - }); + await expect( + preparePcapNativeBound("win32", {}, resources, async () => probeResult("")), + ).resolves.toMatchObject({ + nativeBound: { + memoryLimitBytes: BOUNDED_PRODUCER_LIMITS.address_space_bytes, + }, }); }); @@ -63,19 +42,18 @@ it("accepts selected limiter symlinks with different and whitespace-bearing base for (const name of ["bounded-capture", " limiter", " limiter "]) { const selected = join(root, name); await symlink(executable, selected); - await withPlatform("linux", async () => { - const bound = await preparePcapNativeBound( - { REA_TSHARK_PRLIMIT_COMMAND: selected }, - resources, - async (selection, args) => { - expect(selection.invocationPath).toBe(selected); - return probeResult( - args[0] === "--help" ? help : `${name} from util-linux 2.38.1\n`, - ); - }, - ); - expect(bound.nativeBound.limiter?.command.invocationPath).toBe(selected); - }); + const bound = await preparePcapNativeBound( + "linux", + { REA_TSHARK_PRLIMIT_COMMAND: selected }, + resources, + async (selection, args) => { + expect(selection.invocationPath).toBe(selected); + return probeResult( + args[0] === "--help" ? help : `${name} from util-linux 2.38.1\n`, + ); + }, + ); + expect(bound.nativeBound.limiter?.command.invocationPath).toBe(selected); } }); @@ -92,25 +70,24 @@ it("attributes malformed limiter version output while retaining producer evidenc diagnostics: { invalid_utf8_streams: ["stdout"] }, }, ); - await withPlatform("linux", async () => { - await expect( - preparePcapNativeBound( - { REA_TSHARK_PRLIMIT_COMMAND: selected }, - resources, - async () => { - throw failure; - }, - ), - ).rejects.toMatchObject({ - _tag: "AnalysisCapabilityUnavailableError", - capturedOutput, - diagnostics: { - invalid_utf8_streams: ["stdout"], - configuration_key: "REA_TSHARK_PRLIMIT_COMMAND", - configured: selected, + await expect( + preparePcapNativeBound( + "linux", + { REA_TSHARK_PRLIMIT_COMMAND: selected }, + resources, + async () => { + throw failure; }, - userMessage: expect.stringContaining("unreadable version output"), - }); + ), + ).rejects.toMatchObject({ + _tag: "AnalysisCapabilityUnavailableError", + capturedOutput, + diagnostics: { + invalid_utf8_streams: ["stdout"], + configuration_key: "REA_TSHARK_PRLIMIT_COMMAND", + configured: selected, + }, + userMessage: expect.stringContaining("unreadable version output"), }); }); @@ -124,20 +101,19 @@ it("pins capture ceilings through the shared prlimit prefix and keeps 300 CPU se file_bytes: BOUNDED_PRODUCER_LIMITS.file_bytes, cpu_seconds: 300, }; - await withPlatform("linux", async () => { - const prepared = await preparePcapNativeBound( - { REA_TSHARK_PRLIMIT_COMMAND: limiter }, - resources, - async (_selection, args) => - probeResult( - args[0] === "--help" ? help : "prlimit from util-linux 2.38.1\n", - ), - ); - expect(prepared.nativeBound.limiter?.arguments).toEqual( - prlimitCeilingArguments(limits), - ); - expect(prepared.limitations[0]).toContain(String(limits.cpu_seconds)); - }); + const prepared = await preparePcapNativeBound( + "linux", + { REA_TSHARK_PRLIMIT_COMMAND: limiter }, + resources, + async (_selection, args) => + probeResult( + args[0] === "--help" ? help : "prlimit from util-linux 2.38.1\n", + ), + ); + expect(prepared.nativeBound.limiter?.arguments).toEqual( + prlimitCeilingArguments(limits), + ); + expect(prepared.limitations[0]).toContain(String(limits.cpu_seconds)); }); it("rejects a directory or a command that does not identify as util-linux prlimit", async () => { @@ -145,59 +121,57 @@ it("rejects a directory or a command that does not identify as util-linux prlimi const executable = join(root, "not-prlimit"); await writeFile(executable, "#!/bin/sh\nexit 0\n"); await chmod(executable, 0o700); - await withPlatform("linux", async () => { - for (const [path, output] of [ - [root, "prlimit from util-linux 2.38"], - [executable, ""], - ] as const) { - await expect( - preparePcapNativeBound( - { REA_TSHARK_PRLIMIT_COMMAND: path }, - resources, - async () => probeResult(output), - ), - ).rejects.toMatchObject({ - _tag: "AnalysisCapabilityUnavailableError", - // The limiter owns the repair; readiness keeps it over Wireshark advice. - remediationAction: expect.stringMatching( - /REA_TSHARK_PRLIMIT_COMMAND.*\/usr\/bin\/prlimit.*absolute.*executable.*util-linux prlimit/iu, - ) as unknown, - diagnostics: { - configuration_key: "REA_TSHARK_PRLIMIT_COMMAND", - configured: path, - }, - }); - } - }); + for (const [path, output] of [ + [root, "prlimit from util-linux 2.38"], + [executable, ""], + ] as const) { + await expect( + preparePcapNativeBound( + "linux", + { REA_TSHARK_PRLIMIT_COMMAND: path }, + resources, + async () => probeResult(output), + ), + ).rejects.toMatchObject({ + _tag: "AnalysisCapabilityUnavailableError", + // The limiter owns the repair; readiness keeps it over Wireshark advice. + remediationAction: expect.stringMatching( + /REA_TSHARK_PRLIMIT_COMMAND.*\/usr\/bin\/prlimit.*absolute.*executable.*util-linux prlimit/iu, + ) as unknown, + diagnostics: { + configuration_key: "REA_TSHARK_PRLIMIT_COMMAND", + configured: path, + }, + }); + } }); it("preserves cancellation and selected-command identity failures during the probe", async () => { const root = await createTestTempDirectory("rea-prlimit-probe-failure-"); const limiter = join(root, "prlimit"); await writeFile(limiter, "#!/bin/sh\nexit 0\n", { mode: 0o700 }); - await withPlatform("linux", async () => { - for (const failure of [ - new AnalysisCancelledError("inspect_pcap_capture"), - new AnalysisArtifactChangedError( - "inspect_pcap_capture", - limiter, - "changed", + for (const failure of [ + new AnalysisCancelledError("inspect_pcap_capture"), + new AnalysisArtifactChangedError( + "inspect_pcap_capture", + limiter, + "changed", + ), + new AnalysisOutputError("inspect_pcap_capture", "invalid output", { + cleanup: { reason: "stop failed", resources: ["owned-process"] }, + }), + ]) { + await expect( + preparePcapNativeBound( + "linux", + { REA_TSHARK_PRLIMIT_COMMAND: limiter }, + resources, + async () => { + throw failure; + }, ), - new AnalysisOutputError("inspect_pcap_capture", "invalid output", { - cleanup: { reason: "stop failed", resources: ["owned-process"] }, - }), - ]) { - await expect( - preparePcapNativeBound( - { REA_TSHARK_PRLIMIT_COMMAND: limiter }, - resources, - async () => { - throw failure; - }, - ), - ).rejects.toBe(failure); - } - }); + ).rejects.toBe(failure); + } }); it("rejects another util-linux command and retains the rejected help output", async () => { @@ -208,20 +182,19 @@ it("rejects another util-linux command and retains the rejected help output", as " --output columns", "help diagnostic", ).capturedOutput; - await withPlatform("linux", async () => { - await expect( - preparePcapNativeBound( - { REA_TSHARK_PRLIMIT_COMMAND: selected }, - resources, - async (_selection, args) => - args[0] === "--help" - ? { stdout: capturedOutput.stdout, capturedOutput } - : probeResult("lsblk from util-linux 2.38\n"), - ), - ).rejects.toMatchObject({ - _tag: "AnalysisCapabilityUnavailableError", - capturedOutput, - }); + await expect( + preparePcapNativeBound( + "linux", + { REA_TSHARK_PRLIMIT_COMMAND: selected }, + resources, + async (_selection, args) => + args[0] === "--help" + ? { stdout: capturedOutput.stdout, capturedOutput } + : probeResult("lsblk from util-linux 2.38\n"), + ), + ).rejects.toMatchObject({ + _tag: "AnalysisCapabilityUnavailableError", + capturedOutput, }); }); @@ -230,16 +203,15 @@ it("retains rejected version output", async () => { const selected = join(root, "prlimit"); await writeFile(selected, "#!/bin/sh\nexit 0\n", { mode: 0o700 }); const output = probeResult("unexpected banner", "diagnostic"); - await withPlatform("linux", async () => { - await expect( - preparePcapNativeBound( - { REA_TSHARK_PRLIMIT_COMMAND: selected }, - resources, - async () => output, - ), - ).rejects.toMatchObject({ - _tag: "AnalysisCapabilityUnavailableError", - capturedOutput: output.capturedOutput, - }); + await expect( + preparePcapNativeBound( + "linux", + { REA_TSHARK_PRLIMIT_COMMAND: selected }, + resources, + async () => output, + ), + ).rejects.toMatchObject({ + _tag: "AnalysisCapabilityUnavailableError", + capturedOutput: output.capturedOutput, }); }); diff --git a/src/pcap/PcapNativeBound.ts b/src/pcap/PcapNativeBound.ts index d861985b27..04e8f77054 100644 --- a/src/pcap/PcapNativeBound.ts +++ b/src/pcap/PcapNativeBound.ts @@ -70,6 +70,7 @@ const PCAP_CPU_SECONDS = 300; /** Own native capture admission and the exact enforced resource profile. */ export const preparePcapNativeBound = async ( + platform: NodeJS.Platform, environment: Readonly>, resources: ArtifactAnalysisResources, probe: ( @@ -87,7 +88,7 @@ export const preparePcapNativeBound = async ( nativeBound: NonNullable[0]["nativeBound"]>; limitations: readonly string[]; }> => { - if (process.platform === "win32") { + if (platform === "win32") { return { nativeBound: { memoryLimitBytes: BOUNDED_PRODUCER_LIMITS.address_space_bytes, @@ -97,7 +98,7 @@ export const preparePcapNativeBound = async ( ], }; } - if (!pcapCaptureHostSupported(process.platform)) { + if (!pcapCaptureHostSupported(platform)) { const reason = PCAP_CAPTURE_UNSUPPORTED_HOST_REASON; throw new AnalysisCapabilityUnavailableError("pcap", operation, reason, { userMessage: reason, diff --git a/src/pcap/PcapProvider.ts b/src/pcap/PcapProvider.ts index 066d9583d5..00c9e78956 100644 --- a/src/pcap/PcapProvider.ts +++ b/src/pcap/PcapProvider.ts @@ -203,6 +203,8 @@ export interface PcapProviderOptions { readonly environment?: Readonly>; readonly launcher?: PcapCommandLauncher; readonly artifactReader?: typeof readStableArtifact; + /** The host the packet tools run on; defaults to the running host. */ + readonly platform?: NodeJS.Platform; } /** @@ -271,6 +273,7 @@ export class PcapProvider { string, ArtifactCommandPath & { readonly identity: WiresharkExecutableIdentity } >(); + private readonly platform: NodeJS.Platform; private readonly snapshots = new Set(); private readonly snapshotFailures = new Map< PcapSnapshot, @@ -282,9 +285,10 @@ export class PcapProvider { >(); constructor(options: PcapProviderOptions = {}) { + this.platform = options.platform ?? HOST_PLATFORM.platform; this.environment = snapshotEnvironment( options.environment ?? process.env, - HOST_PLATFORM.platform, + this.platform, ); this.launcher = options.launcher; this.#resources = createArtifactAnalysisResources( @@ -359,6 +363,7 @@ export class PcapProvider { } output = await runPcapCommand({ operation, + platform: this.platform, redactHttpTransportCredentials: stage === "tshark" && operation === "inspect_pcap_capture", command: selected?.invocationPath ?? command, @@ -468,6 +473,7 @@ export class PcapProvider { signal?: AbortSignal, ): Promise { const prepared = await preparePcapNativeBound( + this.platform, this.environment, this.#resources, async (selected, arguments_) => { @@ -491,7 +497,7 @@ export class PcapProvider { } private async client(operation: PcapOperation, signal?: AbortSignal) { - const selection = resolvePcapTools(this.environment); + const selection = resolvePcapTools(this.environment, this.platform); this.wiresharkIdentities.clear(); for (const [name, selected] of [ ["tshark", selection.tshark], @@ -602,7 +608,7 @@ export class PcapProvider { ): Promise { try { const { client } = await this.client("inspect_pcap_client", signal); - if (!pcapCaptureHostSupported(process.platform)) + if (!pcapCaptureHostSupported(this.platform)) return { status: "unavailable", code: "unsupported_host", diff --git a/src/rizin/RizinDebugSessionManager.ts b/src/rizin/RizinDebugSessionManager.ts index a9b839c376..c9e58ee09d 100644 --- a/src/rizin/RizinDebugSessionManager.ts +++ b/src/rizin/RizinDebugSessionManager.ts @@ -72,6 +72,7 @@ import { OwnedDebuggerSessionRegistry } from "../process/OwnedDebuggerSessionReg import { absoluteCallerPath } from "../filesystem/callerPath.js"; import { AbortedWait, waitForAbortable } from "../process/AbortablePromise.js"; import { utf8HeadExcerpt } from "../domain/utf8HeadExcerpt.js"; +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; const CLEANUP_COMMAND_TIMEOUT_MS = 1_000; const STARTUP_TIMEOUT_MS = 30_000; @@ -312,7 +313,7 @@ export class RizinDebugSessionManager { this.#maxSessions = limits.maxSessions; this.#maxPendingCommands = limits.maxPendingCommands; this.#launchCommandOutput = limits.maxCommandOutputBytes; - this.#platform = options.platform ?? process.platform; + this.#platform = options.platform ?? HOST_PLATFORM.platform; const stopProcess = options.stopProcess ?? stopOwnedDebuggerProcess; const platform = this.#platform; this.#sessions = new OwnedDebuggerSessionRegistry({ diff --git a/src/server/createServer.ts b/src/server/createServer.ts index f2333d03b4..572c6720e7 100644 --- a/src/server/createServer.ts +++ b/src/server/createServer.ts @@ -2,7 +2,7 @@ import { createCapabilityServices, type CapabilityServiceOptions, } from "../composition/capabilityServices.js"; -import { HOST_PLATFORM } from "../platform/HostPlatform.js"; +import { HOST_PLATFORM, type HostPlatform } from "../platform/HostPlatform.js"; import { registerToolFamilies } from "../contracts/toolFamilyIds.js"; import { SCOPED_NO_TARGET_RECOVERY } from "./recoveryInstructions.js"; import { AnalysisSettings } from "../application/AnalysisSettings.js"; @@ -82,6 +82,12 @@ export interface CreateServerOptions extends CapabilityServiceOptions { readonly providerEnvironment?: Readonly; readonly logger?: Logger; readonly availabilityPolicy?: () => AvailabilityPolicy; + /** + * The host the server's integrations run on: it decides environment-name + * rules, host-restricted availability and execution checks. Defaults to the + * running host; tests select another host here. + */ + readonly host?: HostPlatform; } const createMcpServer = ( @@ -133,9 +139,10 @@ export const createServer = ( ): EvidenceMcpServer => { const session = source.kind === "session" ? source.session : undefined; const analysis = source.kind === "session" ? source.session : source.analysis; + const host = options.host ?? HOST_PLATFORM; const environment = snapshotEnvironment( options.environment ?? process.env, - HOST_PLATFORM.platform, + host.platform, ); const analysisSettings = options.analysisSettings ?? new AnalysisSettings(environment); @@ -150,6 +157,7 @@ export const createServer = ( const providerEnvironment = captureProviderEnvironment( options.providerEnvironment, environment, + host.platform, ); const baseDelivery = selectToolResultDelivery(environment, options.delivery); const delivery = @@ -163,8 +171,8 @@ export const createServer = ( providerEnvironment, settings: analysisSettings.read, options, - platform: process.platform, - arch: process.arch, + platform: host.platform, + arch: host.architecture, }); const { evmInterface, @@ -258,6 +266,7 @@ export const createServer = ( optionalProviderLoadFailures: options.optionalProviderLoadFailures, }, + host.platform, ); return { policy: (): AvailabilityPolicy => { @@ -633,6 +642,7 @@ export const createServer = ( if (session === undefined) return; registerSessionTools(server, session, toolLogger, { environment, + platform: host.platform, artifactResources, ...(availability === undefined ? {} diff --git a/src/server/providerEnvironment.ts b/src/server/providerEnvironment.ts index e8444c39f2..c393745128 100644 --- a/src/server/providerEnvironment.ts +++ b/src/server/providerEnvironment.ts @@ -1,12 +1,9 @@ import { snapshotEnvironment } from "../process/snapshotEnvironment.js"; -import { HOST_PLATFORM } from "../platform/HostPlatform.js"; /** Capture the selected provider environment at server construction time. */ export const captureProviderEnvironment = ( providerEnvironment: Readonly | undefined, serverEnvironment: Readonly, + platform: NodeJS.Platform, ): Readonly => - snapshotEnvironment( - providerEnvironment ?? serverEnvironment, - HOST_PLATFORM.platform, - ); + snapshotEnvironment(providerEnvironment ?? serverEnvironment, platform); diff --git a/src/server/registerSessionTools.ts b/src/server/registerSessionTools.ts index 01070b5071..5022a94ee8 100644 --- a/src/server/registerSessionTools.ts +++ b/src/server/registerSessionTools.ts @@ -93,6 +93,7 @@ interface ProcessToolRegistration { >; readonly resourceScope: ProcessCaptureResourceScope; readonly environment: Readonly; + readonly platform: NodeJS.Platform; } const registerProcessTools = ({ @@ -102,6 +103,7 @@ const registerProcessTools = ({ captureContract, resourceScope, environment, + platform, }: ProcessToolRegistration): void => { const admission = withAdmittedAnalysis({ kind: "session", session }); server.registerTool( @@ -123,7 +125,7 @@ const registerProcessTools = ({ prepareProcessScenarioPlan( input, environment, - process.platform, + platform, context.mcpReq.signal, ), ); @@ -134,7 +136,7 @@ const registerProcessTools = ({ ); const evidence = createProcessScenarioPlanEvidence( prepared.value, - process.platform, + platform, ); const recorded = session.recordEvidence(evidence); if (!recorded.ok) @@ -155,7 +157,7 @@ const registerProcessTools = ({ captureProcessScenario( input, context.mcpReq.signal, - process.platform, + platform, environment, undefined, undefined, @@ -263,6 +265,8 @@ export interface SessionToolOptions extends Partial; + /** The host process capture plans for and runs on. */ + readonly platform: NodeJS.Platform; readonly startedAt?: string; readonly availabilityPolicy?: () => AvailabilityPolicy; } @@ -395,6 +399,7 @@ export const registerSessionTools = ( availabilityPolicy: sessionAvailabilityPolicy( options.availabilityPolicy, {}, + options.platform, ), androidAnalysisAvailability: options.androidAnalysisAvailability ?? missingAndroidAvailability, @@ -439,6 +444,7 @@ export const registerSessionTools = ( captureContract, resourceScope: processResources, environment: options.environment, + platform: options.platform, }); const closeServer = server.close.bind(server); server.close = async () => { diff --git a/src/server/sessionAvailabilityPolicy.ts b/src/server/sessionAvailabilityPolicy.ts index efbb883744..3f6eec949e 100644 --- a/src/server/sessionAvailabilityPolicy.ts +++ b/src/server/sessionAvailabilityPolicy.ts @@ -3,7 +3,6 @@ import { HOST_RESTRICTED_FEATURES, type HostRestrictedFeature, } from "../contracts/toolAvailability.js"; -import { platform } from "node:process"; import type { CapabilityAvailabilityFacts } from "../application/CapabilityAvailability.js"; /** Either the caller or the observed host can mark an integration unsupported. */ @@ -22,6 +21,8 @@ const combineHostUnsupported = ( export const sessionAvailabilityPolicy = ( configured: (() => AvailabilityPolicy) | undefined, defaults: CapabilityAvailabilityFacts, + /** The host process capture plans for and runs on. */ + platform: NodeJS.Platform, ): (() => AvailabilityPolicy) => { const policy = configured ?? diff --git a/src/serverIdentity.ts b/src/serverIdentity.ts index d54e9c8913..331d4d1055 100644 --- a/src/serverIdentity.ts +++ b/src/serverIdentity.ts @@ -1,5 +1,7 @@ import { statSync } from "node:fs"; import { dirname, basename, resolve } from "node:path"; + +import { HOST_PLATFORM } from "./platform/HostPlatform.js"; import { fileURLToPath } from "node:url"; import { @@ -40,7 +42,7 @@ const compareServerPaths = ( // lexically, while Bun follows native traversal through a symlink before `..`. const script = normalizeEntrypointPath(expected, runtime) ?? expected; if (script === observed) return "aligned"; - if (process.platform === "win32") return "mismatch"; + if (HOST_PLATFORM.platform === "win32") return "mismatch"; try { const selected = statSync(script, { bigint: true }); const running = statSync(observed, { bigint: true }); diff --git a/src/signals/SigrokRecordingProvider.ts b/src/signals/SigrokRecordingProvider.ts index 1818a4ed56..9d0fb79213 100644 --- a/src/signals/SigrokRecordingProvider.ts +++ b/src/signals/SigrokRecordingProvider.ts @@ -10,6 +10,7 @@ import { } from "../domain/producerResourceLimits.js"; import { SIGROK_PROVIDER_IDENTITY } from "./SigrokProviderIdentity.js"; import { snapshotEnvironment } from "../process/snapshotEnvironment.js"; +import { HOST_PLATFORM } from "../platform/HostPlatform.js"; import { type InspectSignalDecodersInput, signalDecodersSchema, @@ -114,7 +115,7 @@ export class SigrokRecordingProvider implements SignalRecordingPort { readonly launcher?: Launcher, readonly createRuntime: () => Promise = () => PrivateRuntimeRoot.create({ prefix: "rea-sigrok-" }), - readonly platform: NodeJS.Platform = process.platform, + readonly platform: NodeJS.Platform = HOST_PLATFORM.platform, readonly readArtifact: typeof readStableArtifact = readStableArtifact, readonly readLimits: typeof readLinuxResourceLimits = readLinuxResourceLimits, ) { diff --git a/src/wasm/WabtArtifactProvider.ts b/src/wasm/WabtArtifactProvider.ts index 6c59e01844..c29d586869 100644 --- a/src/wasm/WabtArtifactProvider.ts +++ b/src/wasm/WabtArtifactProvider.ts @@ -270,7 +270,7 @@ export class WabtArtifactProvider implements WasmArtifactPort { const selection = await selectArtifactCommandPath( appendCallerPath( directory, - `${tool}${process.platform === "win32" ? ".exe" : ""}`, + `${tool}${HOST_PLATFORM.platform === "win32" ? ".exe" : ""}`, ), options?.signal, ); diff --git a/tests/boundary/browser/historicalCaptureDecoder.test.ts b/tests/boundary/browser/historicalCaptureDecoder.test.ts index c96b5694de..72a18bca29 100644 --- a/tests/boundary/browser/historicalCaptureDecoder.test.ts +++ b/tests/boundary/browser/historicalCaptureDecoder.test.ts @@ -160,16 +160,11 @@ fs.writeFileSync(request.reply_path, ${JSON.stringify(JSON.stringify({ ok: true, const command = MitmproxyCaptureAdapter.prototype.command; vi.spyOn(MitmproxyCaptureAdapter.prototype, "command").mockImplementation( function (this: MitmproxyCaptureAdapter, request, runtime) { - const platform = Object.getOwnPropertyDescriptor(process, "platform")!; - Object.defineProperty(process, "platform", { - ...platform, - value: "linux", - }); - try { - return command.call(this, request, runtime); - } finally { - Object.defineProperty(process, "platform", platform); - } + return command.call( + new MitmproxyCaptureAdapter(this.environment, "linux"), + request, + runtime, + ); }, ); onTestFinished(() => { diff --git a/tests/boundary/evm/evmCleanupRetry.test.ts b/tests/boundary/evm/evmCleanupRetry.test.ts index dd031fa0d9..e9ea434ebc 100644 --- a/tests/boundary/evm/evmCleanupRetry.test.ts +++ b/tests/boundary/evm/evmCleanupRetry.test.ts @@ -51,6 +51,7 @@ vi.mock("node:fs/promises", async (importOriginal) => { }); import { EvmoleInterfaceProvider } from "../../../src/evm/EvmoleInterfaceProvider.js"; +import { SIMULATED_LINUX_X64 } from "../../fixtures/simulatedHost.js"; import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js"; import { cleanupOwnedProcessGroup } from "../../../src/process/ProcessOwnership.js"; import { PrivateRuntimeRoot } from "../../../src/process/PrivateRuntimeRoot.js"; @@ -62,10 +63,6 @@ import { AnalysisCancelledError } from "../../../src/domain/analysisErrorCore.js it.each(["pre-aborted", "admission", "close"] as const)( "preserves opaque caller reasons through service cancellation at %s", async (stage) => { - const platform = Object.getOwnPropertyDescriptor(process, "platform"); - const arch = Object.getOwnPropertyDescriptor(process, "arch"); - Object.defineProperty(process, "platform", { ...platform, value: "linux" }); - Object.defineProperty(process, "arch", { ...arch, value: "x64" }); const workspace = await mkdtemp(join(tmpdir(), "rea-evm-artifact-cancel-")); const input = join(workspace, "selected.hex"); await writeFile(input, "0x60006000f3\n"); @@ -76,6 +73,7 @@ it.each(["pre-aborted", "admission", "close"] as const)( { REA_EVM_PRLIMIT_COMMAND: process.execPath }, undefined, createRuntime, + SIMULATED_LINUX_X64, ); try { for (const reason of [ @@ -115,9 +113,6 @@ it.each(["pre-aborted", "admission", "close"] as const)( closeState.onLimits = undefined; await provider.close(); await rm(workspace, { recursive: true, force: true }); - if (platform !== undefined) - Object.defineProperty(process, "platform", platform); - if (arch !== undefined) Object.defineProperty(process, "arch", arch); } }, ); @@ -130,10 +125,6 @@ it.each([ ] as const)( "updates a returned cleanup error after later root release: %s", async (scenario) => { - const platform = Object.getOwnPropertyDescriptor(process, "platform"); - const arch = Object.getOwnPropertyDescriptor(process, "arch"); - Object.defineProperty(process, "platform", { ...platform, value: "linux" }); - Object.defineProperty(process, "arch", { ...arch, value: "x64" }); const workspace = await mkdtemp(join(tmpdir(), "rea-evm-cleanup-retry-")); const input = join(workspace, "selected.hex"); await writeFile(input, "0x60006000f3\n"); @@ -144,11 +135,6 @@ it.each([ const provider = new EvmoleInterfaceProvider( { REA_EVM_PRLIMIT_COMMAND: process.execPath }, async (spawn) => { - // Emulate only Linux admission and limits; restore Darwin before the - // owned process captures and validates its real host identity. - if (platform !== undefined) - Object.defineProperty(process, "platform", platform); - if (arch !== undefined) Object.defineProperty(process, "arch", arch); const requestPath = spawn.arguments.at(-1); if (requestPath === undefined) throw new Error("Request path missing"); const request = JSON.parse(await readFile(requestPath, "utf8")) as { @@ -209,6 +195,7 @@ it.each([ }, }; }, + SIMULATED_LINUX_X64, ); try { @@ -263,26 +250,24 @@ it.each([ // Preserve the assertion's original failure; the workspace cleanup follows. } await rm(workspace, { recursive: true, force: true }); - if (platform !== undefined) - Object.defineProperty(process, "platform", platform); - if (arch !== undefined) Object.defineProperty(process, "arch", arch); } }, ); it("keeps descriptor cleanup in close aggregates until the exact file lease releases", async () => { - const platform = Object.getOwnPropertyDescriptor(process, "platform"); - const arch = Object.getOwnPropertyDescriptor(process, "arch"); - Object.defineProperty(process, "platform", { ...platform, value: "linux" }); - Object.defineProperty(process, "arch", { ...arch, value: "x64" }); const workspace = await mkdtemp(join(tmpdir(), "rea-evm-descriptor-retry-")); const input = join(workspace, "selected.hex"); await writeFile(input, "0x60006000f3\n"); closeState.path = input; closeState.failures = 2; - const provider = new EvmoleInterfaceProvider({ - REA_EVM_PRLIMIT_COMMAND: process.execPath, - }); + const provider = new EvmoleInterfaceProvider( + { + REA_EVM_PRLIMIT_COMMAND: process.execPath, + }, + undefined, + undefined, + SIMULATED_LINUX_X64, + ); try { const result = await provider.inspect({ path: input, encoding: "hex" }); if (result.ok) throw new Error("Expected an artifact descriptor failure"); @@ -319,17 +304,10 @@ it("keeps descriptor cleanup in close aggregates until the exact file lease rele // Preserve the assertion's original failure while releasing test files. } await rm(workspace, { recursive: true, force: true }); - if (platform !== undefined) - Object.defineProperty(process, "platform", platform); - if (arch !== undefined) Object.defineProperty(process, "arch", arch); } }); it("keeps a mixed root and reply-descriptor aggregate pending until both owners release", async () => { - const platform = Object.getOwnPropertyDescriptor(process, "platform"); - const arch = Object.getOwnPropertyDescriptor(process, "arch"); - Object.defineProperty(process, "platform", { ...platform, value: "linux" }); - Object.defineProperty(process, "arch", { ...arch, value: "x64" }); const workspace = await mkdtemp(join(tmpdir(), "rea-evm-mixed-owners-")); const input = join(workspace, "selected.hex"); await writeFile(input, "0x60006000f3\n"); @@ -350,9 +328,6 @@ it("keeps a mixed root and reply-descriptor aggregate pending until both owners closeState.path = replyPath; closeState.failures = 2; await writeFile(replyPath, "malformed worker reply"); - if (platform !== undefined) - Object.defineProperty(process, "platform", platform); - if (arch !== undefined) Object.defineProperty(process, "arch", arch); return spawnOwnedProviderProcess({ ...spawn, command: process.execPath, @@ -375,6 +350,7 @@ it("keeps a mixed root and reply-descriptor aggregate pending until both owners }, }; }, + SIMULATED_LINUX_X64, ); try { const result = await provider.inspect({ path: input, encoding: "hex" }); @@ -418,17 +394,10 @@ it("keeps a mixed root and reply-descriptor aggregate pending until both owners // Preserve the assertion's original failure while releasing test files. } await rm(workspace, { recursive: true, force: true }); - if (platform !== undefined) - Object.defineProperty(process, "platform", platform); - if (arch !== undefined) Object.defineProperty(process, "arch", arch); } }); it("releases a retained process independently while a root cleanup retry remains pending", async () => { - const platform = Object.getOwnPropertyDescriptor(process, "platform"); - const arch = Object.getOwnPropertyDescriptor(process, "arch"); - Object.defineProperty(process, "platform", { ...platform, value: "linux" }); - Object.defineProperty(process, "arch", { ...arch, value: "x64" }); const workspace = await mkdtemp( join(tmpdir(), "rea-evm-process-root-retry-"), ); @@ -460,9 +429,6 @@ it("releases a retained process independently while a root cleanup retry remains raw: { functions: [] }, }), ); - if (platform !== undefined) - Object.defineProperty(process, "platform", platform); - if (arch !== undefined) Object.defineProperty(process, "arch", arch); const launched = await spawnOwnedProviderProcess({ ...spawn, command: process.execPath, @@ -497,6 +463,7 @@ it("releases a retained process independently while a root cleanup retry remains }, }; }, + SIMULATED_LINUX_X64, ); try { const result = await provider.inspect({ path: input, encoding: "hex" }); @@ -540,17 +507,10 @@ it("releases a retained process independently while a root cleanup retry remains // Preserve the assertion's original failure while releasing test files. } await rm(workspace, { recursive: true, force: true }); - if (platform !== undefined) - Object.defineProperty(process, "platform", platform); - if (arch !== undefined) Object.defineProperty(process, "arch", arch); } }); it("preserves an active cancellation through denied owned-group cleanup and later retry", async () => { - const platform = Object.getOwnPropertyDescriptor(process, "platform"); - const arch = Object.getOwnPropertyDescriptor(process, "arch"); - Object.defineProperty(process, "platform", { ...platform, value: "linux" }); - Object.defineProperty(process, "arch", { ...arch, value: "x64" }); const workspace = await mkdtemp(join(tmpdir(), "rea-evm-cancel-process-")); const input = join(workspace, "selected.hex"); await writeFile(input, "0x60006000f3\n"); @@ -563,9 +523,6 @@ it("preserves an active cancellation through denied owned-group cleanup and late const provider = new EvmoleInterfaceProvider( { REA_EVM_PRLIMIT_COMMAND: process.execPath }, async (spawn) => { - if (platform !== undefined) - Object.defineProperty(process, "platform", platform); - if (arch !== undefined) Object.defineProperty(process, "arch", arch); const launched = await spawnOwnedProviderProcess({ ...spawn, command: process.execPath, @@ -607,6 +564,7 @@ it("preserves an active cancellation through denied owned-group cleanup and late }, }; }, + SIMULATED_LINUX_X64, ); try { const result = await provider.inspect( @@ -649,9 +607,6 @@ it("preserves an active cancellation through denied owned-group cleanup and late // Preserve the assertion's original failure while releasing test files. } await rm(workspace, { recursive: true, force: true }); - if (platform !== undefined) - Object.defineProperty(process, "platform", platform); - if (arch !== undefined) Object.defineProperty(process, "arch", arch); } }); @@ -667,10 +622,6 @@ it.each([ ] as const)( "retains validated reply ownership through finalization: %s", async (scenario) => { - const platform = Object.getOwnPropertyDescriptor(process, "platform"); - const arch = Object.getOwnPropertyDescriptor(process, "arch"); - Object.defineProperty(process, "platform", { ...platform, value: "linux" }); - Object.defineProperty(process, "arch", { ...arch, value: "x64" }); const workspace = await mkdtemp( join(tmpdir(), "rea-evm-reply-finalization-"), ); @@ -724,9 +675,6 @@ it.each([ replyPath, scenario === "malformed-cancel" ? "malformed" : JSON.stringify(reply), ); - if (platform !== undefined) - Object.defineProperty(process, "platform", platform); - if (arch !== undefined) Object.defineProperty(process, "arch", arch); // Controlled worker output, with a real owned process and actual reply FD. return spawnOwnedProviderProcess({ ...spawn, @@ -734,6 +682,8 @@ it.each([ arguments: ["-e", ""], }); }, + undefined, + SIMULATED_LINUX_X64, ); try { const result = await provider.inspect( @@ -807,9 +757,6 @@ it.each([ closeState.readFailure = undefined; await provider.close(); await rm(workspace, { recursive: true, force: true }); - if (platform !== undefined) - Object.defineProperty(process, "platform", platform); - if (arch !== undefined) Object.defineProperty(process, "arch", arch); } }, ); @@ -817,10 +764,6 @@ it.each([ it.each(["physical-read", "completed-late-cancel"] as const)( "retains only completed caller carrier identity: %s", async (scenario) => { - const platform = Object.getOwnPropertyDescriptor(process, "platform"); - const arch = Object.getOwnPropertyDescriptor(process, "arch"); - Object.defineProperty(process, "platform", { ...platform, value: "linux" }); - Object.defineProperty(process, "arch", { ...arch, value: "x64" }); const workspace = await mkdtemp( join(tmpdir(), "rea-evm-carrier-finalization-"), ); @@ -843,6 +786,7 @@ it.each(["physical-read", "completed-late-cancel"] as const)( { REA_EVM_PRLIMIT_COMMAND: process.execPath }, undefined, createRuntime, + SIMULATED_LINUX_X64, ); try { const result = await provider.inspect( @@ -882,9 +826,6 @@ it.each(["physical-read", "completed-late-cancel"] as const)( closeState.readFailure = undefined; await provider.close(); await rm(workspace, { recursive: true, force: true }); - if (platform !== undefined) - Object.defineProperty(process, "platform", platform); - if (arch !== undefined) Object.defineProperty(process, "arch", arch); } }, ); @@ -900,10 +841,6 @@ it.each([ ] as const)( "preserves exact reserved-exit marker receipt and cleanup: %s", async (scenario) => { - const platform = Object.getOwnPropertyDescriptor(process, "platform"); - const arch = Object.getOwnPropertyDescriptor(process, "arch"); - Object.defineProperty(process, "platform", { ...platform, value: "linux" }); - Object.defineProperty(process, "arch", { ...arch, value: "x64" }); const workspace = await mkdtemp(join(tmpdir(), "rea-evm-marker-receipt-")); const input = join(workspace, "selected.hex"); await writeFile(input, "0x60006000f3\n"); @@ -929,9 +866,6 @@ it.each([ new Error("physical marker EIO"), { code: "EIO" }, ); - if (platform !== undefined) - Object.defineProperty(process, "platform", platform); - if (arch !== undefined) Object.defineProperty(process, "arch", arch); // The inert owned child authors a controlled marker; this does not run EVMole or target bytecode. const launched = await spawnOwnedProviderProcess({ ...spawn, @@ -960,6 +894,8 @@ it.each([ }, }; }, + undefined, + SIMULATED_LINUX_X64, ); try { const result = await provider.inspect({ path: input, encoding: "hex" }); @@ -1005,18 +941,11 @@ it.each([ closeState.readFailure = undefined; await provider.close(); await rm(workspace, { recursive: true, force: true }); - if (platform !== undefined) - Object.defineProperty(process, "platform", platform); - if (arch !== undefined) Object.defineProperty(process, "arch", arch); } }, ); it("keeps the selected limiter and child environment together while later inspections reconfigure", async () => { - const platform = Object.getOwnPropertyDescriptor(process, "platform"); - const arch = Object.getOwnPropertyDescriptor(process, "arch"); - Object.defineProperty(process, "platform", { ...platform, value: "linux" }); - Object.defineProperty(process, "arch", { ...arch, value: "x64" }); const workspace = await mkdtemp(join(tmpdir(), "rea-evm-environment-")); const input = join(workspace, "selected.hex"); const limiter = join(workspace, "selected-limiter"); @@ -1032,17 +961,22 @@ it("keeps the selected limiter and child environment together while later inspec environment.REA_EVM_PRLIMIT_COMMAND = "/missing-limiter"; environment.REA_ENV_MARKER = "changed-during-inspection"; }; - const provider = new EvmoleInterfaceProvider(environment, async (spawn) => { - expect(spawn.command).toBe(expectedLimiter); - return spawnOwnedProviderProcess({ - ...spawn, - command: process.execPath, - arguments: [ - "-e", - "process.stdout.write(process.env.REA_ENV_MARKER, () => { process.exitCode = 9; })", - ], - }); - }); + const provider = new EvmoleInterfaceProvider( + environment, + async (spawn) => { + expect(spawn.command).toBe(expectedLimiter); + return spawnOwnedProviderProcess({ + ...spawn, + command: process.execPath, + arguments: [ + "-e", + "process.stdout.write(process.env.REA_ENV_MARKER, () => { process.exitCode = 9; })", + ], + }); + }, + undefined, + SIMULATED_LINUX_X64, + ); try { for (const marker of ["first", "second"]) { if (marker === "second") { @@ -1058,8 +992,5 @@ it("keeps the selected limiter and child environment together while later inspec closeState.onLimits = undefined; await provider.close(); await rm(workspace, { recursive: true, force: true }); - if (platform !== undefined) - Object.defineProperty(process, "platform", platform); - if (arch !== undefined) Object.defineProperty(process, "arch", arch); } }); diff --git a/tests/boundary/filesystem/clientNativeConnectionAdmission.test.ts b/tests/boundary/filesystem/clientNativeConnectionAdmission.test.ts index 9dc675a8ab..622c9ac025 100644 --- a/tests/boundary/filesystem/clientNativeConnectionAdmission.test.ts +++ b/tests/boundary/filesystem/clientNativeConnectionAdmission.test.ts @@ -69,13 +69,13 @@ const PROGRAM = ` }; const resources = new ArtifactResourceScope(); try { - const conflict = await registerMcpClient(client, { command, args }, undefined, resources); + const conflict = await registerMcpClient(client, { command, args }, undefined, resources, process.platform); const refused = { ok: conflict.ok, typed: !conflict.ok && conflict.error instanceof ConfigurationError, targetExists: await exists(target), backupExists: await exists(target + '.rea.backup'), higherUnchanged: await readFile(higher, 'utf8') === source }; const harmless = JSON.stringify({ mcpServers: { rea: { ...row, operator: { preserve: true } } } }); await writeFile(higher, harmless); - const control = await registerMcpClient(client, { command, args }, undefined, resources); + const control = await registerMcpClient(client, { command, args }, undefined, resources, process.platform); console.log(JSON.stringify({ statuses, refused, control: { ok: control.ok, status: control.ok ? control.value.status : control.error.message, targetExists: await exists(target), higherUnchanged: await readFile(higher, 'utf8') === harmless } })); diff --git a/tests/boundary/filesystem/kiloClientLocation.test.ts b/tests/boundary/filesystem/kiloClientLocation.test.ts index 0bfc9efb22..5abf99e5f7 100644 --- a/tests/boundary/filesystem/kiloClientLocation.test.ts +++ b/tests/boundary/filesystem/kiloClientLocation.test.ts @@ -1,3 +1,4 @@ +import { registerMcpClientsOnHost } from "../../fixtures/mcpRegistration.js"; import { HOST_PLATFORM } from "../../../src/platform/HostPlatform.js"; import { mkdir, readFile, rm, writeFile } from "node:fs/promises"; import { join } from "node:path"; @@ -6,7 +7,6 @@ import { afterEach, beforeEach, expect, it, vi } from "vitest"; import { readEffectiveClientRegistrationConfiguration } from "../../../src/application/ClientConfigurationFiles.js"; import { currentClientRegistrationCommand } from "../../../src/application/ClientRegistrationIdentity.js"; import { readClientRegistrationStatuses } from "../../../src/application/ClientRegistrationStatus.js"; -import { registerMcpClients } from "../../../src/application/McpClientRegistration.js"; import { resolveMcpRegistrationClients } from "../../../src/application/McpRegistrationCatalog.js"; import { resolveSupportedClients, @@ -234,7 +234,7 @@ it("lets doctor and uninstall act on the Kilo layer rea mcp add wrote", async () resources, ); if (!selected.ok) throw selected.error; - const [outcome] = await registerMcpClients( + const [outcome] = await registerMcpClientsOnHost( selected.value, { command: command[0] ?? "", args: command.slice(1) }, undefined, @@ -394,7 +394,7 @@ it("registers Kilo through its table row in rea mcp add", async () => { expect(selected.value[0]?.inlineConfiguration?.origin).toBe( "KILO_CONFIG_CONTENT", ); - const [outcome] = await registerMcpClients( + const [outcome] = await registerMcpClientsOnHost( selected.value, { command: command[0] ?? "", args: command.slice(1) }, undefined, diff --git a/tests/boundary/filesystem/mcpAddClientLifecycle.test.ts b/tests/boundary/filesystem/mcpAddClientLifecycle.test.ts index d43dc010df..c429797f81 100644 --- a/tests/boundary/filesystem/mcpAddClientLifecycle.test.ts +++ b/tests/boundary/filesystem/mcpAddClientLifecycle.test.ts @@ -1,3 +1,4 @@ +import { registerMcpClientsOnHost } from "../../fixtures/mcpRegistration.js"; import { HOST_PLATFORM } from "../../../src/platform/HostPlatform.js"; import { chmod, @@ -27,7 +28,6 @@ import { readClientRegistrationInspections, readClientRegistrationStatuses, } from "../../../src/application/ClientRegistrationStatus.js"; -import { registerMcpClients } from "../../../src/application/McpClientRegistration.js"; import { resolveMcpRegistrationClients } from "../../../src/application/McpRegistrationCatalog.js"; import { clientConfigurationAligned, @@ -99,7 +99,7 @@ it.each([ // An older, still REA-owned launcher: the package runner form that // current setup migrates to the selected installation. const legacy = { command: "npx", args: ["-y", "rea-agents@1.0.0", "mcp"] }; - const [outcome] = await registerMcpClients( + const [outcome] = await registerMcpClientsOnHost( selected.value, legacy, undefined, @@ -181,7 +181,7 @@ it("registers Amp in settings.jsonc when that is Amp's only settings file", asyn ); if (!selected.ok) throw selected.error; expect(selected.value[0]?.configPath).toBe(jsonc); - await registerMcpClients( + await registerMcpClientsOnHost( selected.value, { command: command[0] ?? "", args: command.slice(1) }, undefined, @@ -566,7 +566,7 @@ it.skipIf(platform === "win32")( expect(selected.value[0]).toMatchObject({ configPaths: row?.configPaths, }); - const [outcome] = await registerMcpClients( + const [outcome] = await registerMcpClientsOnHost( selected.value, { command: command[0] ?? "", args: command.slice(1) }, undefined, @@ -743,7 +743,7 @@ it.skipIf(platform === "win32")( resources, ); if (!selected.ok) throw selected.error; - const [outcome] = await registerMcpClients( + const [outcome] = await registerMcpClientsOnHost( selected.value, { command: command[0] ?? "", args: command.slice(1) }, undefined, diff --git a/tests/boundary/filesystem/webScriptExport.test.ts b/tests/boundary/filesystem/webScriptExport.test.ts index d9430b0585..078c96ad85 100644 --- a/tests/boundary/filesystem/webScriptExport.test.ts +++ b/tests/boundary/filesystem/webScriptExport.test.ts @@ -1498,25 +1498,3 @@ it.each(["basename", "directory"])( ).toEqual(result.scripts); }, ); - -it("retains invalid Windows ChangeTime configuration at the capture read boundary", async () => { - const { input, resources } = await setup(); - const platform = Object.getOwnPropertyDescriptor(process, "platform")!; - const previous = process.env.REA_WINDOWS_CHANGE_TIME_DRIFT_MS; - try { - Object.defineProperty(process, "platform", { value: "win32" }); - process.env.REA_WINDOWS_CHANGE_TIME_DRIFT_MS = "invalid"; - const result = await exportWebScripts(input, resources); - expect(result.ok).toBe(false); - if (result.ok) throw new Error("Expected configuration refusal"); - expect(projectAnalysisError(result.error)).toMatchObject({ - code: "configuration_invalid", - details: { settings: [{ setting: "REA_WINDOWS_CHANGE_TIME_DRIFT_MS" }] }, - }); - } finally { - Object.defineProperty(process, "platform", platform); - if (previous === undefined) - delete process.env.REA_WINDOWS_CHANGE_TIME_DRIFT_MS; - else process.env.REA_WINDOWS_CHANGE_TIME_DRIFT_MS = previous; - } -}); diff --git a/tests/boundary/filesystem/webScriptExportWindowsChangeTime.test.ts b/tests/boundary/filesystem/webScriptExportWindowsChangeTime.test.ts new file mode 100644 index 0000000000..b2006d465c --- /dev/null +++ b/tests/boundary/filesystem/webScriptExportWindowsChangeTime.test.ts @@ -0,0 +1,41 @@ +import { writeFile } from "node:fs/promises"; +import { join } from "node:path"; + +import { expect, it, onTestFinished, vi } from "vitest"; + +import { exportWebScripts } from "../../../src/application/WebScriptExportService.js"; +import { ArtifactResourceScope } from "../../../src/resources/ArtifactResourceScope.js"; +import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { scriptCaptureEvidenceFixture } from "../../fixtures/webScriptCapture.js"; + +// The capture read settles its ChangeTime baseline by the running host's +// rules; select Windows, whose settle budget comes from the environment. +vi.mock("../../../src/platform/HostPlatform.js", () => ({ + HOST_PLATFORM: Object.freeze({ platform: "win32", architecture: "x64" }), +})); + +it("retains invalid Windows ChangeTime configuration at the capture read boundary", async () => { + const root = await createTestTempDirectory("rea-web-script-export-"); + const resources = new ArtifactResourceScope(); + onTestFinished(() => resources.close()); + const input = { + capture_path: join(root, "capture.json"), + output_directory: join(root, "export"), + }; + await writeFile( + input.capture_path, + JSON.stringify(scriptCaptureEvidenceFixture()), + ); + vi.stubEnv("REA_WINDOWS_CHANGE_TIME_DRIFT_MS", "invalid"); + onTestFinished(() => { + vi.unstubAllEnvs(); + }); + const result = await exportWebScripts(input, resources); + expect(result.ok).toBe(false); + if (result.ok) throw new Error("Expected configuration refusal"); + expect(projectAnalysisError(result.error)).toMatchObject({ + code: "configuration_invalid", + details: { settings: [{ setting: "REA_WINDOWS_CHANGE_TIME_DRIFT_MS" }] }, + }); +}); diff --git a/tests/boundary/filesystem/webScriptManifestPaths.test.ts b/tests/boundary/filesystem/webScriptManifestPaths.test.ts index a5dfeb26c8..6657bde5aa 100644 --- a/tests/boundary/filesystem/webScriptManifestPaths.test.ts +++ b/tests/boundary/filesystem/webScriptManifestPaths.test.ts @@ -208,22 +208,19 @@ it.each(["trace_web_module_imports", "trace_web_source_location"] as const)( "refuses Windows backslash source interpretation for %s", async (operation) => { const fixture = await literalManifest(); - const originalPlatform = Object.getOwnPropertyDescriptor( - process, - "platform", + // Exercise the Windows admission branch; this is not native Windows IO. + const artifacts = new LocalWebScriptArtifacts( + operation, + undefined, + "win32", ); - const artifacts = new LocalWebScriptArtifacts(operation); let response; try { - // Exercise the Windows admission branch; this is not native Windows IO. - Object.defineProperty(process, "platform", { value: "win32" }); response = await artifacts.load({ manifest_path: fixture.manifestPath, script_index: 0, }); } finally { - if (originalPlatform !== undefined) - Object.defineProperty(process, "platform", originalPlatform); await artifacts.close(); } if (response.ok) throw new Error("Expected Windows source path refusal"); diff --git a/tests/boundary/javascript-recovery/wakaruCommandConfiguration.test.ts b/tests/boundary/javascript-recovery/wakaruCommandConfiguration.test.ts index 6d2b482d8c..87b1a7bbb5 100644 --- a/tests/boundary/javascript-recovery/wakaruCommandConfiguration.test.ts +++ b/tests/boundary/javascript-recovery/wakaruCommandConfiguration.test.ts @@ -2,11 +2,12 @@ import { mkdir, realpath, symlink, writeFile } from "node:fs/promises"; import { join } from "node:path"; import { expect, it } from "vitest"; import { resolveWakaruCommand } from "../../../src/javascript/recovery/WakaruCommand.js"; +import { SIMULATED_LINUX_X64 } from "../../fixtures/simulatedHost.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; -const linuxX64 = it.skipIf( - process.platform !== "linux" || process.arch !== "x64", -); +// Wakaru admits only Linux x64; select that host and keep the real POSIX +// filesystem for the configured paths. +const linuxX64 = it.skipIf(process.platform === "win32"); linuxX64( "refuses a directory configured as the Wakaru resource limiter", @@ -18,10 +19,13 @@ linuxX64( await mkdir(limiter); await expect( - resolveWakaruCommand({ - REA_WAKARU_COMMAND: command, - REA_JAVASCRIPT_PRLIMIT_COMMAND: limiter, - }), + resolveWakaruCommand( + { + REA_WAKARU_COMMAND: command, + REA_JAVASCRIPT_PRLIMIT_COMMAND: limiter, + }, + SIMULATED_LINUX_X64, + ), ).rejects.toMatchObject({ _tag: "AnalysisCapabilityUnavailableError", reason: expect.stringContaining(limiter), @@ -39,10 +43,13 @@ linuxX64("allows a symlink to a regular Wakaru resource limiter", async () => { await symlink(target, limiter); await expect( - resolveWakaruCommand({ - REA_WAKARU_COMMAND: command, - REA_JAVASCRIPT_PRLIMIT_COMMAND: limiter, - }), + resolveWakaruCommand( + { + REA_WAKARU_COMMAND: command, + REA_JAVASCRIPT_PRLIMIT_COMMAND: limiter, + }, + SIMULATED_LINUX_X64, + ), ).resolves.toMatchObject({ limiter: { invocationPath: limiter, resolvedPath: await realpath(target) }, }); diff --git a/tests/boundary/mcp/hostRestrictedAvailabilityMcp.test.ts b/tests/boundary/mcp/hostRestrictedAvailabilityMcp.test.ts new file mode 100644 index 0000000000..6c46077885 --- /dev/null +++ b/tests/boundary/mcp/hostRestrictedAvailabilityMcp.test.ts @@ -0,0 +1,250 @@ +import { join } from "node:path"; + +import { Client, InMemoryTransport } from "@modelcontextprotocol/client"; +import { expect, it } from "vitest"; +import { z } from "zod"; + +import { expandToolAvailability } from "../../../src/contracts/toolOutputSchemaPrimitives.js"; +import { sessionOutputSchemas } from "../../../src/contracts/toolOutputSchemaGroups.js"; +import { createServer } from "../../../src/server/createServer.js"; +import { createTestBinarySession } from "../../fixtures/binarySession.js"; +import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; + +/** Each tool with the host its execution check admits. */ +const HOST_RESTRICTED_TOOLS = [ + ["inspect_packet_capture", "linux"], + ["inspect_packet_fields", "linux"], + ["decode_signal_recording", "linux"], + ["inspect_signal_decoders", "linux"], + ["inspect_firmware_regions", "linux"], + ["extract_firmware", "linux"], + ["inspect_binary_layout", "linux-x64"], + ["inspect_recorded_crash", "linux-x64"], + ["recover_javascript_sources", "linux-x64"], + ["inspect_evm_interface", "linux-x64"], +] as const; + +const connect = async ( + platform: NodeJS.Platform, + architecture: NodeJS.Architecture, + options: Parameters[1] = {}, +): Promise<{ + readonly path: (name: string) => string; + readonly availability: () => Promise< + ReturnType + >; + readonly call: ( + name: string, + args: Record, + ) => Promise>; + readonly close: () => Promise; +}> => { + const directory = await createTestTempDirectory("rea-host-restricted-mcp-"); + const path = (name: string) => join(directory, name); + const session = createTestBinarySession(() => { + throw new Error("binary analysis must not start during status discovery"); + }); + // Absolute paths configure every integration; discovery does not run them. + const server = createServer( + { kind: "session", session }, + { + environment: { + REA_TSHARK_COMMAND: path("tshark"), + REA_SIGROK_COMMAND: path("sigrok-cli"), + REA_BINWALK_COMMAND: path("binwalk"), + REA_UNBLOB_COMMAND: path("unblob"), + REA_PWNTOOLS_PYTHON: path("python3"), + REA_WAKARU_COMMAND: path("wakaru"), + REA_EVM_PRLIMIT_COMMAND: path("missing-prlimit"), + REA_MCP_OUTPUT_SCHEMA_PROFILE: "off", + }, + // Discovery and execution checks both read the server's selected host. + host: { platform, architecture }, + ...options, + }, + ); + const client = new Client({ + name: "host-restricted-availability", + version: "1", + }); + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + await server.connect(serverTransport); + await client.connect(clientTransport); + const call = async (name: string, args: Record) => { + const response = await client.callTool({ name, arguments: args }); + const text = z + .array(z.object({ type: z.string(), text: z.string().optional() })) + .parse(response.content) + .find((item) => item.type === "text")?.text; + return z + .record(z.string(), z.unknown()) + .parse(response.structuredContent ?? JSON.parse(text ?? "null")); + }; + return { + path, + availability: async () => + expandToolAvailability( + sessionOutputSchemas.binary_session.parse( + await call("binary_session", {}), + ).result.tool_availability, + ), + call, + close: async () => { + await Promise.allSettled([ + client.close(), + server.close(), + session.close(), + ]); + }, + }; +}; + +it.each([ + ["darwin", "arm64"], + ["linux", "arm64"], + ["linux", "x64"], +] as const)( + "reports host-restricted integrations on %s %s by host before configuration", + async (platform, arch) => { + const harness = await connect(platform, arch); + try { + const availability = await harness.availability(); + for (const [name, requirement] of HOST_RESTRICTED_TOOLS) { + const supported = + platform === "linux" && (requirement === "linux" || arch === "x64"); + const entry = availability.find((tool) => tool.name === name); + if (!supported) + expect(entry, name).toMatchObject({ + available: false, + reason: "unsupported_host", + }); + else if (name === "inspect_evm_interface") + // The configured limiter is absent; the host itself is supported. + expect(entry, name).toMatchObject({ + available: false, + reason: "provider_missing", + }); + else expect(entry, name).toMatchObject({ available: true }); + } + } finally { + await harness.close(); + } + }, +); + +it.each([ + ["the observed host", "darwin", "arm64", {}], + [ + "the caller", + "linux", + "x64", + { hostUnsupported: { signalRecording: true } }, + ], +] as const)( + "keeps a host restriction from %s under a configured availability policy", + async (_source, platform, arch, restriction) => { + const harness = await connect(platform, arch, { + availabilityPolicy: () => ({ + processCaptureEnabled: true, + signalRecordingEnabled: true, + ...restriction, + }), + }); + try { + expect( + (await harness.availability()).find( + (tool) => tool.name === "decode_signal_recording", + ), + ).toMatchObject({ available: false, reason: "unsupported_host" }); + } finally { + await harness.close(); + } + }, +); + +it("refuses execution on the hosts that discovery reports unsupported", async () => { + const harness = await connect("darwin", "arm64"); + try { + for (const [name, args] of [ + ["inspect_signal_decoders", {}], + ["inspect_binary_layout", { path: harness.path("runtime.hex") }], + [ + "inspect_evm_interface", + { path: harness.path("runtime.hex"), encoding: "hex" }, + ], + ] as const) + expect(await harness.call(name, args), name).toMatchObject({ + error: { code: "capability_unavailable", retryable: false }, + }); + } finally { + await harness.close(); + } +}); + +it("gates execution of the default providers by the server's selected host", async () => { + // One of the two hosts differs from the runner's, so each provider refuses + // differently under them only if composition forwards the selected host. + const unsupported = await connect("darwin", "arm64"); + const supported = await connect("linux", "x64"); + try { + for (const name of [ + "inspect_firmware_regions", + "recover_javascript_sources", + "inspect_packet_fields", + "inspect_signal_decoders", + "inspect_evm_interface", + ] as const) { + const args = (harness: typeof supported) => + name === "inspect_packet_fields" || name === "inspect_signal_decoders" + ? {} + : name === "recover_javascript_sources" + ? { + path: harness.path("input.js"), + output_directory: harness.path("recovered"), + } + : name === "inspect_evm_interface" + ? { path: harness.path("runtime.hex"), encoding: "hex" } + : { path: harness.path("firmware.bin") }; + const refused = await unsupported.call(name, args(unsupported)); + expect(refused, name).toMatchObject({ + error: { code: "capability_unavailable", retryable: false }, + }); + const admitted = await supported.call(name, args(supported)); + expect( + (admitted as { error?: { message?: unknown } }).error?.message, + name, + ).not.toBe((refused as { error: { message: unknown } }).error.message); + } + } finally { + await Promise.all([unsupported.close(), supported.close()]); + } +}); + +it.each([ + ["win32", false], + ["linux", true], +] as const)( + "reports process capture on a selected %s host as its plan admits it", + async (platform, admitted) => { + const harness = await connect(platform, "x64"); + try { + const entry = (await harness.availability()).find( + (tool) => tool.name === "capture_process_scenario", + ); + expect(entry?.available).toBe(admitted); + const planned = await harness.call("capture_process_scenario", { + executable: process.execPath, + working_directory: harness.path("."), + dry_run: true, + }); + if (admitted) expect(planned).not.toHaveProperty("error"); + else + expect(planned).toMatchObject({ + error: { code: "capability_unavailable" }, + }); + } finally { + await harness.close(); + } + }, +); diff --git a/tests/boundary/native/pwntoolsArtifactCleanup.test.ts b/tests/boundary/native/pwntoolsArtifactCleanup.test.ts index 3538a38f32..4a277200a9 100644 --- a/tests/boundary/native/pwntoolsArtifactCleanup.test.ts +++ b/tests/boundary/native/pwntoolsArtifactCleanup.test.ts @@ -1,3 +1,4 @@ +import { SIMULATED_LINUX_X64 } from "../../fixtures/simulatedHost.js"; import { createHash } from "node:crypto"; import { mkdtemp, rm, writeFile, readFile, mkdir } from "node:fs/promises"; import { tmpdir } from "node:os"; @@ -74,203 +75,181 @@ const makeDecoder = () => async () => { throw new Error("runtime should not be created for failed input read"); }, + SIMULATED_LINUX_X64, ); -const emulateSupportedHost = async ( - run: () => Promise, -): Promise => { - const platform = Object.getOwnPropertyDescriptor(process, "platform"); - const arch = Object.getOwnPropertyDescriptor(process, "arch"); - Object.defineProperty(process, "platform", { ...platform, value: "linux" }); - Object.defineProperty(process, "arch", { ...arch, value: "x64" }); +it("reports the read failure without stale incomplete-cleanup state when close retry succeeds", async () => { + const root = await mkdtemp(join(tmpdir(), "rea-pwntools-close-retry-")); + const path = join(root, "selected.bin"); + await writeFile(path, "selected evidence"); + closeState.fail = false; + closeState.failOnce = true; + closeState.opened = 0; + closeState.closes = 0; + const decoder = makeDecoder(); try { - await run(); + const result = await decoder.inspect({ path }); + if (result.ok) throw new Error("Injected close failure was not returned"); + expect(result.error.partialObservation).toEqual({ + kind: "file-snapshot-hash", + path, + bytes: 17, + sha256: createHash("sha256").update("selected evidence").digest("hex"), + }); + expect(result.error.cleanupIncomplete).toBe(false); + expect(projectAnalysisError(result.error).code).not.toBe( + "cleanup_incomplete", + ); + expect(result.error.cause).toMatchObject({ + cleanup: { + resources: [path], + reason: expect.stringContaining( + "injected stable artifact close failure", + ), + }, + }); + expect(closeState.closes).toBeGreaterThanOrEqual(2); + } finally { + closeState.fail = false; + closeState.failOnce = false; + await decoder.close(); + await rm(root, { recursive: true, force: true }); + } +}); + +it("retains a persistent failed input descriptor and refuses the next acquisition", async () => { + const root = await mkdtemp(join(tmpdir(), "rea-pwntools-held-close-")); + const path = join(root, "selected.bin"); + await writeFile(path, "selected evidence"); + closeState.fail = true; + closeState.failOnce = false; + closeState.opened = 0; + closeState.closes = 0; + const decoder = makeDecoder(); + try { + const first = await decoder.inspect({ path }); + expect(first.ok).toBe(false); + if (first.ok) throw new Error("Persistent close failure was not returned"); + expect(projectAnalysisError(first.error).code).toBe("cleanup_incomplete"); + const openedAfterFailure = closeState.opened; + + const retry = await decoder.inspect({ path }); + if (retry.ok) throw new Error("Retained descriptor was not retried"); + expect(projectAnalysisError(retry.error).code).toBe("cleanup_incomplete"); + expect(closeState.opened).toBe(openedAfterFailure); + + await expect(decoder.close()).rejects.toMatchObject({ + cleanupIncomplete: true, + }); + closeState.fail = false; + await decoder.close(); } finally { - if (platform !== undefined) - Object.defineProperty(process, "platform", platform); - if (arch !== undefined) Object.defineProperty(process, "arch", arch); - } -}; - -it("reports the read failure without stale incomplete-cleanup state when close retry succeeds", async () => - emulateSupportedHost(async () => { - const root = await mkdtemp(join(tmpdir(), "rea-pwntools-close-retry-")); - const path = join(root, "selected.bin"); - await writeFile(path, "selected evidence"); closeState.fail = false; - closeState.failOnce = true; - closeState.opened = 0; - closeState.closes = 0; - const decoder = makeDecoder(); - try { - const result = await decoder.inspect({ path }); - if (result.ok) throw new Error("Injected close failure was not returned"); - expect(result.error.partialObservation).toEqual({ - kind: "file-snapshot-hash", - path, - bytes: 17, - sha256: createHash("sha256").update("selected evidence").digest("hex"), - }); - expect(result.error.cleanupIncomplete).toBe(false); - expect(projectAnalysisError(result.error).code).not.toBe( - "cleanup_incomplete", - ); - expect(result.error.cause).toMatchObject({ - cleanup: { - resources: [path], - reason: expect.stringContaining( - "injected stable artifact close failure", - ), - }, - }); - expect(closeState.closes).toBeGreaterThanOrEqual(2); - } finally { - closeState.fail = false; - closeState.failOnce = false; - await decoder.close(); - await rm(root, { recursive: true, force: true }); - } - })); - -it("retains a persistent failed input descriptor and refuses the next acquisition", async () => - emulateSupportedHost(async () => { - const root = await mkdtemp(join(tmpdir(), "rea-pwntools-held-close-")); - const path = join(root, "selected.bin"); - await writeFile(path, "selected evidence"); - closeState.fail = true; closeState.failOnce = false; - closeState.opened = 0; - closeState.closes = 0; - const decoder = makeDecoder(); try { - const first = await decoder.inspect({ path }); - expect(first.ok).toBe(false); - if (first.ok) - throw new Error("Persistent close failure was not returned"); - expect(projectAnalysisError(first.error).code).toBe("cleanup_incomplete"); - const openedAfterFailure = closeState.opened; - - const retry = await decoder.inspect({ path }); - if (retry.ok) throw new Error("Retained descriptor was not retried"); - expect(projectAnalysisError(retry.error).code).toBe("cleanup_incomplete"); - expect(closeState.opened).toBe(openedAfterFailure); - - await expect(decoder.close()).rejects.toMatchObject({ - cleanupIncomplete: true, - }); - closeState.fail = false; await decoder.close(); - } finally { - closeState.fail = false; - closeState.failOnce = false; - try { - await decoder.close(); - } catch { - // The test already asserts persistent cleanup failure before releasing it. - } - await rm(root, { recursive: true, force: true }); + } catch { + // The test already asserts persistent cleanup failure before releasing it. } - })); + await rm(root, { recursive: true, force: true }); + } +}); -it("retains selected target identity when cancellation arrives after its completed read", async () => - emulateSupportedHost(async () => { - const root = await mkdtemp(join(tmpdir(), "rea-pwntools-input-cancel-")); - const path = join(root, "selected.bin"); - await writeFile(path, "selected evidence"); - closeState.inputAbort = new AbortController(); - const decoder = makeDecoder(); - try { - const result = await decoder.inspect( - { path }, - { signal: closeState.inputAbort.signal }, - ); - expect(result.ok).toBe(false); - if (result.ok) - throw new Error("input finalization unexpectedly succeeded"); - expect(projectAnalysisError(result.error).code).toBe("cancelled"); - expect(result.error.cause).toBe("selected-close-cancel"); - expect(result.error.partialObservation).toEqual({ - kind: "file-snapshot-hash", - path, - bytes: 17, - sha256: createHash("sha256").update("selected evidence").digest("hex"), - }); - } finally { - closeState.inputAbort = undefined; - await decoder.close(); - await rm(root, { recursive: true, force: true }); - } - })); +it("retains selected target identity when cancellation arrives after its completed read", async () => { + const root = await mkdtemp(join(tmpdir(), "rea-pwntools-input-cancel-")); + const path = join(root, "selected.bin"); + await writeFile(path, "selected evidence"); + closeState.inputAbort = new AbortController(); + const decoder = makeDecoder(); + try { + const result = await decoder.inspect( + { path }, + { signal: closeState.inputAbort.signal }, + ); + expect(result.ok).toBe(false); + if (result.ok) throw new Error("input finalization unexpectedly succeeded"); + expect(projectAnalysisError(result.error).code).toBe("cancelled"); + expect(result.error.cause).toBe("selected-close-cancel"); + expect(result.error.partialObservation).toEqual({ + kind: "file-snapshot-hash", + path, + bytes: 17, + sha256: createHash("sha256").update("selected evidence").digest("hex"), + }); + } finally { + closeState.inputAbort = undefined; + await decoder.close(); + await rm(root, { recursive: true, force: true }); + } +}); // Simulated decoder writes a reply; the selected object is never executed. it("retains admitted layout through reply close failure and cancellation, then resolves cleanup", async () => { await prepareProcessOwnershipInspection(); - await emulateSupportedHost(async () => { - const root = await mkdtemp(join(tmpdir(), "rea-pwntools-reply-close-")); - const path = join(root, "selected.bin"); - await writeFile(path, Buffer.alloc(128)); - const runtime = await PrivateRuntimeRoot.create({ - parent: root, - prefix: "worker-", - }); - const { - artifact: _artifact, - diagnostics: _diagnostics, - ...payload - } = binaryLayoutFixture(path); - closeState.replyFail = true; - closeState.abort = new AbortController(); - const provider = new PwntoolsLayoutProvider( - { REA_PWNTOOLS_PYTHON: process.execPath }, - async (spawn) => { - const request = JSON.parse( - await readFile(join(runtime.path, "request.json"), "utf8"), - ) as { reply_path: string }; - return spawnOwnedProviderProcess({ - ...spawn, - arguments: [ - "-e", - 'require("node:fs").writeFileSync(process.argv[1], process.argv[2])', - request.reply_path, - JSON.stringify({ - ok: true, - profile: PWNTOOLS_PROVIDER_IDENTITY.version, - value: payload, - }), - ], - }); - }, - async () => runtime, - ); - try { - const result = await provider.inspect( - { path }, - { signal: closeState.abort.signal }, - ); - expect(result.ok).toBe(false); - if (result.ok) - throw new Error("reply finalization unexpectedly succeeded"); - expect(result.error.cleanupIncomplete).toBe(true); - expect(result.error.partialObservation).toMatchObject({ - artifact: { path, bytes: 128 }, - }); - expect(projectAnalysisError(result.error)).toMatchObject({ - code: "cleanup_incomplete", - }); - closeState.replyFail = false; - closeState.abort = undefined; - await provider.close(); - expect(result.error.cleanupIncomplete).toBe(false); - expect(projectAnalysisError(result.error)).toMatchObject({ - code: "cancelled", - }); - } finally { - closeState.replyFail = false; - closeState.abort = undefined; - await provider.close(); - await rm(root, { recursive: true, force: true }); - } + const root = await mkdtemp(join(tmpdir(), "rea-pwntools-reply-close-")); + const path = join(root, "selected.bin"); + await writeFile(path, Buffer.alloc(128)); + const runtime = await PrivateRuntimeRoot.create({ + parent: root, + prefix: "worker-", }); + const { + artifact: _artifact, + diagnostics: _diagnostics, + ...payload + } = binaryLayoutFixture(path); + closeState.replyFail = true; + closeState.abort = new AbortController(); + const provider = new PwntoolsLayoutProvider( + { REA_PWNTOOLS_PYTHON: process.execPath }, + async (spawn) => { + const request = JSON.parse( + await readFile(join(runtime.path, "request.json"), "utf8"), + ) as { reply_path: string }; + return spawnOwnedProviderProcess({ + ...spawn, + arguments: [ + "-e", + 'require("node:fs").writeFileSync(process.argv[1], process.argv[2])', + request.reply_path, + JSON.stringify({ + ok: true, + profile: PWNTOOLS_PROVIDER_IDENTITY.version, + value: payload, + }), + ], + }); + }, + async () => runtime, + SIMULATED_LINUX_X64, + ); + try { + const result = await provider.inspect( + { path }, + { signal: closeState.abort.signal }, + ); + expect(result.ok).toBe(false); + if (result.ok) throw new Error("reply finalization unexpectedly succeeded"); + expect(result.error.cleanupIncomplete).toBe(true); + expect(result.error.partialObservation).toMatchObject({ + artifact: { path, bytes: 128 }, + }); + expect(projectAnalysisError(result.error)).toMatchObject({ + code: "cleanup_incomplete", + }); + closeState.replyFail = false; + closeState.abort = undefined; + await provider.close(); + expect(result.error.cleanupIncomplete).toBe(false); + expect(projectAnalysisError(result.error)).toMatchObject({ + code: "cancelled", + }); + } finally { + closeState.replyFail = false; + closeState.abort = undefined; + await provider.close(); + await rm(root, { recursive: true, force: true }); + } }); it.each([ @@ -287,144 +266,143 @@ it.each([ "admits base core facts before optional debugger enrichment: %s", async (scenario) => { await prepareProcessOwnershipInspection(); - await emulateSupportedHost(async () => { - const root = await mkdtemp(join(tmpdir(), "rea-pwntools-core-reply-")); - const path = join(root, "selected.core"); - const value = recordedCrashFixture(path); - await writeFile(path, recordedCrashFixtureBytes(value)); - const runtime = await PrivateRuntimeRoot.create({ - parent: root, - prefix: "worker-", - }); - const plugin = join(root, "gdbinit.py"); - const venv = join(root, "venv"); - await writeFile(plugin, "# simulated debugger fixture"); - await mkdir(venv); - const { - artifact: _artifact, - diagnostics: _diagnostics, - debugger: _debugger, - decoder_diagnostics: _decoderDiagnostics, - ...payload - } = value; - if (scenario === "invalid-source" || scenario === "invalid-source-cancel") - payload.notes[0]!.owner_bytes_base64 = - Buffer.from("FAKE\0").toString("base64"); - closeState.replyFail = - scenario !== "normal" && - scenario !== "cancel" && - scenario !== "invalid-source-cancel" && - scenario !== "malformed-cancel"; - closeState.abort = - scenario === "cancel-close" || - scenario === "cancel" || - scenario === "invalid-source-cancel" || - scenario === "malformed-cancel" - ? new AbortController() - : undefined; - let launches = 0; - const provider = new PwntoolsRecordedCrashProvider( - { - REA_PWNTOOLS_PYTHON: process.execPath, - REA_PWNDBG_GDB: process.execPath, - REA_PWNDBG_GDBINIT: plugin, - REA_PWNDBG_VENV_PATH: venv, - }, - async (spawn) => { - launches++; - const request = JSON.parse( - await readFile( - join(spawn.cwd ?? runtime.path, "request.json"), - "utf8", - ), - ) as { reply_path: string }; - const reply = - launches === 1 - ? { - ok: true, - profile: - scenario === "invalid-profile" - ? "foreign-profile" - : PWNTOOLS_PROVIDER_IDENTITY.version, - value: payload, - } - : { ok: true, value: recordedCrashDebuggerFixture() }; - return spawnOwnedProviderProcess({ - ...spawn, - arguments: [ - "-e", - 'require("node:fs").writeFileSync(process.argv[1], process.argv[2])', - request.reply_path, - scenario === "malformed" || scenario === "malformed-cancel" - ? "{broken" - : JSON.stringify(reply), - ], - }); - }, - async () => runtime, + const root = await mkdtemp(join(tmpdir(), "rea-pwntools-core-reply-")); + const path = join(root, "selected.core"); + const value = recordedCrashFixture(path); + await writeFile(path, recordedCrashFixtureBytes(value)); + const runtime = await PrivateRuntimeRoot.create({ + parent: root, + prefix: "worker-", + }); + const plugin = join(root, "gdbinit.py"); + const venv = join(root, "venv"); + await writeFile(plugin, "# simulated debugger fixture"); + await mkdir(venv); + const { + artifact: _artifact, + diagnostics: _diagnostics, + debugger: _debugger, + decoder_diagnostics: _decoderDiagnostics, + ...payload + } = value; + if (scenario === "invalid-source" || scenario === "invalid-source-cancel") + payload.notes[0]!.owner_bytes_base64 = + Buffer.from("FAKE\0").toString("base64"); + closeState.replyFail = + scenario !== "normal" && + scenario !== "cancel" && + scenario !== "invalid-source-cancel" && + scenario !== "malformed-cancel"; + closeState.abort = + scenario === "cancel-close" || + scenario === "cancel" || + scenario === "invalid-source-cancel" || + scenario === "malformed-cancel" + ? new AbortController() + : undefined; + let launches = 0; + const provider = new PwntoolsRecordedCrashProvider( + { + REA_PWNTOOLS_PYTHON: process.execPath, + REA_PWNDBG_GDB: process.execPath, + REA_PWNDBG_GDBINIT: plugin, + REA_PWNDBG_VENV_PATH: venv, + }, + async (spawn) => { + launches++; + const request = JSON.parse( + await readFile( + join(spawn.cwd ?? runtime.path, "request.json"), + "utf8", + ), + ) as { reply_path: string }; + const reply = + launches === 1 + ? { + ok: true, + profile: + scenario === "invalid-profile" + ? "foreign-profile" + : PWNTOOLS_PROVIDER_IDENTITY.version, + value: payload, + } + : { ok: true, value: recordedCrashDebuggerFixture() }; + return spawnOwnedProviderProcess({ + ...spawn, + arguments: [ + "-e", + 'require("node:fs").writeFileSync(process.argv[1], process.argv[2])', + request.reply_path, + scenario === "malformed" || scenario === "malformed-cancel" + ? "{broken" + : JSON.stringify(reply), + ], + }); + }, + async () => runtime, + SIMULATED_LINUX_X64, + ); + try { + const result = await provider.inspect( + { path, include_debugger_context: true }, + closeState.abort === undefined + ? undefined + : { signal: closeState.abort.signal }, ); - try { - const result = await provider.inspect( - { path, include_debugger_context: true }, - closeState.abort === undefined - ? undefined - : { signal: closeState.abort.signal }, - ); - expect(launches).toBe(scenario === "normal" ? 2 : 1); - if (scenario === "normal") { - expect(result.ok).toBe(true); - if (result.ok) expect(result.value.debugger.status).toBe("available"); - } else { - expect(result.ok).toBe(false); - if (result.ok) - throw new Error("reply finalization unexpectedly succeeded"); - if ( - scenario === "close" || - scenario === "cancel-close" || - scenario === "cancel" - ) { - expect(result.error.partialObservation).toMatchObject({ - artifact: { path, bytes: value.artifact.bytes }, - debugger: { status: "unavailable", requested: true }, - }); - } else expect(result.error.partialObservation).toBeUndefined(); - closeState.replyFail = false; - closeState.abort = undefined; - await provider.close(); - expect(result.error.cleanupIncomplete).toBe(false); - if ( - scenario === "invalid-source" || - scenario === "invalid-profile" || - scenario === "malformed" || - scenario === "invalid-source-cancel" || - scenario === "malformed-cancel" - ) - expect(projectAnalysisError(result.error).code).toBe( - "unreadable_output", - ); - if ( - scenario === "invalid-source-cancel" || - scenario === "malformed-cancel" - ) { - expect(projectAnalysisError(result.error)).toMatchObject({ - code: "unreadable_output", - details: { - diagnostics: { - reply_finalization_error: { code: "cancelled" }, - }, - }, - }); - expect( - result.error.diagnostics?.reply_finalization_error, - ).not.toHaveProperty("captured_output"); - } - } - } finally { + expect(launches).toBe(scenario === "normal" ? 2 : 1); + if (scenario === "normal") { + expect(result.ok).toBe(true); + if (result.ok) expect(result.value.debugger.status).toBe("available"); + } else { + expect(result.ok).toBe(false); + if (result.ok) + throw new Error("reply finalization unexpectedly succeeded"); + if ( + scenario === "close" || + scenario === "cancel-close" || + scenario === "cancel" + ) { + expect(result.error.partialObservation).toMatchObject({ + artifact: { path, bytes: value.artifact.bytes }, + debugger: { status: "unavailable", requested: true }, + }); + } else expect(result.error.partialObservation).toBeUndefined(); closeState.replyFail = false; closeState.abort = undefined; await provider.close(); - await rm(root, { recursive: true, force: true }); + expect(result.error.cleanupIncomplete).toBe(false); + if ( + scenario === "invalid-source" || + scenario === "invalid-profile" || + scenario === "malformed" || + scenario === "invalid-source-cancel" || + scenario === "malformed-cancel" + ) + expect(projectAnalysisError(result.error).code).toBe( + "unreadable_output", + ); + if ( + scenario === "invalid-source-cancel" || + scenario === "malformed-cancel" + ) { + expect(projectAnalysisError(result.error)).toMatchObject({ + code: "unreadable_output", + details: { + diagnostics: { + reply_finalization_error: { code: "cancelled" }, + }, + }, + }); + expect( + result.error.diagnostics?.reply_finalization_error, + ).not.toHaveProperty("captured_output"); + } } - }); + } finally { + closeState.replyFail = false; + closeState.abort = undefined; + await provider.close(); + await rm(root, { recursive: true, force: true }); + } }, ); diff --git a/tests/boundary/pcap/pcapCommand.test.ts b/tests/boundary/pcap/pcapCommand.test.ts index 5d71a47dcf..635942f48b 100644 --- a/tests/boundary/pcap/pcapCommand.test.ts +++ b/tests/boundary/pcap/pcapCommand.test.ts @@ -1,3 +1,4 @@ +import { HOST_PLATFORM } from "../../../src/platform/HostPlatform.js"; import { join } from "node:path"; import { writeFile } from "node:fs/promises"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; @@ -36,6 +37,7 @@ it.skipIf(process.platform !== "darwin")( throw new Error("Cancelled preparation must not launch the tool"); }); const failure = await runPcapCommand({ + platform: HOST_PLATFORM.platform, operation: "inspect_pcap_client", command: process.execPath, arguments: ["--version"], @@ -61,6 +63,7 @@ it("preserves a failed producer when cancellation arrives during its final clean const controller = new AbortController(); const reason = { request: "cancel during cleanup" }; const failure = await runPcapCommand({ + platform: HOST_PLATFORM.platform, operation: "inspect_pcap_capture", command: process.execPath, arguments: [ @@ -112,6 +115,7 @@ it.each([ async (reason) => { const controller = new AbortController(); const failure = await runPcapCommand({ + platform: HOST_PLATFORM.platform, operation: "inspect_pcap_client", command: process.execPath, arguments: [ @@ -176,6 +180,7 @@ it.skipIf(process.platform !== "darwin")( release(); }); const pending = runPcapCommand({ + platform: HOST_PLATFORM.platform, operation: "inspect_pcap_client", command: process.execPath, arguments: ["--version"], @@ -215,6 +220,7 @@ it("returns complete stdout while retaining unresolved process cleanup", async ( | undefined; let mayClean = false; const output = await runPcapCommand({ + platform: HOST_PLATFORM.platform, operation: "inspect_pcap_capture", command: process.execPath, arguments: ["-e", 'process.stdout.write("complete producer output")'], @@ -265,6 +271,7 @@ it.each([ "reports a %s launch refusal while reading a capture as an unavailable tool", async (code, wording) => { const failure = await runPcapCommand({ + platform: HOST_PLATFORM.platform, operation: "inspect_pcap_capture", command: "/selected/tshark", arguments: ["-r", "/authored-capture.pcap"], @@ -302,6 +309,7 @@ posixIt( await writeFile(file, ""); const command = join(file, "tshark"); const failure = await runPcapCommand({ + platform: HOST_PLATFORM.platform, operation: "inspect_pcap_client", command, arguments: ["--version"], @@ -323,6 +331,7 @@ posixIt( it("reports the Windows native launcher's refusal of the selected tool as an unavailable tool", async () => { const command = "C:\\Wireshark\\tshark.exe"; const failure = await runPcapCommand({ + platform: HOST_PLATFORM.platform, operation: "inspect_pcap_capture", command, arguments: ["-r", "/authored-capture.pcap"], @@ -353,6 +362,7 @@ it("reports the Windows native launcher's refusal of the selected tool as an una it("attributes a refused limiter spawn to the limiter, not Wireshark", async () => { const limiter = await selectArtifactCommandPath(process.execPath); const failure = await runPcapCommand({ + platform: HOST_PLATFORM.platform, operation: "inspect_pcap_capture", command: "/selected/tshark", arguments: [], @@ -425,6 +435,7 @@ const runLimited = async ( limiterArguments: string[] = ["--as=1073741824"], ) => runPcapCommand({ + platform: HOST_PLATFORM.platform, operation: "inspect_pcap_capture", command, arguments: [], @@ -482,6 +493,7 @@ posixIt("attributes prlimit's own refusal to the limiter", async () => { it("does not attribute an errno without spawn identity to the selected tool", async () => { const failure = await runPcapCommand({ + platform: HOST_PLATFORM.platform, operation: "inspect_pcap_client", command: "/selected/tshark", arguments: ["--version"], @@ -501,3 +513,38 @@ it("does not attribute an errno without spawn identity to the selected tool", as if (!(failure instanceof AnalysisProtocolError)) throw failure; expect(failure.message).toContain("failing stage is unknown"); }); + +it.each([ + ["win32", "C:\\Windows\\System32\\cmd.exe", true], + ["linux", "C:\\Tools\\tshark.cmd", false], +] as const)( + "launches a batch tool through cmd.exe only for a Windows host (%s)", + async (platform, expectedCommand, verbatim) => { + const launches: { + readonly command: string; + readonly windowsVerbatimArguments: boolean | undefined; + }[] = []; + await runPcapCommand({ + platform, + operation: "inspect_pcap_client", + command: "C:\\Tools\\tshark.cmd", + arguments: ["--version"], + limits: { timeoutMs: 5000, maxOutputBytes: 1024 }, + environment: { SYSTEMROOT: "C:\\Windows" }, + signal: undefined, + launcher: async (spawn) => { + launches.push({ + command: spawn.command, + windowsVerbatimArguments: spawn.windowsVerbatimArguments, + }); + throw new Error("recorded launch"); + }, + retain: () => { + throw new Error("No provider resources were acquired"); + }, + }).catch(() => undefined); + expect(launches).toEqual([ + { command: expectedCommand, windowsVerbatimArguments: verbatim }, + ]); + }, +); diff --git a/tests/boundary/pcap/pcapCredentialErrors.test.ts b/tests/boundary/pcap/pcapCredentialErrors.test.ts index 0f151d4298..f4d08845f0 100644 --- a/tests/boundary/pcap/pcapCredentialErrors.test.ts +++ b/tests/boundary/pcap/pcapCredentialErrors.test.ts @@ -1,3 +1,4 @@ +import { HOST_PLATFORM } from "../../../src/platform/HostPlatform.js"; import { z } from "zod"; import { existsSync } from "node:fs"; import { writeFile } from "node:fs/promises"; @@ -39,6 +40,7 @@ const ownedCommand = ( ) => runPcapCommand({ operation: "inspect_pcap_capture", + platform: HOST_PLATFORM.platform, command: process.execPath, arguments: ["-e", code], redactHttpTransportCredentials: true, @@ -117,6 +119,7 @@ it("retains safe cleanup observations and retries their original owner", async ( let retained = false; const output = await runPcapCommand({ operation: "inspect_pcap_capture", + platform: HOST_PLATFORM.platform, command: process.execPath, arguments: ["-e", print], redactHttpTransportCredentials: true, @@ -160,6 +163,7 @@ const nativeOptions = ( path: string, ): Omit[0], "limits"> => ({ operation: "inspect_pcap_capture", + platform: HOST_PLATFORM.platform, command: "/usr/bin/tshark", arguments: [ "-n", diff --git a/tests/boundary/pcap/pcapProviderCrossPlatform.test.ts b/tests/boundary/pcap/pcapProviderCrossPlatform.test.ts index 5cc0fc3a4e..0cc8312931 100644 --- a/tests/boundary/pcap/pcapProviderCrossPlatform.test.ts +++ b/tests/boundary/pcap/pcapProviderCrossPlatform.test.ts @@ -584,3 +584,21 @@ it.each(["tshark", "capinfos"] as const)( ); }, ); + +it.skipIf(isWindows).each([ + ["freebsd", { status: "unavailable", code: "unsupported_host" }], + ["win32", { status: "available" }], +] as const)( + "decides capture-host support from the selected %s host, not the running one", + async (platform, expected) => { + const provider = new PcapProvider({ + environment: { + REA_TSHARK_COMMAND: tsharkStub, + REA_CAPINFOS_COMMAND: capinfosStub, + }, + platform, + }); + onTestFinished(() => provider.close()); + expect(await provider.inspectAvailability()).toMatchObject(expected); + }, +); diff --git a/tests/boundary/process/artifactSelectedCommand.test.ts b/tests/boundary/process/artifactSelectedCommand.test.ts index e569fcd395..c4428cd6ef 100644 --- a/tests/boundary/process/artifactSelectedCommand.test.ts +++ b/tests/boundary/process/artifactSelectedCommand.test.ts @@ -1,3 +1,5 @@ +import { HOST_PLATFORM } from "../../../src/platform/HostPlatform.js"; +import { SIMULATED_LINUX_X64 } from "../../fixtures/simulatedHost.js"; import { chmod, mkdir, @@ -183,14 +185,6 @@ const createSelectedEngineFixture = async ( input, kind === "firmware" ? "fixture-input-data" : "module.exports = 42;", ); - const platform = Object.getOwnPropertyDescriptor(process, "platform"); - const arch = Object.getOwnPropertyDescriptor(process, "arch"); - if (platform === undefined || arch === undefined) - throw new Error("Missing host descriptors"); - const restoreHost = () => { - Object.defineProperty(process, "platform", platform); - Object.defineProperty(process, "arch", arch); - }; const launches: { cwd?: string; pid?: number; @@ -206,7 +200,6 @@ const createSelectedEngineFixture = async ( REA_SELECTED_ENVIRONMENT: "initial", }; const launcher: typeof spawnOwnedProviderProcess = async (options) => { - restoreHost(); const child = await spawnOwnedProviderProcess(options); launches.push({ command: options.command, @@ -223,12 +216,13 @@ const createSelectedEngineFixture = async ( onTestFinished(() => fileSizeCeiling.mockRestore()); const service = kind === "firmware" - ? new FirmwareAnalysisService(new FirmwareProvider(environment, launcher)) + ? new FirmwareAnalysisService( + new FirmwareProvider(environment, launcher, SIMULATED_LINUX_X64), + ) : new JavaScriptRecoveryService( - new WakaruProvider(environment, launcher), + new WakaruProvider(environment, launcher, SIMULATED_LINUX_X64), ); onTestFinished(async () => { - restoreHost(); await service.close(); for (const launch of launches) { if (launch.pid !== undefined) @@ -240,23 +234,13 @@ const createSelectedEngineFixture = async ( } }); let sequence = 0; - const execute = async () => { - Object.defineProperty(process, "platform", { - ...platform, - value: "linux", - }); - Object.defineProperty(process, "arch", { ...arch, value: "x64" }); - try { - return service instanceof FirmwareAnalysisService - ? await service.execute("inspect_firmware_regions", { path: input }) - : await service.recover({ - path: input, - output_directory: join(directory, `output-${sequence++}`), - }); - } finally { - restoreHost(); - } - }; + const execute = async () => + service instanceof FirmwareAnalysisService + ? service.execute("inspect_firmware_regions", { path: input }) + : service.recover({ + path: input, + output_directory: join(directory, `output-${sequence++}`), + }); return { bin, command, @@ -465,31 +449,21 @@ it.skipIf(process.platform === "win32")( { message: "busy", details: {} }, ); onTestFinished(() => resources.close()); - const platform = Object.getOwnPropertyDescriptor(process, "platform"); - if (platform === undefined) throw new Error("Missing host descriptor"); - let prepared: Awaited>; - try { - Object.defineProperty(process, "platform", { - ...platform, - value: "linux", - }); - prepared = await preparePcapNativeBound( - { REA_TSHARK_PRLIMIT_COMMAND: selected }, - resources, - async (_selected, args) => { - const stdout = - args[0] === "--help" - ? " --as[=limit] --fsize[=limit] --cpu[=limit] --core[=limit]" - : "prlimit from util-linux 2.38.1"; - return { - stdout, - capturedOutput: { stdout, stderr: "", truncated: false }, - }; - }, - ); - } finally { - Object.defineProperty(process, "platform", platform); - } + const prepared = await preparePcapNativeBound( + "linux", + { REA_TSHARK_PRLIMIT_COMMAND: selected }, + resources, + async (_selected, args) => { + const stdout = + args[0] === "--help" + ? " --as[=limit] --fsize[=limit] --cpu[=limit] --core[=limit]" + : "prlimit from util-linux 2.38.1"; + return { + stdout, + capturedOutput: { stdout, stderr: "", truncated: false }, + }; + }, + ); let refuseCleanup = false; let retained: ProviderProcessSupervisor | undefined; onTestFinished(async () => { @@ -499,6 +473,7 @@ it.skipIf(process.platform === "win32")( const execute = () => runPcapCommand({ operation: "inspect_pcap_capture", + platform: HOST_PLATFORM.platform, command: "/bin/echo", arguments: ["selected limiter"], limits: { timeoutMs: 10_000, maxOutputBytes: 1024 }, diff --git a/tests/boundary/process/nativeUiVerifierActions.test.ts b/tests/boundary/process/nativeUiVerifierActions.test.ts index efeb3c5903..f75b6cac3f 100644 --- a/tests/boundary/process/nativeUiVerifierActions.test.ts +++ b/tests/boundary/process/nativeUiVerifierActions.test.ts @@ -42,8 +42,8 @@ export const artifactMcpResult=async(_client,name)=>{if(name==='observe_native_u join(directory, "hook.mjs"), ` import {registerHooks} from 'node:module';import {pathToFileURL} from 'node:url'; -Object.defineProperty(process,'platform',{value:'darwin'});process.kill=()=>{const open=globalThis.reaOpenChild;if(open?.exitCode===null){open.exitCode=0;queueMicrotask(()=>open.emit('exit',0,null));}return true;}; -registerHooks({resolve(specifier,context,next){if(context.parentURL?.endsWith('/scripts/verify-native-ui.mjs')&&['node:child_process','../dist/application/BinaryTargetResolver.js','../dist/native/NativeUiObservation.js','./lib/artifact-e2e.mjs','../dist/process/ProcessOwnershipObservation.js'].includes(specifier))return {shortCircuit:true,url:pathToFileURL(process.env.RECORDING).href};return next(specifier,context);}}); +const darwinHost='data:text/javascript,'+encodeURIComponent('export const HOST_PLATFORM=Object.freeze({platform:"darwin",architecture:'+JSON.stringify(process.arch)+'});');process.kill=()=>{const open=globalThis.reaOpenChild;if(open?.exitCode===null){open.exitCode=0;queueMicrotask(()=>open.emit('exit',0,null));}return true;}; +registerHooks({resolve(specifier,context,next){if(context.parentURL?.endsWith('/scripts/verify-native-ui.mjs')&&specifier==='../dist/platform/HostPlatform.js')return {shortCircuit:true,url:darwinHost};if(context.parentURL?.endsWith('/scripts/verify-native-ui.mjs')&&['node:child_process','../dist/application/BinaryTargetResolver.js','../dist/native/NativeUiObservation.js','./lib/artifact-e2e.mjs','../dist/process/ProcessOwnershipObservation.js'].includes(specifier))return {shortCircuit:true,url:pathToFileURL(process.env.RECORDING).href};return next(specifier,context);}}); `, ); const result = execute( diff --git a/tests/boundary/process/providerOutcome.test.ts b/tests/boundary/process/providerOutcome.test.ts index 4424b400ae..f73e315aaa 100644 --- a/tests/boundary/process/providerOutcome.test.ts +++ b/tests/boundary/process/providerOutcome.test.ts @@ -1,3 +1,4 @@ +import { HOST_PLATFORM } from "../../../src/platform/HostPlatform.js"; import { randomUUID } from "node:crypto"; import { readFile } from "node:fs/promises"; import { beforeAll, expect, it } from "vitest"; @@ -133,6 +134,7 @@ const readCapture = ( ) => runPcapCommand({ operation: "inspect_pcap_capture", + platform: HOST_PLATFORM.platform, command: process.execPath, arguments: ["-e", script], inputPath: "/authored-capture.pcap", @@ -178,6 +180,7 @@ it("classifies a caller cancellation through the shared owner", async () => { const reason = { request: "caller cancel" }; const running = runPcapCommand({ operation: "inspect_pcap_capture", + platform: HOST_PLATFORM.platform, command: process.execPath, arguments: ["-e", "setInterval(() => {}, 1000)"], inputPath: "/authored-capture.pcap", diff --git a/tests/boundary/process/windowsExecutableSelection.test.ts b/tests/boundary/process/windowsExecutableSelection.test.ts index dd057304bb..66f32694c4 100644 --- a/tests/boundary/process/windowsExecutableSelection.test.ts +++ b/tests/boundary/process/windowsExecutableSelection.test.ts @@ -44,27 +44,27 @@ processTest.skipIf(process.platform !== "win32")( if (['path', 'pathext', 'nodefaultcurrentdirectoryinexepath', 'rea_adb_path', 'rea_apktool_command'].includes(key.toLowerCase())) delete environment[key]; environment.Path = ${JSON.stringify(trusted)}; environment.PathExt = '.EXE;.CMD'; - const adb = await resolveAdbBinary(environment); + const adb = await resolveAdbBinary(environment, 'win32'); assert.equal(adb.binary.toLowerCase(), ${JSON.stringify(join(trusted, "adb.exe").toLowerCase())}); const native = await execFileOutput(adb.binary, ['-e', 'process.stdout.write(process.execPath)'], { env: adb.environment, timeout: 5000 }); assert.equal(native.stdout.toLowerCase(), adb.binary.toLowerCase()); - const apktool = await resolveApktoolCommand(environment); + const apktool = await resolveApktoolCommand(environment, 'win32'); assert.equal(apktool.command.toLowerCase(), ${JSON.stringify(join(trusted, "apktool.cmd").toLowerCase())}); const apktoolCommands = new ApktoolCommandCleanup(); - try { assert.equal((await inspectApktoolClient(apktool, apktoolCommands, { environment })).version, '2.12.1'); } + try { assert.equal((await inspectApktoolClient(apktool, apktoolCommands, { environment, platform: 'win32' })).version, '2.12.1'); } finally { await apktoolCommands.close(); } const runner = new UpdateCommandRunner(); try { assert.deepEqual(await runner.runProbe(['npm', 'prefix', '--global'], environment), { ok: true, value: 'selected' }); assert.deepEqual(await runner.runInstall(['npm', 'install', '--global', 'fixture@0.0.0'], environment, 'structured'), { ok: true, value: '' }); const missing = { ...environment, Path: '' }; - await assert.rejects(resolveAdbBinary(missing), { code: 'binary_missing' }); - await assert.rejects(resolveApktoolCommand(missing), { code: 'command_missing' }); + await assert.rejects(resolveAdbBinary(missing, 'win32'), { code: 'binary_missing' }); + await assert.rejects(resolveApktoolCommand(missing, 'win32'), { code: 'command_missing' }); assert.equal((await runner.runProbe(['npm', 'prefix'], missing)).ok, false); // A caller who explicitly includes '.' still selects that directory. const explicit = { ...environment, Path: '.' }; - assert.equal((await resolveAdbBinary(explicit)).binary.toLowerCase(), ${JSON.stringify(join(working, "adb.exe").toLowerCase())}); - assert.equal((await resolveApktoolCommand(explicit)).command.toLowerCase(), ${JSON.stringify(join(working, "apktool.cmd").toLowerCase())}); + assert.equal((await resolveAdbBinary(explicit, 'win32')).binary.toLowerCase(), ${JSON.stringify(join(working, "adb.exe").toLowerCase())}); + assert.equal((await resolveApktoolCommand(explicit, 'win32')).command.toLowerCase(), ${JSON.stringify(join(working, "apktool.cmd").toLowerCase())}); assert.deepEqual(await runner.runProbe(['npm', 'prefix'], explicit), { ok: true, value: 'cwd' }); } finally { await runner.close(); } process.stdout.write('verified'); diff --git a/tests/boundary/providers/adb/adbCommandFinalization.test.ts b/tests/boundary/providers/adb/adbCommandFinalization.test.ts index 5cbc0b7586..9f1d607d71 100644 --- a/tests/boundary/providers/adb/adbCommandFinalization.test.ts +++ b/tests/boundary/providers/adb/adbCommandFinalization.test.ts @@ -1,3 +1,4 @@ +import { HOST_PLATFORM } from "../../../../src/platform/HostPlatform.js"; import { readFile, writeFile } from "node:fs/promises"; import { dirname, join } from "node:path"; import { beforeEach, expect, onTestFinished, test, vi } from "vitest"; @@ -69,7 +70,10 @@ const capture = async ( runAdbCapture( "inspect_adb_device", { device: "device" }, - await resolveAdbBinary({ ...process.env, REA_ADB_PATH: process.execPath }), + await resolveAdbBinary( + { ...process.env, REA_ADB_PATH: process.execPath }, + HOST_PLATFORM.platform, + ), ["-e", script], limits, signal, @@ -155,7 +159,10 @@ const clientScript = async (source: string) => { await writeFile(binary, `#!${process.execPath}\n${source}\n`, { mode: 0o755, }); - return resolveAdbBinary({ ...process.env, REA_ADB_PATH: binary }); + return resolveAdbBinary( + { ...process.env, REA_ADB_PATH: binary }, + HOST_PLATFORM.platform, + ); }; const nativeClientTest = test.skipIf(process.platform === "win32"); @@ -165,7 +172,10 @@ test.each([null, "caller stopped", new Error("caller stopped")] as const)( const controller = new AbortController(); controller.abort(reason); const error: unknown = await inspectAdbClient( - await resolveAdbBinary({ REA_ADB_PATH: process.execPath }), + await resolveAdbBinary( + { REA_ADB_PATH: process.execPath }, + HOST_PLATFORM.platform, + ), controller.signal, ).catch((cause: unknown) => cause); expect(error).toMatchObject({ @@ -209,7 +219,10 @@ nativeClientTest( const controller = new AbortController(); hooks.afterCommand = () => controller.abort(null); const error: unknown = await inspectAdbClient( - await resolveAdbBinary({ REA_ADB_PATH: join(root, "missing") }), + await resolveAdbBinary( + { REA_ADB_PATH: join(root, "missing") }, + HOST_PLATFORM.platform, + ), controller.signal, ).catch((cause: unknown) => cause); expect(error).toMatchObject({ diff --git a/tests/boundary/providers/apktoolProcessFixture.test.ts b/tests/boundary/providers/apktoolProcessFixture.test.ts index 18da0aea51..3644c96e40 100644 --- a/tests/boundary/providers/apktoolProcessFixture.test.ts +++ b/tests/boundary/providers/apktoolProcessFixture.test.ts @@ -1,3 +1,4 @@ +import { HOST_PLATFORM } from "../../../src/platform/HostPlatform.js"; import { mkdir, rm, writeFile } from "node:fs/promises"; import { expect, it } from "vitest"; @@ -23,7 +24,11 @@ it const probe = inspectApktoolClient( { command: fixture.command, commandSource: "environment" }, commands, - { signal: controller.signal, environment: process.env }, + { + signal: controller.signal, + environment: process.env, + platform: HOST_PLATFORM.platform, + }, ).catch((cause: unknown) => cause); try { await expect diff --git a/tests/boundary/providers/kuna/kunaCommandLifetime.test.ts b/tests/boundary/providers/kuna/kunaCommandLifetime.test.ts index 3acaad8734..6f0680f39e 100644 --- a/tests/boundary/providers/kuna/kunaCommandLifetime.test.ts +++ b/tests/boundary/providers/kuna/kunaCommandLifetime.test.ts @@ -10,11 +10,13 @@ import { ArtifactResourceScope } from "./dist/resources/ArtifactResourceScope.js import { AnalysisCleanupLease } from "./dist/resources/AnalysisCleanupLease.js"; import { inspectKunaInstallation } from "./dist/kuna/KunaInstallation.js"; import { KunaTargetCommands } from "./dist/kuna/KunaTargetCommands.js"; +import { HOST_PLATFORM } from "./dist/platform/HostPlatform.js"; const fixture = JSON.parse(process.env.REA_TEST_KUNA_FIXTURE); const kunaResources = new ArtifactResourceScope(); const installation = await inspectKunaInstallation( { REA_KUNA_COMMAND: fixture.kuna, REA_KUNA_CACHE_DIR: fixture.cacheRoot }, { + platform: HOST_PLATFORM.platform, resourceScope: { retain: (handle, resource) => kunaResources.retain({ kind: "lease", resource, lease: AnalysisCleanupLease.forCloseOwner(handle, resource) }), diff --git a/tests/boundary/providers/kuna/kunaInstallationLifetime.test.ts b/tests/boundary/providers/kuna/kunaInstallationLifetime.test.ts index 84dabfd0c6..e562c26b67 100644 --- a/tests/boundary/providers/kuna/kunaInstallationLifetime.test.ts +++ b/tests/boundary/providers/kuna/kunaInstallationLifetime.test.ts @@ -1,3 +1,4 @@ +import { HOST_PLATFORM } from "../../../../src/platform/HostPlatform.js"; import { afterEach, beforeEach, expect, it, vi } from "vitest"; const gates = vi.hoisted(() => { @@ -110,7 +111,11 @@ it gates.holdIdentityRead = phase === "identity-read"; const inspection = inspectKunaInstallation( { REA_KUNA_COMMAND: executable }, - { resourceScope, signal: controller.signal }, + { + platform: HOST_PLATFORM.platform, + resourceScope, + signal: controller.signal, + }, ); const inspectionOutcome = inspection.then( diff --git a/tests/boundary/providers/kuna/kunaResourceScope.ts b/tests/boundary/providers/kuna/kunaResourceScope.ts index 6bd17842e5..be2f5c1282 100644 --- a/tests/boundary/providers/kuna/kunaResourceScope.ts +++ b/tests/boundary/providers/kuna/kunaResourceScope.ts @@ -1,3 +1,4 @@ +import { HOST_PLATFORM } from "../../../../src/platform/HostPlatform.js"; import { createInspectionResources } from "../../../fixtures/inspectionResources.js"; import type { RetainedResourceScope } from "../../../../src/ports/AnalysisProvider.js"; import type { KunaInstallationOptions } from "../../../../src/kuna/KunaInstallation.js"; @@ -17,15 +18,21 @@ export const withKunaResourceScope = async ( export const inspectKunaInstallationOwned = ( environment: Readonly, - options: Omit = {}, + options: Omit & { + readonly platform?: NodeJS.Platform; + } = {}, ) => withKunaResourceScope((resourceScope) => - inspectKunaInstallation(environment, { ...options, resourceScope }), + inspectKunaInstallation(environment, { + platform: HOST_PLATFORM.platform, + ...options, + resourceScope, + }), ); export const inspectKunaProviderOwned = ( environment: Readonly, - platform?: NodeJS.Platform, + platform: NodeJS.Platform = HOST_PLATFORM.platform, ) => withKunaResourceScope((resourceScope) => inspectKunaProvider(environment, platform, { resourceScope }), diff --git a/tests/boundary/providers/kuna/kunaVersionProbeOwnership.test.ts b/tests/boundary/providers/kuna/kunaVersionProbeOwnership.test.ts index 12c3a9d22b..6f453c070d 100644 --- a/tests/boundary/providers/kuna/kunaVersionProbeOwnership.test.ts +++ b/tests/boundary/providers/kuna/kunaVersionProbeOwnership.test.ts @@ -1,3 +1,4 @@ +import { HOST_PLATFORM } from "../../../../src/platform/HostPlatform.js"; import { spawn } from "node:child_process"; import { createHash } from "node:crypto"; import { chmod, writeFile } from "node:fs/promises"; @@ -107,6 +108,7 @@ it.skipIf(process.platform === "win32")( const result = await inspectKunaInstallation( { REA_KUNA_COMMAND: executable }, { + platform: HOST_PLATFORM.platform, resourceScope: resourceScopeFor(scope), processLauncher: launcher.launcher, probeTimeoutMs: 3_000, @@ -240,6 +242,7 @@ it.skipIf(process.platform === "win32")( const pending = inspectKunaInstallation( { REA_KUNA_COMMAND: executable }, { + platform: HOST_PLATFORM.platform, resourceScope: resourceScopeFor(scope), processLauncher: launcher.launcher, signal: controller.signal, @@ -461,6 +464,7 @@ it.skipIf(process.platform === "win32")( const pending = inspectKunaInstallation( { REA_KUNA_COMMAND: executable }, { + platform: HOST_PLATFORM.platform, resourceScope: resourceScopeFor(scope), processLauncher: launcher.launcher, signal: controller.signal, diff --git a/tests/boundary/providers/readinessRemediationInventory.test.ts b/tests/boundary/providers/readinessRemediationInventory.test.ts index b66e76c37d..d59a51f0de 100644 --- a/tests/boundary/providers/readinessRemediationInventory.test.ts +++ b/tests/boundary/providers/readinessRemediationInventory.test.ts @@ -1,3 +1,4 @@ +import { HOST_PLATFORM } from "../../../src/platform/HostPlatform.js"; import { join } from "node:path"; import { expect, it, vi } from "vitest"; @@ -69,7 +70,7 @@ it.skipIf(process.platform === "win32").each([ REA_KUNA_COMMAND: "/audit/not-invoked/kuna", [setting]: value, }; - const owner = readKunaConfiguration(environment); + const owner = readKunaConfiguration(environment, HOST_PLATFORM.platform); if (owner.ok) throw new Error(`${setting}=${value} must be refused`); expect(owner.error.remediation).toContain(setting); expect(owner.error.remediation).not.toBe(owner.error.reason); diff --git a/tests/fixtures/mcpRegistration.ts b/tests/fixtures/mcpRegistration.ts new file mode 100644 index 0000000000..05250062e2 --- /dev/null +++ b/tests/fixtures/mcpRegistration.ts @@ -0,0 +1,41 @@ +import type { ArtifactResourceScope } from "../../src/resources/ArtifactResourceScope.js"; +import type { ClientRegistrationCommand } from "../../src/domain/clientRegistrationCommand.js"; +import { + registerMcpClient, + registerMcpClients, +} from "../../src/application/McpClientRegistration.js"; +import type { McpRegistrationClient } from "../../src/application/McpRegistrationCatalog.js"; +import { HOST_PLATFORM } from "../../src/platform/HostPlatform.js"; + +/** + * `rea mcp add` for clients resolved for the running host, as the CLI runs it. + * Tests that resolve clients for another platform call the owner directly. + */ +export const registerMcpClientOnHost = ( + client: McpRegistrationClient, + launcher: ClientRegistrationCommand, + signal: AbortSignal | undefined, + resources: ArtifactResourceScope, +) => + registerMcpClient( + client, + launcher, + signal, + resources, + HOST_PLATFORM.platform, + ); + +/** Register each host-resolved client in order, as `rea mcp add` does. */ +export const registerMcpClientsOnHost = ( + clients: readonly McpRegistrationClient[], + launcher: ClientRegistrationCommand, + signal: AbortSignal | undefined, + resources: ArtifactResourceScope, +) => + registerMcpClients( + clients, + launcher, + signal, + resources, + HOST_PLATFORM.platform, + ); diff --git a/tests/fixtures/simulatedHost.ts b/tests/fixtures/simulatedHost.ts new file mode 100644 index 0000000000..a70a735283 --- /dev/null +++ b/tests/fixtures/simulatedHost.ts @@ -0,0 +1,12 @@ +import type { HostPlatform } from "../../src/platform/HostPlatform.js"; + +/** + * The only host the pwntools decoders and the EVM interface worker admit. + * Tests pass it to a provider to exercise admission, launch and cleanup on any + * POSIX host; process ownership, fixture launches and the filesystem stay + * those of the real host. + */ +export const SIMULATED_LINUX_X64: HostPlatform = Object.freeze({ + platform: "linux", + architecture: "x64", +}); diff --git a/tests/process-global/hostRestrictedAvailabilityMcp.test.ts b/tests/process-global/hostRestrictedAvailabilityMcp.test.ts deleted file mode 100644 index 9877f3f4a7..0000000000 --- a/tests/process-global/hostRestrictedAvailabilityMcp.test.ts +++ /dev/null @@ -1,207 +0,0 @@ -import { join } from "node:path"; - -import { Client, InMemoryTransport } from "@modelcontextprotocol/client"; -import { expect, it } from "vitest"; -import { z } from "zod"; - -import { expandToolAvailability } from "../../src/contracts/toolOutputSchemaPrimitives.js"; -import { sessionOutputSchemas } from "../../src/contracts/toolOutputSchemaGroups.js"; -import { createServer } from "../../src/server/createServer.js"; -import { createTestBinarySession } from "../fixtures/binarySession.js"; -import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js"; - -/** Each tool with the host its execution check admits. */ -const HOST_RESTRICTED_TOOLS = [ - ["inspect_packet_capture", "linux"], - ["inspect_packet_fields", "linux"], - ["decode_signal_recording", "linux"], - ["inspect_signal_decoders", "linux"], - ["inspect_firmware_regions", "linux"], - ["extract_firmware", "linux"], - ["inspect_binary_layout", "linux-x64"], - ["inspect_recorded_crash", "linux-x64"], - ["recover_javascript_sources", "linux-x64"], - ["inspect_evm_interface", "linux-x64"], -] as const; - -/** Run with the host identity that discovery and execution checks read. */ -const emulateHost = async ( - platform: NodeJS.Platform, - arch: NodeJS.Architecture, - run: () => Promise, -): Promise => { - const original = { - platform: Object.getOwnPropertyDescriptor(process, "platform"), - arch: Object.getOwnPropertyDescriptor(process, "arch"), - }; - Object.defineProperty(process, "platform", { - ...original.platform, - value: platform, - }); - Object.defineProperty(process, "arch", { ...original.arch, value: arch }); - try { - await run(); - } finally { - if (original.platform !== undefined) - Object.defineProperty(process, "platform", original.platform); - if (original.arch !== undefined) - Object.defineProperty(process, "arch", original.arch); - } -}; - -const connect = async ( - options: Parameters[1] = {}, -): Promise<{ - readonly path: (name: string) => string; - readonly availability: () => Promise< - ReturnType - >; - readonly call: ( - name: string, - args: Record, - ) => Promise>; - readonly close: () => Promise; -}> => { - const directory = await createTestTempDirectory("rea-host-restricted-mcp-"); - const path = (name: string) => join(directory, name); - const session = createTestBinarySession(() => { - throw new Error("binary analysis must not start during status discovery"); - }); - // Absolute paths configure every integration; discovery does not run them. - const server = createServer( - { kind: "session", session }, - { - environment: { - REA_TSHARK_COMMAND: path("tshark"), - REA_SIGROK_COMMAND: path("sigrok-cli"), - REA_BINWALK_COMMAND: path("binwalk"), - REA_UNBLOB_COMMAND: path("unblob"), - REA_PWNTOOLS_PYTHON: path("python3"), - REA_WAKARU_COMMAND: path("wakaru"), - REA_EVM_PRLIMIT_COMMAND: path("missing-prlimit"), - REA_MCP_OUTPUT_SCHEMA_PROFILE: "off", - }, - ...options, - }, - ); - const client = new Client({ - name: "host-restricted-availability", - version: "1", - }); - const [clientTransport, serverTransport] = - InMemoryTransport.createLinkedPair(); - await server.connect(serverTransport); - await client.connect(clientTransport); - const call = async (name: string, args: Record) => { - const response = await client.callTool({ name, arguments: args }); - const text = z - .array(z.object({ type: z.string(), text: z.string().optional() })) - .parse(response.content) - .find((item) => item.type === "text")?.text; - return z - .record(z.string(), z.unknown()) - .parse(response.structuredContent ?? JSON.parse(text ?? "null")); - }; - return { - path, - availability: async () => - expandToolAvailability( - sessionOutputSchemas.binary_session.parse( - await call("binary_session", {}), - ).result.tool_availability, - ), - call, - close: async () => { - await Promise.allSettled([ - client.close(), - server.close(), - session.close(), - ]); - }, - }; -}; - -it.each([ - ["darwin", "arm64"], - ["linux", "arm64"], - ["linux", "x64"], -] as const)( - "reports host-restricted integrations on %s %s by host before configuration", - async (platform, arch) => - emulateHost(platform, arch, async () => { - const harness = await connect(); - try { - const availability = await harness.availability(); - for (const [name, requirement] of HOST_RESTRICTED_TOOLS) { - const supported = - platform === "linux" && (requirement === "linux" || arch === "x64"); - const entry = availability.find((tool) => tool.name === name); - if (!supported) - expect(entry, name).toMatchObject({ - available: false, - reason: "unsupported_host", - }); - else if (name === "inspect_evm_interface") - // The configured limiter is absent; the host itself is supported. - expect(entry, name).toMatchObject({ - available: false, - reason: "provider_missing", - }); - else expect(entry, name).toMatchObject({ available: true }); - } - } finally { - await harness.close(); - } - }), -); - -it.each([ - ["the observed host", "darwin", "arm64", {}], - [ - "the caller", - "linux", - "x64", - { hostUnsupported: { signalRecording: true } }, - ], -] as const)( - "keeps a host restriction from %s under a configured availability policy", - async (_source, platform, arch, restriction) => - emulateHost(platform, arch, async () => { - const harness = await connect({ - availabilityPolicy: () => ({ - processCaptureEnabled: true, - signalRecordingEnabled: true, - ...restriction, - }), - }); - try { - expect( - (await harness.availability()).find( - (tool) => tool.name === "decode_signal_recording", - ), - ).toMatchObject({ available: false, reason: "unsupported_host" }); - } finally { - await harness.close(); - } - }), -); - -it("refuses execution on the hosts that discovery reports unsupported", async () => - emulateHost("darwin", "arm64", async () => { - const harness = await connect(); - try { - for (const [name, args] of [ - ["inspect_signal_decoders", {}], - ["inspect_binary_layout", { path: harness.path("runtime.hex") }], - [ - "inspect_evm_interface", - { path: harness.path("runtime.hex"), encoding: "hex" }, - ], - ] as const) - expect(await harness.call(name, args), name).toMatchObject({ - error: { code: "capability_unavailable", retryable: false }, - }); - } finally { - await harness.close(); - } - })); diff --git a/tests/process-global/pwntoolsCleanup.test.ts b/tests/process-global/pwntoolsCleanup.test.ts index df5b0aeaa5..4105a67e2d 100644 --- a/tests/process-global/pwntoolsCleanup.test.ts +++ b/tests/process-global/pwntoolsCleanup.test.ts @@ -1,13 +1,7 @@ +import { SIMULATED_LINUX_X64 } from "../fixtures/simulatedHost.js"; import { access, readFile, writeFile } from "node:fs/promises"; import { join } from "node:path"; -import { - afterEach, - beforeAll, - beforeEach, - expect, - it, - onTestFinished, -} from "vitest"; +import { beforeAll, expect, it, onTestFinished } from "vitest"; import { PwntoolsLayoutProvider } from "../../src/native/pwntools/PwntoolsLayoutProvider.js"; import { PrivateRuntimeRoot } from "../../src/process/PrivateRuntimeRoot.js"; @@ -22,29 +16,12 @@ import { removeTestWorkspace, } from "../support/workspace/workspaceFixture.js"; -const platform = Object.getOwnPropertyDescriptor(process, "platform"); -const architecture = Object.getOwnPropertyDescriptor(process, "arch"); const supportedHost = process.platform !== "win32"; beforeAll(() => supportedHost ? prepareProcessOwnershipInspection() : undefined, ); -// Only the decoder's availability gate is simulated. The module-owned process -// inspector was created and prepared for the real host before these overrides; -// every fixture launch, output stream, cleanup signal and filesystem is real. -beforeEach(() => { - Object.defineProperty(process, "platform", { value: "linux" }); - Object.defineProperty(process, "arch", { value: "x64" }); -}); - -afterEach(() => { - if (platform !== undefined) - Object.defineProperty(process, "platform", platform); - if (architecture !== undefined) - Object.defineProperty(process, "arch", architecture); -}); - const fixture = async () => { const workspace = await createTestWorkspace("rea-pwntools-cleanup-"); onTestFinished(() => removeTestWorkspace(workspace.root)); @@ -102,6 +79,7 @@ it.runIf(supportedHost)( }, }; }, + SIMULATED_LINUX_X64, ); onTestFinished(async () => { cleanupAllowed = true; @@ -202,6 +180,7 @@ it.runIf(supportedHost)( await root.close(); }, }), + SIMULATED_LINUX_X64, ); onTestFinished(async () => { removalAllowed = true; @@ -258,6 +237,7 @@ it.runIf(supportedHost)( }, () => PrivateRuntimeRoot.create({ parent: workspace.root, prefix: "owned-" }), + SIMULATED_LINUX_X64, ); onTestFinished(async () => { release?.(); diff --git a/tests/process-global/pwntoolsCliFinalization.test.ts b/tests/process-global/pwntoolsCliFinalization.test.ts index fd707a24da..0a88c1de0f 100644 --- a/tests/process-global/pwntoolsCliFinalization.test.ts +++ b/tests/process-global/pwntoolsCliFinalization.test.ts @@ -1,15 +1,8 @@ +import { SIMULATED_LINUX_X64 } from "../fixtures/simulatedHost.js"; import { z } from "zod"; import { access, readFile, writeFile } from "node:fs/promises"; import { join } from "node:path"; -import { - afterEach, - beforeAll, - beforeEach, - expect, - it, - onTestFinished, - vi, -} from "vitest"; +import { afterEach, beforeAll, expect, it, onTestFinished, vi } from "vitest"; import { BinaryLayoutService } from "../../src/application/binaryDiagnostics/BinaryLayoutService.js"; import { createCli } from "../../src/cli.js"; @@ -34,23 +27,12 @@ import { } from "../support/workspace/workspaceFixture.js"; const supportedHost = process.platform !== "win32"; -const platform = Object.getOwnPropertyDescriptor(process, "platform"); -const architecture = Object.getOwnPropertyDescriptor(process, "arch"); const exitCode = process.exitCode; beforeAll(() => supportedHost ? prepareProcessOwnershipInspection() : undefined, ); -beforeEach(() => { - // Prepare the real host inspector first; only decoder availability is simulated. - Object.defineProperty(process, "platform", { value: "linux" }); - Object.defineProperty(process, "arch", { value: "x64" }); -}); afterEach(() => { - if (platform !== undefined) - Object.defineProperty(process, "platform", platform); - if (architecture !== undefined) - Object.defineProperty(process, "arch", architecture); process.exitCode = exitCode; vi.restoreAllMocks(); }); @@ -127,6 +109,7 @@ it.runIf(supportedHost).each(["decoded", "failed"] as const)( await root.close(); }, }), + SIMULATED_LINUX_X64, ); onTestFinished(() => provider.close()); const output = await runCli(provider, path); @@ -175,6 +158,7 @@ it.runIf(supportedHost)( }; }, async () => root, + SIMULATED_LINUX_X64, ); onTestFinished(() => provider.close()); expect(await runCli(provider, path)).toMatchObject({ @@ -214,6 +198,7 @@ it.runIf(supportedHost)( await root.close(); }, }), + SIMULATED_LINUX_X64, ); onTestFinished(async () => { removalAllowed = true; @@ -252,6 +237,7 @@ it.runIf(supportedHost)( await root.close(); }, }), + SIMULATED_LINUX_X64, ); onTestFinished(async () => { removalAllowed = true; @@ -293,6 +279,7 @@ it.runIf(supportedHost)( await root.close(); }, }), + SIMULATED_LINUX_X64, ); onTestFinished(() => provider.close()); const result = await provider.inspectAndClose( @@ -319,7 +306,12 @@ it.runIf(supportedHost).each(["inspect", "inspectAndClose"] as const)( const reason = { stage: "pre-admission" }; const controller = new AbortController(); controller.abort(reason); - const provider = new PwntoolsLayoutProvider({}); + const provider = new PwntoolsLayoutProvider( + {}, + undefined, + undefined, + SIMULATED_LINUX_X64, + ); onTestFinished(() => provider.close()); const result = await provider[method]( { path: "/not-acquired" }, @@ -347,6 +339,7 @@ it.runIf(supportedHost)( controller.abort(reason); return root; }, + SIMULATED_LINUX_X64, ); onTestFinished(() => provider.close()); const result = await provider.inspect( @@ -379,6 +372,7 @@ it.runIf(supportedHost).each(["AbortError-name", "same-as-reason"])( ); throw physical; }, + SIMULATED_LINUX_X64, ); onTestFinished(() => provider.close()); const result = await provider.inspect( @@ -416,6 +410,7 @@ it.runIf(supportedHost)( return launched; }, async () => root, + SIMULATED_LINUX_X64, ); onTestFinished(async () => { try { @@ -457,6 +452,7 @@ it.runIf(supportedHost)( await root.close(); }, }), + SIMULATED_LINUX_X64, ); onTestFinished(async () => { removalAllowed = true; diff --git a/tests/process-global/pwntoolsCliRemediation.test.ts b/tests/process-global/pwntoolsCliRemediation.test.ts index c764166a35..d8869517fa 100644 --- a/tests/process-global/pwntoolsCliRemediation.test.ts +++ b/tests/process-global/pwntoolsCliRemediation.test.ts @@ -1,5 +1,6 @@ +import { SIMULATED_LINUX_X64 } from "../fixtures/simulatedHost.js"; import { writeFile } from "node:fs/promises"; -import { afterEach, beforeEach, expect, it, onTestFinished, vi } from "vitest"; +import { afterEach, expect, it, onTestFinished, vi } from "vitest"; import { createCli } from "../../src/cli.js"; import * as composition from "../../src/composition/binaryDiagnostics.js"; @@ -12,20 +13,9 @@ import { removeTestWorkspace, } from "../support/workspace/workspaceFixture.js"; -const platform = Object.getOwnPropertyDescriptor(process, "platform"); -const architecture = Object.getOwnPropertyDescriptor(process, "arch"); const exitCode = process.exitCode; -beforeEach(() => { - // Exercise configuration admission on this host without starting Python. - Object.defineProperty(process, "platform", { value: "linux" }); - Object.defineProperty(process, "arch", { value: "x64" }); -}); afterEach(() => { - if (platform !== undefined) - Object.defineProperty(process, "platform", platform); - if (architecture !== undefined) - Object.defineProperty(process, "arch", architecture); process.exitCode = exitCode; vi.restoreAllMocks(); }); @@ -73,12 +63,24 @@ it for (const { environment, message, key } of configurations) { if (command === "inspect-binary-layout") vi.spyOn(composition, "createBinaryLayoutService").mockReturnValue( - new BinaryLayoutService(new PwntoolsLayoutProvider(environment)), + new BinaryLayoutService( + new PwntoolsLayoutProvider( + environment, + undefined, + undefined, + SIMULATED_LINUX_X64, + ), + ), ); else vi.spyOn(composition, "createRecordedCrashService").mockReturnValue( new RecordedCrashService( - new PwntoolsRecordedCrashProvider(environment), + new PwntoolsRecordedCrashProvider( + environment, + undefined, + undefined, + SIMULATED_LINUX_X64, + ), ), ); let stdout = ""; diff --git a/tests/process-global/pwntoolsStageRetirement.test.ts b/tests/process-global/pwntoolsStageRetirement.test.ts index 26047fe866..c00593398a 100644 --- a/tests/process-global/pwntoolsStageRetirement.test.ts +++ b/tests/process-global/pwntoolsStageRetirement.test.ts @@ -1,3 +1,4 @@ +import { SIMULATED_LINUX_X64 } from "../fixtures/simulatedHost.js"; import { access, lstat, @@ -8,15 +9,7 @@ import { } from "node:fs/promises"; import { join } from "node:path"; import { fileURLToPath } from "node:url"; -import { - afterEach, - beforeAll, - beforeEach, - expect, - it, - onTestFinished, - vi, -} from "vitest"; +import { afterEach, beforeAll, expect, it, onTestFinished, vi } from "vitest"; import { z } from "zod"; import { projectAnalysisError } from "../../src/domain/analysisErrorProjection.js"; import { primaryAnalysisError } from "../../src/domain/analysisErrorBase.js"; @@ -45,24 +38,13 @@ import { } from "../support/workspace/workspaceFixture.js"; const supportedHost = process.platform !== "win32"; -const platform = Object.getOwnPropertyDescriptor(process, "platform"); -const architecture = Object.getOwnPropertyDescriptor(process, "arch"); const worker = fileURLToPath( new URL("../fixtures/pwntoolsChangingArtifact.mjs", import.meta.url), ); beforeAll(() => supportedHost ? prepareProcessOwnershipInspection() : undefined, ); -beforeEach(() => { - // Use the actual host inspector; simulate only the decoder availability gate. - Object.defineProperty(process, "platform", { value: "linux" }); - Object.defineProperty(process, "arch", { value: "x64" }); -}); afterEach(() => { - if (platform !== undefined) - Object.defineProperty(process, "platform", platform); - if (architecture !== undefined) - Object.defineProperty(process, "arch", architecture); vi.restoreAllMocks(); }); @@ -177,6 +159,7 @@ it.runIf(supportedHost).each(["decoder", "debugger"] as const)( }); }, async () => root, + SIMULATED_LINUX_X64, ); onTestFinished(() => provider.close()); const result = await provider.inspectAndClose({ @@ -219,6 +202,7 @@ it.runIf(supportedHost)( }); }, async () => root, + SIMULATED_LINUX_X64, ); onTestFinished(() => provider.close()); const result = await provider.inspectAndClose({ @@ -265,6 +249,7 @@ it.runIf(supportedHost).each([ return launched; }, async () => root, + SIMULATED_LINUX_X64, ); onTestFinished(async () => { cleanupAllowed = true; @@ -349,6 +334,7 @@ it.runIf(supportedHost)( }; }, async () => root, + SIMULATED_LINUX_X64, ); onTestFinished(async () => { cleanupAllowed = true; @@ -453,6 +439,7 @@ it.runIf(supportedHost).each(["decoder", "debugger"])( }); }, async () => root, + SIMULATED_LINUX_X64, ); onTestFinished(async () => { releaseAllowed = true; @@ -591,6 +578,7 @@ it.runIf(supportedHost).each( }); }, async () => root, + SIMULATED_LINUX_X64, ); onTestFinished(async () => { releaseAllowed = true; @@ -699,6 +687,7 @@ it.runIf(supportedHost)( prefix: "operation-", }); }, + SIMULATED_LINUX_X64, ); onTestFinished(async () => { await provider.close();