mirror of
https://github.com/morluto/rea.git
synced 2026-11-16 19:53:50 +00:00
* 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
366 lines
12 KiB
TypeScript
366 lines
12 KiB
TypeScript
import { mkdir } from "node:fs/promises";
|
|
import { HOST_PLATFORM } from "../platform/HostPlatform.js";
|
|
import { dirname } from "node:path";
|
|
|
|
import {
|
|
AnalysisCleanupLeaseGroup,
|
|
ArtifactResourceScope,
|
|
} from "../resources/index.js";
|
|
import {
|
|
AnalysisCancelledError,
|
|
cancelledBy,
|
|
} from "../domain/analysisErrorCore.js";
|
|
import { analysisErrorWithCancellation } from "../domain/analysisErrorCancellation.js";
|
|
import { ConfigurationError } from "../domain/configurationErrors.js";
|
|
import { err, ok, type Result } from "../domain/result.js";
|
|
import type { ClientRegistrationCommand } from "../domain/clientRegistrationCommand.js";
|
|
import {
|
|
sameRegularFileState,
|
|
RegularFileChangedError,
|
|
} from "../filesystem/RegularFile.js";
|
|
import { writeClientRegistrationBackup } from "./ClientRegistrationBackup.js";
|
|
import { resolveClientConfigTransactionPath } from "./ClientConfigPath.js";
|
|
import {
|
|
privateProfilePermissions,
|
|
PRIVATE_PROFILE_MODES,
|
|
type PrivateProfilePermissions,
|
|
securePrivateDirectory,
|
|
} from "./ClientPrivateProfile.js";
|
|
import {
|
|
ClientConfigurationPublicationFailure,
|
|
isClientConfigurationCleanupFailure,
|
|
retryClientConfigurationCleanup,
|
|
} from "./ClientConfigurationCleanup.js";
|
|
import { clientConfigurationValuesEqual } from "./ClientConfigurationDocument.js";
|
|
import { ClientConfigurationPublication } from "./ClientConfigurationPublication.js";
|
|
import { withClientConfigurationTransaction } from "./ClientConfigurationTransaction.js";
|
|
import {
|
|
prepareRegistration,
|
|
verifyEffectiveRegistration,
|
|
} from "./McpRegistrationConfiguration.js";
|
|
import type { McpRegistrationClient } from "./McpRegistrationCatalog.js";
|
|
import {
|
|
readRegularFileText,
|
|
readRegularFileTextSnapshot,
|
|
} from "../process/RegularFileRead.js";
|
|
|
|
export interface McpClientRegistrationReceipt {
|
|
readonly status: "configured" | "unchanged";
|
|
readonly backupPath?: string;
|
|
readonly permissions?: PrivateProfilePermissions;
|
|
}
|
|
export type McpClientRegistrationFailure =
|
|
| ConfigurationError
|
|
| AnalysisCancelledError;
|
|
interface OutcomeLabels {
|
|
readonly client: McpRegistrationClient["id"];
|
|
readonly configPath: string;
|
|
readonly scope: McpRegistrationClient["scope"];
|
|
}
|
|
export type McpClientRegistrationOutcome = OutcomeLabels &
|
|
(
|
|
| {
|
|
readonly status: "completed";
|
|
readonly result: Result<
|
|
McpClientRegistrationReceipt,
|
|
McpClientRegistrationFailure
|
|
>;
|
|
}
|
|
| { readonly status: "not_started" }
|
|
);
|
|
|
|
/**
|
|
* Whether a registration's settings were published, including a failure that
|
|
* arrived after publication (for example cancellation during verification).
|
|
*/
|
|
export const mcpClientRegistrationWritten = (
|
|
result: Result<McpClientRegistrationReceipt, McpClientRegistrationFailure>,
|
|
): boolean =>
|
|
result.ok
|
|
? result.value.status === "configured"
|
|
: result.error.diagnostics?.["configured"] === true;
|
|
|
|
/** Preserve every selected client's outcome, including work never started after cancellation. */
|
|
export const registerMcpClients = async (
|
|
clients: readonly McpRegistrationClient[],
|
|
launcher: ClientRegistrationCommand,
|
|
signal: AbortSignal | undefined,
|
|
resources: ArtifactResourceScope,
|
|
/** The host the clients were resolved for; it decides document semantics. */
|
|
platform: NodeJS.Platform,
|
|
): Promise<readonly McpClientRegistrationOutcome[]> => {
|
|
const outcomes: McpClientRegistrationOutcome[] = [];
|
|
let cancelled = false;
|
|
for (const client of clients) {
|
|
const labels = {
|
|
client: client.id,
|
|
configPath: client.configPath,
|
|
scope: client.scope,
|
|
};
|
|
if (cancelled) {
|
|
outcomes.push({ ...labels, status: "not_started" });
|
|
continue;
|
|
}
|
|
const result = await registerMcpClient(
|
|
client,
|
|
launcher,
|
|
signal,
|
|
resources,
|
|
platform,
|
|
);
|
|
outcomes.push({ ...labels, status: "completed", result });
|
|
cancelled =
|
|
signal?.aborted === true ||
|
|
(!result.ok && result.error instanceof AnalysisCancelledError);
|
|
}
|
|
return outcomes;
|
|
};
|
|
|
|
const isMissing = (cause: unknown): boolean =>
|
|
cause instanceof Error && "code" in cause && cause.code === "ENOENT";
|
|
|
|
/** One selected document owner admits, merges and verifies exact launcher facts. */
|
|
export const registerMcpClient = async (
|
|
client: McpRegistrationClient,
|
|
launcher: ClientRegistrationCommand,
|
|
signal: AbortSignal | undefined,
|
|
resources: ArtifactResourceScope,
|
|
platform: NodeJS.Platform,
|
|
): Promise<
|
|
Result<McpClientRegistrationReceipt, McpClientRegistrationFailure>
|
|
> => {
|
|
const settingsPath = client.configPath;
|
|
let backupPath: string | undefined;
|
|
let configured = false;
|
|
const checkCancellation = (): void => {
|
|
if (signal?.aborted === true)
|
|
throw cancelledBy("MCP registration", signal, {
|
|
diagnostics: {
|
|
client: client.id,
|
|
settings_path: settingsPath,
|
|
configured,
|
|
...(backupPath === undefined ? {} : { backup_path: backupPath }),
|
|
},
|
|
});
|
|
};
|
|
try {
|
|
checkCancellation();
|
|
// The caller supplies canonical argv, not a native client-shaped entry.
|
|
if (launcher.command.length === 0)
|
|
throw new ConfigurationError(
|
|
"The registration needs a nonempty executable.",
|
|
);
|
|
const path = await resolveClientConfigTransactionPath(settingsPath);
|
|
if (path === undefined)
|
|
throw new ConfigurationError(
|
|
`Client settings path could not be verified: ${settingsPath}`,
|
|
);
|
|
return await withClientConfigurationTransaction(path, async () => {
|
|
checkCancellation();
|
|
const prepared = await prepareRegistration(
|
|
path,
|
|
client,
|
|
launcher,
|
|
platform,
|
|
);
|
|
const { snapshot, original, contents } = prepared;
|
|
checkCancellation();
|
|
const unchanged = await unchangedRegistration(
|
|
prepared,
|
|
checkCancellation,
|
|
resources,
|
|
);
|
|
checkCancellation();
|
|
if (unchanged !== undefined) return ok(unchanged);
|
|
if (original !== undefined) {
|
|
const backup = await writeClientRegistrationBackup(path, original);
|
|
if (!backup.ok)
|
|
throw new ConfigurationError(backup.error.detail, {
|
|
diagnostics: {
|
|
settings_path: settingsPath,
|
|
backup_path: backup.error.path,
|
|
},
|
|
});
|
|
backupPath = backup.value;
|
|
}
|
|
checkCancellation();
|
|
await mkdir(dirname(path), {
|
|
recursive: true,
|
|
...(client.privateProfile !== undefined
|
|
? { mode: PRIVATE_PROFILE_MODES.directory }
|
|
: {}),
|
|
});
|
|
checkCancellation();
|
|
if (
|
|
client.privateProfile !== undefined &&
|
|
HOST_PLATFORM.platform !== "win32"
|
|
)
|
|
await securePrivateDirectory(
|
|
dirname(path),
|
|
client.privateProfile.home,
|
|
checkCancellation,
|
|
resources,
|
|
);
|
|
checkCancellation();
|
|
const publication = await ClientConfigurationPublication.write(
|
|
path,
|
|
contents,
|
|
original,
|
|
{
|
|
requestedPath: settingsPath,
|
|
state: snapshot?.state,
|
|
...(client.privateProfile !== undefined
|
|
? { requiredMode: PRIVATE_PROFILE_MODES.file }
|
|
: {}),
|
|
},
|
|
);
|
|
// Cancellation cannot abandon published bytes, verification or retained cleanup.
|
|
await verifyRegistration(publication, prepared, backupPath, resources);
|
|
configured = true;
|
|
checkCancellation();
|
|
return ok({
|
|
status: "configured",
|
|
...(backupPath === undefined ? {} : { backupPath }),
|
|
...(client.privateProfile !== undefined
|
|
? { permissions: privateProfilePermissions(HOST_PLATFORM.platform) }
|
|
: {}),
|
|
});
|
|
});
|
|
} catch (cause: unknown) {
|
|
if (cause instanceof AnalysisCancelledError) return err(cause);
|
|
configured ||=
|
|
cause instanceof ClientConfigurationPublicationFailure &&
|
|
cause.outcome.kind === "completed";
|
|
const failure = await registrationFailure(cause, settingsPath, resources, {
|
|
backupPath,
|
|
configured,
|
|
});
|
|
if (signal?.aborted === true)
|
|
analysisErrorWithCancellation(
|
|
failure,
|
|
cancelledBy("MCP registration", signal),
|
|
);
|
|
return err(failure);
|
|
}
|
|
};
|
|
|
|
const registrationFailure = async (
|
|
cause: unknown,
|
|
path: string,
|
|
resources: ArtifactResourceScope,
|
|
progress: {
|
|
readonly backupPath: string | undefined;
|
|
readonly configured: boolean;
|
|
},
|
|
): Promise<ConfigurationError> => {
|
|
const { backupPath, configured } = progress;
|
|
if (cause instanceof ConfigurationError) return cause;
|
|
const cleanup = isClientConfigurationCleanupFailure(cause)
|
|
? await retryClientConfigurationCleanup(cause, resources)
|
|
: undefined;
|
|
const primary = cleanup?.primary ?? cause;
|
|
const detail = primary instanceof Error ? primary.message : String(primary);
|
|
const error = new ConfigurationError(
|
|
`Could not register MCP settings at ${path}: ${detail}`,
|
|
{
|
|
cause,
|
|
...(cleanup?.cleanup === undefined ? {} : { cleanup: cleanup.cleanup }),
|
|
diagnostics: {
|
|
settings_path: path,
|
|
configured,
|
|
...(backupPath === undefined ? {} : { backup_path: backupPath }),
|
|
},
|
|
},
|
|
);
|
|
if (cleanup !== undefined)
|
|
new AnalysisCleanupLeaseGroup(error, cleanup.cleanupLeases);
|
|
return error;
|
|
};
|
|
|
|
/** A semantic no-op is usable only while the admitted physical snapshot remains current. */
|
|
const unchangedRegistration = async (
|
|
prepared: Awaited<ReturnType<typeof prepareRegistration>>,
|
|
checkCancellation: () => void,
|
|
resources: ArtifactResourceScope,
|
|
): Promise<McpClientRegistrationReceipt | undefined> => {
|
|
const { client, path, snapshot, parsed, updated } = prepared;
|
|
if (
|
|
parsed.requiresRewrite === true ||
|
|
!clientConfigurationValuesEqual(parsed.document, updated) ||
|
|
(client.privateProfile !== undefined &&
|
|
HOST_PLATFORM.platform !== "win32" &&
|
|
((snapshot?.state.mode ?? 0) & 0o777) !== PRIVATE_PROFILE_MODES.file)
|
|
)
|
|
return undefined;
|
|
const current = await readRegularFileTextSnapshot(path, {
|
|
symlinks: "reject",
|
|
});
|
|
if (
|
|
snapshot === undefined ||
|
|
current.text !== snapshot.text ||
|
|
!sameRegularFileState(snapshot.state, current.state)
|
|
)
|
|
throw new RegularFileChangedError(path);
|
|
checkCancellation();
|
|
await verifyEffectiveRegistration(prepared, current.text);
|
|
const permissionsChanged =
|
|
client.privateProfile !== undefined && HOST_PLATFORM.platform !== "win32"
|
|
? await securePrivateDirectory(
|
|
dirname(path),
|
|
client.privateProfile.home,
|
|
checkCancellation,
|
|
resources,
|
|
)
|
|
: false;
|
|
return {
|
|
status: permissionsChanged ? "configured" : "unchanged",
|
|
...(client.privateProfile !== undefined
|
|
? { permissions: privateProfilePermissions(HOST_PLATFORM.platform) }
|
|
: {}),
|
|
};
|
|
};
|
|
|
|
const verifyRegistration = async (
|
|
publication: ClientConfigurationPublication,
|
|
prepared: Awaited<ReturnType<typeof prepareRegistration>>,
|
|
backupPath: string | undefined,
|
|
resources: ArtifactResourceScope,
|
|
): Promise<void> => {
|
|
const { original, client } = prepared;
|
|
const settingsPath = client.configPath;
|
|
await publication.verify(async () => {
|
|
try {
|
|
const readback = await readRegularFileText(publication.path, {
|
|
symlinks: "reject",
|
|
});
|
|
await publication.assertCurrent(readback);
|
|
await verifyEffectiveRegistration(prepared, readback);
|
|
} catch (cause: unknown) {
|
|
if (cause instanceof RegularFileChangedError || isMissing(cause))
|
|
throw cause;
|
|
const failure = await registrationFailure(
|
|
cause,
|
|
settingsPath,
|
|
resources,
|
|
{ backupPath, configured: false },
|
|
);
|
|
try {
|
|
await publication.restore(original);
|
|
} catch (rollbackCause: unknown) {
|
|
throw new ConfigurationError(
|
|
"Client settings verification failed and restoration could not be verified",
|
|
{
|
|
cause: rollbackCause,
|
|
cleanupPrimary: failure,
|
|
diagnostics: {
|
|
settings_path: settingsPath,
|
|
...(backupPath === undefined ? {} : { backup_path: backupPath }),
|
|
},
|
|
},
|
|
);
|
|
}
|
|
throw failure;
|
|
}
|
|
});
|
|
};
|