Files
reverse-engineering-anything/src/composition/capabilityServices.ts
T
bartman081523andmorluto d380dc2409 feat(uefi): add pure-TypeScript UEFI firmware analysis tools (#12342)
* feat(uefi): add pure-TS UEFI firmware volume/FFS parser with inspect/extract tools

Add a dependency-free rea-uefi provider that maps AMI/Aptio flash images:
- inspect_uefi_firmware: aligned _FVH discovery, volume-relative FFS walking,
  guided section/compression classification, conservative PSP-directory probing,
  embedded-volume rescan and leftover-region classification; incremental SHA-256
  and explicit integrity notes.
- extract_uefi_firmware: whole-image/volume/FFS-file/section extraction with
  LZMA-custom/LZMAF86 and AMD-zlib decoding, SafeOutputTree staging, derivations
  and extraction_gaps.
- UefiArtifactReader + 'uefi' format wiring across inventory/domain/contracts
  so parsed volumes and extracted PE32/TE files hand off to deep-provider
  analysis (open_binary -> Ghidra).

* feat(uefi): add inspect_uefi_nvram for AMI NVRAM variable stores

Add a pure-TypeScript tool that maps the vendor AMI NVRAM variable stores
(factory-default "StdDefaults" and peers) inside a flash image:
- scan the raw image for NVAR entry chains ("NVAR" + u16 total size +
  u32 attribute 0x8[23]FFFFFF + state + NUL-terminated name + data),
- recurse into a container entry whose data is itself an NVAR chain, so the
  StdDefaults setup variables surface as depth/parent_offset rows,
- report attributes, state, data range, SHA-256 and trailing padding per entry.

Verified against B550 AORUS Elite V2 FId: one StdDefaults store at 0x37090 with
the 11 expected nested variables (Setup, PlatformLang, AMITSESetup, XhciDID,
GcSensorVarName, PCI_COMMON, SioSetupData, UsbSupport, NetworkStackVar,
SecureBootSetup, Setup). Exposed as MCP tool and inspect-uefi-nvram CLI command.

* fix(uefi): address review on checksums, compression, guided sections, NVRAM bounds

- FFS file checksum: verify the two's-complement invariant (payload sum +
  stored byte == 0 mod 256) instead of comparing sums, and encode the correct
  complement in the fixture builder.
- Compression sections (type 0x01): use the 9-byte header and classify EFI
  standard compression instead of 'none', so extraction reports a gap rather
  than publishing compressed bytes as a raw section.
- GUID-defined sections: derive GUID/data-offset/attributes from the parsed
  common header size (compact or extended) and reject out-of-range payload
  offsets.
- AMI NVRAM: bound recursive chains to the enclosing container's data end and
  report partial coverage when a valid nested chain is cut by max_depth.

* fix(uefi): bound decode memory, serialize operations, enforce deadline, mark truncation

- LZMA worker: enforce max_output_bytes while decoding through a bounded output
  sink, so an oversized stream is rejected during expansion instead of after a
  full decompression plus a second Buffer copy.
- Provider: serialize admitted operations (the promised single decode-worker
  lane must not become one worker per overlapping call) and apply one
  whole-request deadline that covers every decode stage, not a fresh per-stream
  timer. close() drains the queue and the resource scope.
- Scan: track truncated sections of known type and report coverage partial
  instead of complete when a section declares more bytes than are present.

* fix(uefi): cancellable queue, timeout surfacing, availability and reader omissions

- Queue: check the caller signal before enqueue and when a job reaches the head,
  and race the queued promise against abort so a cancelled wait returns
  immediately instead of blocking behind the active request.
- Deadline: track the internal deadline and return AnalysisTimeoutError instead
  of the AnalysisCancelledError that runOwnedCommand reports for any external
  abort, preserving the real failure reason for CLI/MCP callers.
- CapabilityInventory: treat inspect_uefi_nvram like the other bundled rea-uefi
  tools so discovery does not demand Unblob for it.
- UefiArtifactReader: report image truncation through onOmission so inventory
  coverage reflects the unread suffix even when no volume was found.

* fix(uefi): limit early cancellation to unstarted jobs and preserve timeout cleanup

- #raceWithAbort only returns early for jobs that have not started; once a
  request is running, await it so worker cleanup and completed output are
  preserved instead of being discarded by a bare cancellation.
- Reclassify a deadline-induced cancellation as AnalysisTimeoutError while
  keeping its cause and cleanup observations, and never override a different
  primary failure.

* docs(licenses): record UEFI decoder dependency notices

* fix(uefi): preserve stream provenance and bound firmware analysis

* feat(uefi): decode LZMAF86 guided sections

* fix(uefi): validate publication before commit and order decoder cleanup

* fix(uefi): preserve unsupported volumes and extraction gaps

---------

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
2026-11-19 21:19:35 +00:00

750 lines
29 KiB
TypeScript

import { UefiAnalysisService } from "../application/uefi/UefiAnalysisService.js";
import type { UefiAnalysisPort } from "../ports/uefi/UefiAnalysisPort.js";
import { createUefiAnalysisProvider } from "./uefi.js";
import type { OptionalProviderLoadFailures } from "../ports/OptionalObservationProviders.js";
import {
locateWiresharkTool,
selectWiresharkTool,
} from "../pcap/PcapConfiguration.js";
import type { AnalysisSettingsReader } from "../domain/analysisSettings.js";
import { CapabilityScope } from "../application/CapabilityScope.js";
import type { CapabilityAvailabilityFacts } from "../application/CapabilityAvailability.js";
import {
CAPABILITY_DECLARATIONS,
type CapabilityDeclarationId,
} from "./capabilityDeclarations.js";
import { isAbsolute } from "node:path";
import { createGpuCodeObjectsService } from "./gpu.js";
import { createPacketCaptureService } from "./captures.js";
import { tsharkHostSupported } from "../captures/TsharkCaptureProvider.js";
import { createSignalRecordingService } from "./signals.js";
import { sigrokHostSupported } from "../signals/SigrokRecordingProvider.js";
import { wasmArtifactModule } from "./wasm.js";
import { apkSignatureModule } from "./apkSignature.js";
import { evmInterfaceModule } from "./evm.js";
import {
evmHostSupported,
evmLimiterAvailability,
} from "../evm/EvmoleInterfaceProvider.js";
import { createSqliteDatabaseService } from "./sqlite.js";
import { createDesktopApplicationService } from "./desktop.js";
import { DesktopBuildComputers } from "../application/desktop/DesktopBuildComputers.js";
import { readHostFile } from "../desktop/HostFileRead.js";
import { createGoBinaryService } from "./go.js";
import { createRustBinaryService } from "./rust.js";
import { createBeamService } from "./erlang.js";
import { createV8CodeCacheService } from "./v8CodeCache.js";
import { createMavenGradleMetadataService } from "./mavenGradleMetadata.js";
import { createModelArtifactService } from "./model.js";
import { createIl2cppMetadataService } from "./il2cpp.js";
import { createElectronFuseService } from "./electronFuses.js";
import { createReleaseExposureService } from "./releaseExposure.js";
import { createPythonPycService } from "./pythonPyc.js";
import { createNugetNupkgService } from "./nugetNupkg.js";
import { createWebNetworkCaptureService } from "./webNetworkCaptures.js";
import { createWebSourceLocationService } from "./webSourceLocations.js";
import { createWebModuleTraceService } from "./webModules.js";
import { createWebRuntimeService } from "./webRuntime.js";
import { createJavaScriptRecoveryProvider } from "./javascriptRecovery.js";
import { wakaruHostSupported } from "../javascript/recovery/WakaruCommand.js";
import { ArtifactResourceScope } from "../resources/index.js";
import { createReverseEngineeringService } from "./reverseEngineering.js";
import type {
ReverseEngineeringService,
CommandProviderLaunchFailures,
} from "../application/reverse/ReverseEngineeringService.js";
import { FirmwareAnalysisService } from "../application/firmware/FirmwareAnalysisService.js";
import { createFirmwareAnalysisProvider } from "./firmware.js";
import { firmwareHostSupported } from "../firmware/FirmwareCommand.js";
import { createAndroidAnalysisProvider } from "./android.js";
import { createPcapAnalysisProvider } from "./pcap.js";
import { createFlutterBuildAnalysisProvider } from "./flutter.js";
import { createApktoolResourceAnalysisProvider } from "./apktool.js";
import { createJebAnalysisProvider } from "./jeb.js";
import { createAdbDeviceAnalysisProvider } from "./adb.js";
import { createFridaInstrumentationProvider } from "./frida.js";
import { createCutterBridgeService } from "./cutter.js";
import {
createGdbSessionManager,
createRizinDebugSessionManager,
} from "./debuggerSessions.js";
import { persistentDebuggerHostSupported } from "../process/PersistentDebuggerHost.js";
import { pcapCaptureHostSupported } from "../domain/pcap/pcapAnalysis.js";
import {
createPeLoadConfigService,
createBinaryHardeningService,
createPeCertificatesService,
createPeImportsService,
createNativeExportsService,
createPeResourcesService,
createWindowsShortcutService,
createRecordedCrashService,
createBinaryLayoutService,
createDevicetreeService,
createElfNotesService,
createDwarfUnitsService,
createElfDebugLinkService,
createNativeInitializersService,
createElfUnwindRangesService,
createAppleIpsService,
createKernelModuleService,
createElfDependenciesService,
createKernelBuildConfigService,
} from "./binaryDiagnostics.js";
import { pwntoolsHostSupported } from "../native/pwntools/PwntoolsDecoder.js";
import type { PacketCaptureService } from "../application/captures/PacketCaptureService.js";
import type { SignalRecordingService } from "../application/signals/SignalRecordingService.js";
import type { WasmArtifactService } from "../application/wasm/WasmArtifactService.js";
import type { ApkSignatureService } from "../application/apkSignature/ApkSignatureService.js";
import type { EvmInterfaceService } from "../application/evm/EvmInterfaceService.js";
import type { SqliteDatabaseService } from "../application/sqlite/SqliteDatabaseService.js";
import type { Il2cppMetadataService } from "../application/il2cpp/Il2cppMetadataService.js";
import type { GoBinaryService } from "../application/go/GoBinaryService.js";
import type { ElectronFuseService } from "../application/electron/ElectronFuseService.js";
import type { RustBinaryService } from "../application/rust/RustBinaryService.js";
import type { PythonPycService } from "../application/python/PythonPycService.js";
import type { NugetNupkgService } from "../application/nuget/NugetNupkgService.js";
import type { BeamService } from "../application/erlang/BeamService.js";
import type { V8CodeCacheService } from "../application/v8CodeCache/V8CodeCacheService.js";
import type { MavenGradleMetadataService } from "../application/java/MavenGradleMetadataService.js";
import type { RecordedCrashService } from "../application/binaryDiagnostics/RecordedCrashService.js";
import type { BinaryLayoutService } from "../application/binaryDiagnostics/BinaryLayoutService.js";
import type { BrowserObservationPort } from "../ports/BrowserObservationPort.js";
import type { BrowserScenarioCapturePort } from "../ports/BrowserScenarioCapturePort.js";
import type { ElectronActiveObservationPort } from "../ports/javascript/ElectronActiveObservationPort.js";
import type { ElectronObservationPort } from "../ports/javascript/ElectronObservationPort.js";
import type { JavaScriptRuntimeObservationPort } from "../ports/javascript/JavaScriptRuntimeObservationPort.js";
import type { FridaInstrumentationPort } from "../ports/frida/FridaInstrumentationPort.js";
import type { WebModuleTraceService } from "../application/WebModuleTraceService.js";
import type { WebSourceLocationService } from "../application/WebSourceLocationService.js";
import type { WebRuntimeService } from "../application/WebRuntimeService.js";
import type { WebNetworkCaptureService } from "../application/WebNetworkCaptureService.js";
import type { JavaScriptRecoveryPort } from "../ports/javascript/JavaScriptRecoveryPort.js";
import type { FirmwareAnalysisPort } from "../ports/firmware/FirmwareAnalysisPort.js";
import type { AndroidAnalysisPort } from "../ports/android/AndroidAnalysisPort.js";
import type { ApktoolResourceAnalysisPort } from "../application/apktool/ApktoolResourceAnalysisPort.js";
import type { PcapAnalysisPort } from "../application/pcap/PcapAnalysisPort.js";
import type { FlutterBuildAnalysisPort } from "../application/flutter/FlutterBuildAnalysisPort.js";
import type { JebAnalysisPort } from "../ports/jeb/JebAnalysisPort.js";
import type { AdbDeviceAnalysisPort } from "../application/adb/AdbDeviceAnalysisPort.js";
import type { BuildSettle } from "../application/desktop/DesktopBuildSettle.js";
import type { BuildComputerDefaults } from "../desktop/BuildComputerEnvironment.js";
import type { ComputerStartTiming } from "../desktop/AgentEnvComputer.js";
/** Typed injection inputs shared by a capability host, independent of transport. */
export interface CapabilityServiceOptions {
readonly packetCapture?: PacketCaptureService;
readonly signalRecording?: SignalRecordingService;
readonly wasmArtifact?: WasmArtifactService;
readonly apkSignature?: ApkSignatureService;
readonly evmInterface?: EvmInterfaceService;
readonly sqliteDatabase?: SqliteDatabaseService;
readonly binaryLayout?: BinaryLayoutService;
readonly goBinary?: GoBinaryService;
readonly il2cppMetadata?: Il2cppMetadataService;
readonly rustBinary?: RustBinaryService;
readonly pythonPyc?: PythonPycService;
readonly nugetNupkg?: NugetNupkgService;
readonly erlangBeam?: BeamService;
readonly v8CodeCache?: V8CodeCacheService;
readonly mavenGradleMetadata?: MavenGradleMetadataService;
readonly electronFuses?: ElectronFuseService;
readonly recordedCrash?: RecordedCrashService;
readonly uefiAnalysis?: UefiAnalysisPort;
readonly firmwareAnalysis?: FirmwareAnalysisPort;
readonly javascriptRecovery?: JavaScriptRecoveryPort;
readonly webModuleTrace?: WebModuleTraceService;
readonly webSourceLocation?: WebSourceLocationService;
readonly webRuntime?: WebRuntimeService;
readonly webNetworkCapture?: WebNetworkCaptureService;
readonly androidAnalysis?: AndroidAnalysisPort;
readonly apktoolAnalysis?: ApktoolResourceAnalysisPort;
readonly pcapAnalysis?: PcapAnalysisPort;
readonly flutterAnalysis?: FlutterBuildAnalysisPort;
readonly jebAnalysis?: JebAnalysisPort;
readonly adbDeviceAnalysis?: AdbDeviceAnalysisPort;
readonly browserObservation?: BrowserObservationPort;
readonly browserScenarioCapture?: BrowserScenarioCapturePort;
readonly electronObservation?: ElectronObservationPort;
readonly optionalObservationProviderOwner?: "server" | "caller";
readonly optionalProviderLoadFailures?: OptionalProviderLoadFailures;
readonly electronActiveObservation?: ElectronActiveObservationPort;
readonly javascriptRuntimeObservation?: JavaScriptRuntimeObservationPort;
readonly fridaInstrumentation?: FridaInstrumentationPort;
/** How build computers read an app until its files settle; the shipped timing on real time unless a test shortens or clocks it. */
readonly desktopBuildSettle?: BuildSettle;
/** Where build computers look for unset settings; the host's PATH and REA cache unless a test isolates them. */
readonly desktopBuildDefaults?: BuildComputerDefaults;
/** How long a build computer waits for its desktop to draw and how often its start reports progress; the shipped timing unless a test shortens it. */
readonly desktopBuildStartTiming?: ComputerStartTiming;
readonly reverseEngineering?: ReverseEngineeringService;
}
const tsharkLocatable = (environment: Readonly<NodeJS.ProcessEnv>): boolean => {
try {
return (
locateWiresharkTool(
selectWiresharkTool(environment, "tshark"),
environment,
) !== undefined
);
} catch {
// A relative REA_TSHARK_COMMAND is configuration the tool reports at execution.
return false;
}
};
export interface CapabilityHostContext {
readonly environment: Readonly<NodeJS.ProcessEnv>;
readonly providerEnvironment: Readonly<NodeJS.ProcessEnv>;
readonly settings: AnalysisSettingsReader;
readonly options: CapabilityServiceOptions;
readonly platform: NodeJS.Platform;
readonly arch: NodeJS.Architecture;
}
interface CapabilityInstance<Value> {
readonly value: Value;
readonly close: () => Promise<void>;
readonly ownership: "host" | "caller";
readonly availability?: CapabilityAvailabilityFacts;
}
const capability =
<Value>(
create: (context: CapabilityHostContext) => Value,
close: (value: Value) => Promise<void>,
observe?: (
context: CapabilityHostContext,
value: Value,
) => CapabilityAvailabilityFacts,
ownership: (context: CapabilityHostContext) => "host" | "caller" = () =>
"host",
) =>
(context: CapabilityHostContext): CapabilityInstance<Value> => {
const value = create(context);
return {
value,
close: () => close(value),
ownership: ownership(context),
...(observe === undefined
? {}
: { availability: observe(context, value) }),
};
};
const service = <Value extends { close(): Promise<void> }>(
create: (context: CapabilityHostContext) => Value,
observe?: (
context: CapabilityHostContext,
value: Value,
) => CapabilityAvailabilityFacts,
) => capability(create, (value) => value.close(), observe);
const outsideHost = (injected: unknown, supported: boolean): boolean =>
injected === undefined && !supported;
const configuredPwntools = (context: CapabilityHostContext): boolean =>
pwntoolsHostSupported(context.platform, context.arch) &&
isAbsolute(context.environment.REA_PWNTOOLS_PYTHON ?? "");
const sharedObservationOwnership = (context: CapabilityHostContext) =>
context.options.optionalObservationProviderOwner === "caller"
? "caller"
: "host";
const closeObservation = (value: { close?: () => Promise<void> } | undefined) =>
value?.close?.() ?? Promise.resolve();
/** Each entry binds construction, ownership and observed availability once. */
const modules = {
wasmArtifact: service(
({ environment, options, settings }) =>
wasmArtifactModule.create(environment, options.wasmArtifact, settings),
({ environment, options }) => ({
optionalFeatures: {
wasmArtifactEnabled:
options.wasmArtifact !== undefined ||
isAbsolute(environment.REA_WABT_BIN_DIRECTORY ?? ""),
},
}),
),
apkSignature: service(({ environment, options }) =>
apkSignatureModule.create(environment, options.apkSignature),
),
evmInterface: service(
({ environment, options, platform, arch }) =>
options.evmInterface ??
evmInterfaceModule.create(environment, { platform, architecture: arch }),
({ environment, options, platform, arch }) => ({
hostUnsupported: {
evmInterface: outsideHost(
options.evmInterface,
evmHostSupported(platform, arch),
),
},
optionalFeatures: {
evmInterfaceEnabled:
options.evmInterface !== undefined ||
evmHostSupported(platform, arch),
},
...(options.evmInterface !== undefined ||
!evmHostSupported(platform, arch)
? {}
: {
probes: {
evmLimiterAvailability: (signal: AbortSignal) =>
evmLimiterAvailability(environment, { platform, arch, signal }),
},
}),
}),
),
sqliteDatabase: service(
({ environment, options }) =>
options.sqliteDatabase ?? createSqliteDatabaseService(environment),
),
binaryLayout: service(
({ environment, options, platform, arch }) =>
options.binaryLayout ??
createBinaryLayoutService(environment, { platform, architecture: arch }),
(context) => ({
hostUnsupported: {
binaryLayout: outsideHost(
context.options.binaryLayout,
pwntoolsHostSupported(context.platform, context.arch),
),
},
optionalFeatures: {
binaryLayoutEnabled:
context.options.binaryLayout !== undefined ||
configuredPwntools(context),
},
}),
),
recordedCrash: service(
({ environment, options, platform, arch }) =>
options.recordedCrash ??
createRecordedCrashService(environment, {
platform,
architecture: arch,
}),
(context) => ({
hostUnsupported: {
recordedCrash: outsideHost(
context.options.recordedCrash,
pwntoolsHostSupported(context.platform, context.arch),
),
},
optionalFeatures: {
recordedCrashEnabled:
context.options.recordedCrash !== undefined ||
configuredPwntools(context),
},
}),
),
webSourceLocation: service(
({ environment, options }) =>
options.webSourceLocation ?? createWebSourceLocationService(environment),
),
webModuleTrace: service(
({ environment, options }) =>
options.webModuleTrace ?? createWebModuleTraceService(environment),
({ environment, options }) => ({
optionalFeatures: {
webModuleResolutionEnabled:
options.webModuleTrace !== undefined ||
isAbsolute(environment.REA_BROWSER_EXECUTABLE ?? ""),
},
}),
),
desktopApplication: service(() => createDesktopApplicationService()),
desktopBuildComputers: capability(
({ providerEnvironment, options }) =>
new DesktopBuildComputers(
providerEnvironment,
readHostFile,
options.desktopBuildSettle,
options.desktopBuildDefaults,
options.desktopBuildStartTiming,
),
(value) => value.closeAll(),
),
goBinary: service(
({ options }) => options.goBinary ?? createGoBinaryService(),
),
rustBinary: service(
({ options }) => options.rustBinary ?? createRustBinaryService(),
),
erlangBeam: service(
({ options }) => options.erlangBeam ?? createBeamService(),
),
v8CodeCache: service(
({ options }) => options.v8CodeCache ?? createV8CodeCacheService(),
),
mavenGradleMetadata: service(
({ options }) =>
options.mavenGradleMetadata ?? createMavenGradleMetadataService(),
),
modelArtifact: service(() => createModelArtifactService()),
gpuCodeObjects: service(() => createGpuCodeObjectsService()),
il2cppMetadata: service(
({ options }) => options.il2cppMetadata ?? createIl2cppMetadataService(),
),
peResources: service(() => createPeResourcesService()),
nativeExports: service(() => createNativeExportsService()),
devicetree: service(() => createDevicetreeService()),
elfNotes: service(() => createElfNotesService()),
dwarfUnits: service(() => createDwarfUnitsService()),
elfDebugLink: service(() => createElfDebugLinkService()),
nativeInitializers: service(() => createNativeInitializersService()),
elfUnwindRanges: service(() => createElfUnwindRangesService()),
appleIps: service(() => createAppleIpsService()),
kernelModule: service(() => createKernelModuleService()),
elfDependencies: service(() => createElfDependenciesService()),
kernelBuildConfig: service(() => createKernelBuildConfigService()),
peLoadConfig: service(() => createPeLoadConfigService()),
binaryHardening: service(() => createBinaryHardeningService()),
peCertificates: service(() => createPeCertificatesService()),
peImports: service(() => createPeImportsService()),
windowsShortcut: service(() => createWindowsShortcutService()),
electronFuses: service(
({ options }) => options.electronFuses ?? createElectronFuseService(),
),
releaseExposure: service(({ environment, settings }) =>
createReleaseExposureService(environment, settings),
),
pythonPyc: service(
({ options }) => options.pythonPyc ?? createPythonPycService(),
),
nugetNupkg: service(
({ options }) => options.nugetNupkg ?? createNugetNupkgService(),
),
webNetworkCapture: service(
({ environment, options, settings }) =>
options.webNetworkCapture ??
createWebNetworkCaptureService(environment, settings),
),
javascriptRecovery: capability(
({ environment, options, platform, arch }) =>
options.javascriptRecovery ??
createJavaScriptRecoveryProvider(environment, undefined, {
platform,
architecture: arch,
}),
(value) => value.close?.() ?? Promise.resolve(),
({ environment, options, platform, arch }) => ({
hostUnsupported: {
javascriptRecovery: outsideHost(
options.javascriptRecovery,
wakaruHostSupported(platform, arch),
),
},
optionalFeatures: {
javascriptRecoveryEnabled:
options.javascriptRecovery !== undefined ||
(wakaruHostSupported(platform, arch) &&
isAbsolute(environment.REA_WAKARU_COMMAND ?? "")),
},
}),
),
artifactResources: service(() => new ArtifactResourceScope()),
reverseEngineering: service(
({ providerEnvironment, options }) =>
options.reverseEngineering ??
createReverseEngineeringService(providerEnvironment),
(_context, value) => ({
observeCommandProviderFailures: () => value.observedLaunchFailures(),
}),
),
firmwareAnalysis: service(
({ environment, options, platform, arch }) =>
new FirmwareAnalysisService(
options.firmwareAnalysis ??
createFirmwareAnalysisProvider(environment, undefined, {
platform,
architecture: arch,
}),
),
({ environment, options, platform }) => ({
hostUnsupported: {
firmwareInspection: outsideHost(
options.firmwareAnalysis,
firmwareHostSupported(platform),
),
firmwareExtraction: outsideHost(
options.firmwareAnalysis,
firmwareHostSupported(platform),
),
},
optionalFeatures: {
firmwareInspectionEnabled:
options.firmwareAnalysis !== undefined ||
(firmwareHostSupported(platform) &&
isAbsolute(environment.REA_BINWALK_COMMAND ?? "")),
firmwareExtractionEnabled:
options.firmwareAnalysis !== undefined ||
(firmwareHostSupported(platform) &&
isAbsolute(environment.REA_UNBLOB_COMMAND ?? "")),
},
}),
),
uefiAnalysis: service(
({ options }) =>
new UefiAnalysisService(
options.uefiAnalysis ?? createUefiAnalysisProvider(),
),
),
gdbSessions: capability(
({ providerEnvironment, platform }) =>
createGdbSessionManager(providerEnvironment, { platform }),
(value) => value.closeAll(),
({ platform }) => ({
hostUnsupported: {
persistentDebugger: !persistentDebuggerHostSupported(platform),
},
}),
),
rizinDebugSessions: capability(
({ providerEnvironment, platform }) =>
createRizinDebugSessionManager(providerEnvironment, { platform }),
(value) => value.closeAll(),
),
android: service(
({ environment, options, settings }) =>
options.androidAnalysis ??
createAndroidAnalysisProvider(environment, undefined, settings),
(_context, value) => ({
probes: {
androidAnalysisAvailability: (signal: AbortSignal) =>
value.inspectAvailability(signal),
},
}),
),
pcap: service(
({ environment, options, platform }) =>
options.pcapAnalysis ?? createPcapAnalysisProvider(environment, platform),
({ options, platform }) => ({
hostUnsupported: {
pcapCapture: outsideHost(
options.pcapAnalysis,
pcapCaptureHostSupported(platform),
),
},
}),
),
flutter: service(
({ options }) =>
options.flutterAnalysis ?? createFlutterBuildAnalysisProvider(),
),
fridaInstrumentation: capability(
({ options }) =>
options.fridaInstrumentation ?? createFridaInstrumentationProvider(),
(value) => value.closeAll(),
({ options }, value) => ({
observeProviderLoadFailures: () => {
const failure =
options.optionalProviderLoadFailures?.fridaInstrumentation ??
value.availabilityFailure?.();
return failure === undefined ? {} : { fridaInstrumentation: failure };
},
}),
),
packetCapture: service(
({ environment, options, platform }) =>
options.packetCapture ??
createPacketCaptureService(environment, platform),
({ environment, options, platform }) => ({
hostUnsupported: {
packetCapture: outsideHost(
options.packetCapture,
tsharkHostSupported(platform),
),
},
optionalFeatures: {
packetCaptureEnabled:
options.packetCapture !== undefined ||
(tsharkHostSupported(platform) && tsharkLocatable(environment)),
},
}),
),
signalRecording: service(
({ environment, options, platform }) =>
options.signalRecording ??
createSignalRecordingService(environment, platform),
({ environment, options, platform }) => ({
hostUnsupported: {
signalRecording: outsideHost(
options.signalRecording,
sigrokHostSupported(platform),
),
},
optionalFeatures: {
signalRecordingEnabled:
options.signalRecording !== undefined ||
(sigrokHostSupported(platform) &&
isAbsolute(environment.REA_SIGROK_COMMAND ?? "")),
},
}),
),
webRuntime: capability(
({ options }) => options.webRuntime ?? createWebRuntimeService(),
(value) => value.provider.close?.() ?? Promise.resolve(),
),
apktool: service(
({ environment, options, platform }) =>
options.apktoolAnalysis ??
createApktoolResourceAnalysisProvider(environment, platform),
(_context, value) => ({
probes: {
apktoolAnalysisAvailability: (signal: AbortSignal) =>
value.inspectAvailability(signal),
},
}),
),
jeb: service(
({ environment, options }) =>
options.jebAnalysis ?? createJebAnalysisProvider(environment),
(_context, value) => ({
probes: {
jebAnalysisAvailability: (signal: AbortSignal) =>
value.inspectAvailability(signal),
},
}),
),
adbDevice: service(
({ environment, options, platform }) =>
options.adbDeviceAnalysis ??
createAdbDeviceAnalysisProvider(environment, platform),
(_context, value) => ({
probes: {
adbAnalysisAvailability: (signal: AbortSignal) =>
value.inspectAvailability(signal),
},
}),
),
cutter: service(({ providerEnvironment, settings }) =>
createCutterBridgeService(providerEnvironment, { read: settings }),
),
browserObservation: capability(
({ options }) => options.browserObservation,
closeObservation,
({ options }) => ({
optionalFeatures: {
browserObservationEnabled: options.browserObservation !== undefined,
},
}),
sharedObservationOwnership,
),
browserScenarioCapture: capability(
({ options }) => options.browserScenarioCapture,
closeObservation,
({ options }) => ({
optionalFeatures: {
browserScenarioEnabled: options.browserScenarioCapture !== undefined,
},
}),
sharedObservationOwnership,
),
electronObservation: capability(
({ options }) => options.electronObservation,
closeObservation,
({ options }) => ({
optionalFeatures: {
electronObservationEnabled: options.electronObservation !== undefined,
},
}),
sharedObservationOwnership,
),
electronActiveObservation: capability(
({ options }) => options.electronActiveObservation,
closeObservation,
({ options }) => ({
optionalFeatures: {
electronAutomationEnabled:
options.electronActiveObservation !== undefined,
},
}),
sharedObservationOwnership,
),
javascriptRuntimeObservation: capability(
({ options }) => options.javascriptRuntimeObservation,
closeObservation,
({ options }) => ({
optionalFeatures: {
v8InspectorObservationEnabled:
options.javascriptRuntimeObservation !== undefined,
},
}),
sharedObservationOwnership,
),
} satisfies Partial<
Record<
CapabilityDeclarationId,
(context: CapabilityHostContext) => CapabilityInstance<unknown>
>
>;
export type CapabilityServices = {
readonly [Key in keyof typeof modules]: ReturnType<
(typeof modules)[Key]
>["value"];
};
/** Compose every service and its cleanup together, retaining precise typed ports. */
export const createCapabilityServices = (context: CapabilityHostContext) => {
const scope = new CapabilityScope();
const hostUnsupported: NonNullable<
CapabilityAvailabilityFacts["hostUnsupported"]
> = {};
const optionalFeatures: NonNullable<
CapabilityAvailabilityFacts["optionalFeatures"]
> = {};
const probes: NonNullable<CapabilityAvailabilityFacts["probes"]> = {};
const failureObservers: (() => OptionalProviderLoadFailures)[] = [];
const commandFailureObservers: (() => CommandProviderLaunchFailures)[] = [];
const availability = { hostUnsupported, optionalFeatures };
// This is a key-preserving map of a source-owned typed declaration, not an
// external value parser or a generic operation dispatcher.
const services = Object.fromEntries(
Object.entries(modules).map(([id, create]) => {
const instance = create(context);
const declaration = CAPABILITY_DECLARATIONS[id as keyof typeof modules];
if (declaration === undefined)
throw new Error(`Undeclared capability ${id}`);
Object.assign(
availability.hostUnsupported,
instance.availability?.hostUnsupported,
);
Object.assign(
availability.optionalFeatures,
instance.availability?.optionalFeatures,
);
Object.assign(probes, instance.availability?.probes);
const observeFailure = instance.availability?.observeProviderLoadFailures;
if (observeFailure !== undefined) failureObservers.push(observeFailure);
const observeCommandFailure =
instance.availability?.observeCommandProviderFailures;
if (observeCommandFailure !== undefined)
commandFailureObservers.push(observeCommandFailure);
return [
id,
instance.ownership === "host"
? scope.own(id, instance.value, instance.close)
: instance.value,
];
}),
) as CapabilityServices;
return {
services,
availability,
probes,
observeProviderLoadFailures: (): OptionalProviderLoadFailures =>
Object.assign({}, ...failureObservers.map((observe) => observe())),
observeCommandProviderFailures: (): CommandProviderLaunchFailures =>
Object.assign({}, ...commandFailureObservers.map((observe) => observe())),
createManagedBinarySession: async () => {
const { createManagedBinarySession } = await import("./binary.js");
return createManagedBinarySession();
},
close: () => scope.close(),
};
};