Files
reverse-engineering-anything/scripts/lib/module-layers.mjs
T
zhuweiyeandmorluto f25312a8bc feat(labview): inspect RSRC containers and embedded VI trees (#13337)
* feat(labview): inspect RSRC containers and embedded VI trees

Add inspect_labview_artifact, a static reader for LabVIEW RSRC containers in
.vi/.ctl/.llb files and in LabVIEW-built PE resources. It reports the container
header, the recorded LabVIEW version, the complete block inventory with each
section's coding, and whether the block-diagram and front-panel heaps are
present, without starting LabVIEW or any process.

Only zlib-coded sections are decoded, for their byte count; no payload is
returned. An absent block-diagram heap is reported as a limitation rather than
reconstructed.

* docs(labview): document RSRC inspection

Describe the inspect_labview_artifact contract, section codings, and the
block-diagram limitation, and list the target in the supported-targets table
and the documentation index.

* test(labview): cover provider admission for the RSRC reader

Add the provider-admission coverage the repository requires for a new
provider, without changing the reader:

- Move the synthetic RSRC container builder into a shared test fixture so
  the unit and boundary tests build the same bytes once.
- Add a CLI and stdio MCP boundary test for inspect_labview_artifact.
- Register `rea-labview-rsrc` lifecycle coverage for operation and cancel.
- Declare the `labviewArtifact` conformance case.
- Regenerate the advertised catalog summary for inspect_labview_artifact.

* fix(labview): require an absolute path in the inspection contract

`inspect_labview_artifact` admitted a relative `path`, while every other
caller-path contract requires an absolute one. The CLI/contract parity
check caught it: the CLI resolves a relative argument before admission,
so the contract must hold the absolute rule alone.

Use `absoluteLocalPathStringSchema`, the schema the other caller-path
contracts already use.

* fix(labview): bound inspection work and preserve parse facts

Address the review findings on the RSRC reader:

- Bound the PE resource walk with a visited set, a total visit budget,
  directory-entry and container allowances, and a typed limit failure
  instead of a silently partial scan.
- Check the resource directory and its data against the declared resource
  range rather than the whole file.
- Cap zlib inflation at its declared length, add a total decoded-work
  budget, and recognise any valid zlib header instead of three byte pairs.
- Check nested RSRC records against their declared data/info sections and
  cap the total section count across blocks.
- Read the artifact through readStableArtifact so identity, bounds and
  cancellation bind to the bytes actually inspected.
- Carry parse failures as ParseFailureError facts: malformed input keeps
  its kind/offset/field, and a limit becomes a typed fixed-allowance
  refusal instead of invalid_format.
- Report heap presence as `unknown` when an embedded program tree or an
  unexamined container could still hold it, not as `absent`.
- Cover cancellation that arrives after the read starts.
- Move the analyst guide under docs/guides/native/.

* fix(labview): retry retained cleanup and keep read failures distinct

- Own the artifact resource scope and run each read through it, so a
  retained failed close is retried before later work and reported at
  shutdown.
- Translate the read failure as recorded instead of replacing it with the
  signal's current state; the stable read owns its cancellation facts.
- State the 256 MiB input ceiling as a fixed allowance so an oversized
  artifact keeps its structured maximum and recovery.
- Match the guide to the decoded-byte behavior: a section over the budget
  is reported `unknown` and the inventory continues.

* fix(labview): bound the version scan and keep cleanup on refusal

- Replace the unbounded `\d+\.\d+` scan with a bounded single-pass search
  over the first 64 KiB of each vers section; a digit-only section no
  longer drives quadratic matching work in the shared server.
- Classify read failures through the shared provider classifier with a
  LabVIEW dialect, so the size ceiling is restated as a fixed allowance
  and the read's cleanup, partial observation and cancellation facts
  survive the refusal.
- Cover both with regressions.

* fix(labview): reuse the shared PE layout and bound the decode work

- Walk PE resources through readPeResourceLayout, so RVA lookup is indexed,
  a payload may map through any admitted section, and the home-grown
  section scan is gone. Add a total entry budget.
- Charge every attempted inflation against the container's decode budget,
  including failed and length-mismatched attempts.
- Bound block records by the list's declared extent, clamped to the
  container because real LabVIEW-built PEs declare more than the resource
  payload holds.
- Reject a named section whose name leaves the list instead of reporting
  it as unnamed.
- Pass the selected container to the parser without copying it.
- Cover the PE path and the over-declared list extent with regressions.

* fix(labview): bound repeated decodes and report unexamined coverage

- Charge compressed input bytes as well as declared output, and memoize
  the decoding of one stored section, so records that share a stream do
  not repeat its work.
- Keep a zlib-coded `vers` section's decoded bytes for the version scan.
- Cap list records by both the declared extent and the info section.
- Report PE walk coverage, and keep heap presence `unknown` for a `.llb`
  archive or an unreadable PE resource branch.

* fix(labview): key cached decoding by block and section

A section's coding depends on both its stored bytes and the block that
declares it: LVzp is XOR regardless of the bytes, while another block may
read the same bytes as raw or zlib. Include the block identifier in the
memo key so a shared section keeps each block's interpretation.

Cover the shared-section case with a regression.

* fix(labview): derive block facts once and stop inferring format from names

- Compute the block-diagram, front-panel and program-tree facts in one
  pass over the inventory and reuse them.
- Check the visited set before charging the PE directory-visit budget, so
  aliases of one directory do not exhaust it.
- Deduplicate aliased resource payload ranges before counting containers.
- Report a direct RSRC container's heap facts as unknown: its content does
  not establish whether it is a VI, a control, or an archive of member VIs,
  and the caller's spelling is not evidence of format.

* fix(labview): decode the packed version record and keep resource type

- Read the LabVIEW version from the packed four-byte word at the start of
  a `vers` record instead of scanning the whole record as Latin-1, and
  report `version_coverage` so an undecodable record is unknown rather
  than absent.
- Accept only RT_RCDATA (type 10) PE resource payloads, so the
  `pe-rcdata-rsrc` kind is accurate and a larger custom resource cannot
  win selection.

* fix(labview): walk only the RCDATA subtree and validate packed digits

- Walk only the RCDATA (type 10) resource subtree, so a shared directory
  reached under another type cannot hide the container and unrelated
  branches are not charged to the entry budget.
- Reject a packed version word whose digit nibbles are not decimal; a
  damaged record is skipped and a damaged-only container reports
  `version_coverage: unknown`.
- Derive the heap and program-tree facts in the parser and consume them in
  the provider, so one owner defines their meaning.

* fix(labview): filter root resource entries before dispatch

- Apply the RCDATA root-type filter before either target branch, so a root
  entry that points straight at a payload cannot enter the result.
- Validate only the decimal major, minor and bugfix fields; the build
  field is not part of the reported version.

* fix(labview): filter PE root types before dispatch and validate only reported version digits

The RT_RCDATA filter ran only for directory targets, so a noncanonical root
entry of another type pointing straight at a data entry could be counted
and labelled pe-rcdata-rsrc. Filter the depth-0 type identity before
either target branch, and share the RT_RCDATA constant with the PE
resource facts owner.

The vers check rejected a record whose build bits held a nibble above 9.
Only major.minor is reported, and pylabview (decimal build digits) and the
classic NumVersion layout (binary non-release revision) disagree on the
build, so only the reported major and minor nibbles are validated.

* fix(labview): resolve names against the shared list and keep read identity

- Locate the one section-name list after every block's start table and use
  it for all blocks, so named sections before the last block keep their
  identity instead of reading a neighbouring table.
- Retain the completed read's byte identity on later refusals and failed
  closes, so a parse failure still names the bytes that were read.

* fix(labview): report why recognized zlib sections stay undecoded

A valid RFC 1950 header with FDICT set was classified as uncompressed, so
a vers section's four-byte length prefix was read as version 0.0. FDICT
now marks the section as recognized-but-undecodable zlib.

Each undecoded zlib section records its reason (preset dictionary,
compressed-input or decoded-output allowance, or failed inflation), and the
report names the fixed allowance that stopped it, so a capacity omission is
distinguishable from damaged bytes.

A PE whose RCDATA branch could not be read is no longer described as
carrying no embedded RSRC resource. The RSRC magic and zlib header fields
are named once and shared.

* fix(labview): keep PE admission separate from an unreadable tree

A file that does not declare `MZ` is not a PE, so it must not be reported
as a malformed PE resource tree. The scan reports whether the file was
admitted as a PE separately from whether the walk was complete.

* fix(labview): take PE identity from the MZ owner and bound section tables

A two-byte MZ check treated plain DOS MZ and NE/LE/LX images as declared
PEs, so an ordinary non-LabVIEW file was reported as an unreadable PE
resource tree. PE identity now comes from observeMzWindowsHeader: only a
PE signature at e_lfanew declares a PE. The unused admitted field is
removed.

A section-start offset inside the count word or block-header rows was
accepted and could fabricate an inventory from block metadata. Tables must
start at or after the end of every block header; blocks may still share a
later table.

The refusal tests now assert the error type unconditionally.

* fix(labview): report embedded parse failures in file coordinates

A malformed RSRC embedded in a PE failed with container-relative offsets,
but the refusal names the selected executable and carries no
container.file_offset, so callers could not locate the failure. The
parser now takes the container origin and moves a failure offset into the
selected file's coordinates; successful results keep container-relative
ranges with container.file_offset.

* fix(labview): frame RSRC tables before applying their count allowances

A damaged container declaring an impossible block or section count was
refused as a capacity limit before its table extent was checked, so a
truncated target surfaced as resource_constraint. Each table is now framed
first; a fully framed table over its allowance is still a capacity
refusal.

* fix(labview): keep unread PE resource roots and rows out of observed absence

A nonzero resource RVA whose file-backed run cannot hold one directory
header returned complete coverage without reading anything, so the file
was reported as carrying no embedded RSRC. Only a zero RVA is observed
absence now; a short declared root is an unread tree.

Directory rows were checked against the entry allowances before their
extent, so a damaged directory declaring impossible counts surfaced as
resource_constraint. Rows are framed first; a fully framed directory over
its allowance is still a capacity refusal.

* fix(labview): reject RSRC data sections that overlap the fixed header

A data offset inside the 32-byte RSRC header let a section's stored-length
word be read from header fields, returning a fabricated empty section as a
successful inventory. A data offset below the header is now malformed.

* fix(labview): check decode-omission guidance structurally and own the RSRC magic once

The allowance test froze the delivered sentence. It now checks the parser's
decodeOmissions fact and the effective allowance, and compares the public
limitation with the provider's own formatter output.

The RSRC magic was declared again in artifact recognition; it now has one
owner in the LabVIEW domain contract, used by recognition, the parser, the
PE scan and the provider.

* feat(labview): summarize and page the RSRC inventory from retained Evidence

inspect_labview_artifact returned every block and section inline, so an
admitted container with 4096 named sections could exceed a megabyte and
bypass the agent result budget. The tool now takes detail: complete keeps
the inline inventory; summary, or omitted detail over the budget, returns
container, version and heap facts with block and section counts, and the
complete inventory is paged with inspect_analysis_view kind
labview-artifact (blocks, sections, optional block filter) or read with
evidence-json. The CLI delivers the same way.

RSRC data and info ranges that intersect are refused as malformed rather
than reading list metadata as section data.

* test(labview): read the CLI report as the complete inventory

The advertised output now admits complete or summary detail, so the test
parses the complete report schema explicitly.

* perf(labview): build view rows only for the requested page

Each view call copied every section before reading the request, so a
summary or one-row page did work proportional to the whole inventory. A
section index (block and section position, and positions per block) is
built once per immutable retained report and reused; summaries read
counts from it, and section pages build objects only for selected rows.

---------

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
2026-11-27 22:26:04 +00:00

638 lines
23 KiB
JavaScript

/**
* Declared layer of every top-level `src/` unit: each directory, and each
* root-level source file. Dependencies may point to the same or a lower
* layer. An undeclared unit fails the check, so a new directory must choose
* its layer when it is added.
*
* The order starts with dependency-free kernel helpers that every layer may
* use, then the domain, contracts, process/filesystem foundation, and ports.
* Providers implement the ports and application workflows consume them.
*/
export const LAYER_ORDER = Object.freeze([
"kernel",
"domain",
"contracts",
"foundation",
"ports",
"providerCore",
"providers",
"application",
"composition",
"adapters",
]);
const units = (layer, names) => names.map((name) => [name, layer]);
export const UNIT_LAYERS = Object.freeze(
Object.fromEntries([
...units("kernel", ["kernel"]),
...units("domain", ["domain"]),
...units("contracts", ["contracts"]),
...units("foundation", [
"compression",
"config",
"filesystem",
"hopperPaths",
"platform",
"process",
"resources",
"windows",
"generatedPackageMetadata.ts",
"identity.ts",
"logger.ts",
]),
...units("ports", ["ports"]),
// The shared provider core (src/providers): deferred client owners and
// failure attribution that every provider folder may import. It may not
// import a provider folder.
...units("providerCore", ["providers"]),
// Every unit here is a provider folder; see providerBoundaryFacts.
...units("providers", [
"adb",
"android",
"apkSignature",
"apktool",
"artifacts",
"browser",
"captures",
"cutter",
"deb",
"desktop",
"dotnet",
"electron",
"erlang",
"evm",
"firmware",
"flutter",
"frida",
"gdb",
"ghidra",
"go",
"gpu",
"hopper",
"ida",
"il2cpp",
"labview",
"inspector",
"javascript",
"java",
"jeb",
"kuna",
"model",
"native",
"nuget",
"vsix",
"objdump",
"oci",
"pcap",
"python",
"reference",
"rizin",
"rust",
"signals",
"sqlite",
"uefi",
"v8",
"wasm",
"yara",
]),
...units("application", ["application"]),
...units("composition", ["composition"]),
...units("adapters", [
"cli",
"main",
"server",
"cli.ts",
"cliBuiltinArguments.ts",
"cliConfiguration.ts",
"cliLoader.ts",
"cliLogging.ts",
"cliOneShot.ts",
"doctorRuntime.ts",
"main.ts",
"mcpDoctor.ts",
"recordedCliCommandRegistrations.ts",
"recordedMcpCatalog.ts",
]),
]),
);
/**
* Single file-to-file imports that may point up the layer order. Each one is
* a deliberate decision, not a baseline debt: it is not counted, and any other
* import between the same units still is. Keep the list short and say why.
*/
export const LAYER_EXCEPTIONS = Object.freeze([]);
const sourcePath = (path) => path.replace(/\.js$/u, ".ts");
/** Whether one resolved import is a declared layer exception. */
export const isLayerException = (file, target) =>
LAYER_EXCEPTIONS.some(
(exception) =>
exception.file === sourcePath(file) &&
exception.target === sourcePath(target),
);
const PRODUCTION_SOURCE = /^src\/.+\.(?:ts|js)$/u;
const NON_PRODUCTION = /\.(?:test|spec|fixture)\.(?:ts|js)$|\.d\.ts$/u;
/** The top-level unit of a production `src/` file, or undefined. */
export const sourceUnit = (path) => {
if (!PRODUCTION_SOURCE.test(path) || NON_PRODUCTION.test(path))
return undefined;
// A root-level source file is its own unit; built .js specifiers name .ts files.
return path.split("/")[1].replace(/\.js$/u, ".ts");
};
const rank = (unit) => LAYER_ORDER.indexOf(UNIT_LAYERS[unit]);
/** Unit pairs that import each other, the shortest import cycles. */
const mutualPairs = (edges) =>
[...edges.keys()]
.map((key) => key.split(" -> "))
.filter(([from, to]) => from < to && edges.has(`${to} -> ${from}`))
.map(([from, to]) => `${from} <-> ${to}`)
.sort();
/**
* Collect unit-level facts from resolved production imports: undeclared
* units, imports that point to a higher layer (counted per unit pair), and
* unit pairs that import each other. Longer cycles through three or more
* units are not reported; every such cycle contains an upward import, which
* the layer count already ratchets.
*/
export const layerGraphFacts = (imports, files = []) => {
const edges = new Map();
const undeclared = new Set();
for (const file of files) {
const unit = sourceUnit(file);
if (unit !== undefined && UNIT_LAYERS[unit] === undefined)
undeclared.add(unit);
}
for (const { file, target } of imports) {
const from = sourceUnit(file);
const to = sourceUnit(target);
if (from === undefined || to === undefined || from === to) continue;
if (isLayerException(file, target)) continue;
for (const unit of [from, to])
if (UNIT_LAYERS[unit] === undefined) undeclared.add(unit);
const key = `${from} -> ${to}`;
edges.set(key, (edges.get(key) ?? 0) + 1);
}
const upward = {};
for (const [key, count] of [...edges].sort(([a], [b]) =>
a < b ? -1 : a > b ? 1 : 0,
)) {
const [from, to] = key.split(" -> ");
if (undeclared.has(from) || undeclared.has(to)) continue;
if (rank(from) < rank(to)) upward[key] = count;
}
return {
undeclared: [...undeclared].sort(),
upward,
cycles: mutualPairs(edges),
...providerBoundaryFacts(imports),
};
};
/** Whether a unit is a provider folder. */
export const isProviderUnit = (unit) => UNIT_LAYERS[unit] === "providers";
const ENTRY_IMPORTER_LAYERS = new Set([
"application",
"composition",
"adapters",
]);
/**
* Declared entry files of each unit, relative to `src/<unit>/`: the only
* files that outside code may import.
*
* - `src/resources`, the shared provider toolkit (stable reads, artifact
* readers, resource scopes, cleanup leases and their failure projections),
* is reached from every other unit through its `index.ts`.
* - A provider folder is reached from application, composition and the CLI/MCP
* adapters through the files listed here: the provider classes, identities,
* metadata, worker servers, doctors and commands that composition wires.
* There is no per-provider barrel, because composition, the capability
* declarations and the CLI load single provider files lazily or for metadata
* only, and a barrel would pull in the whole provider.
*
* Adding a file here widens that unit's public surface; review it as such.
* Imports of any other file are counted in the baseline's `entry` map.
*/
export const ENTRY_FILES = Object.freeze(
Object.fromEntries(
Object.entries({
resources: ["index.ts"],
adb: ["AdbProvider.ts", "AdbProviderIdentity.ts"],
android: [
"JadxDoctor.ts",
"JadxMcpTransport.ts",
"JadxProvider.ts",
"JadxRelease.ts",
],
apkSignature: ["ApkSignatureProvider.ts", "ApkSignatureRelease.ts"],
apktool: ["ApktoolProvider.ts", "ApktoolProviderIdentity.ts"],
artifacts: [
"ArtifactProvider.ts",
"ArtifactProviderMetadata.ts",
"DesktopApplicationReader.ts",
// inspect_analysis_view's record-header pages re-read a root file
// through its format reader under the view's resource scope.
"formatRecordHeaderPage.ts",
"ReleaseExposureReader.ts",
// JavaScript reconstruction owns one resource scope across the
// inventory scan, the format reader and the source read.
"inventory/scanCanonical.ts",
"javascript/JavaScriptArtifactFiles.ts",
"javascript/JavaScriptArtifactReader.ts",
],
browser: [
"CdpBrowserProvider.ts",
"CdpElectronProvider.ts",
"IsolatedWebBundleAnalyzer.ts",
"PlaywrightBrowserScenarioProvider.ts",
"PlaywrightElectronActiveProvider.ts",
"PlaywrightScenarioSession.ts",
"WebBundleAnalysisWorkerServer.ts",
"assets/WebSourceLocationArtifacts.ts",
"execution/CdpWebRuntimeProvider.ts",
"history/CaptureProviderIdentities.ts",
"history/HistoricalCaptureDecoder.ts",
"history/MitmproxyCaptureAdapter.ts",
"history/NodeCaptureAdapter.ts",
"history/playwrightTrace/PlaywrightTraceDecoder.ts",
"modules/NativeModuleResolver.ts",
"modules/WebModuleArtifacts.ts",
"providerIdentities.ts",
],
captures: ["TsharkCaptureProvider.ts", "TsharkProviderIdentity.ts"],
cutter: [
"CutterBridgeClient.ts",
"CutterBridgeService.ts",
"CutterProviderIdentity.ts",
],
deb: ["DebPackageProvider.ts", "DebPackageProviderIdentity.ts"],
desktop: [
"AgentEnvComputer.ts",
"AgentEnvProviderIdentity.ts",
"BuildComputerEnvironment.ts",
"DconfDatabaseReader.ts",
"DesktopBuildDoctorFacts.ts",
"DesktopBuildSetupHost.ts",
"DesktopCaptureProvider.ts",
"DesktopSessionRequests.ts",
// Build-computer workflows in src/application/desktop drive these owners.
"AgentEnvComputerHelper.ts",
"AgentEnvSolveHelper.ts",
"BuildComputerController.ts",
"BuildComputerLongRuns.ts",
"BuildSecretFiles.ts",
"ScreenJudgeProcess.ts",
// Build-computer composition (`capabilityServices`) wires `readHostFile` into `DesktopBuildComputers`.
"HostFileRead.ts",
],
dotnet: ["ManagedStaticProvider.ts", "ManagedStaticProviderMetadata.ts"],
electron: ["ElectronFuseProvider.ts", "ElectronFuseProviderIdentity.ts"],
erlang: ["BeamProvider.ts", "ErlangBeamProviderIdentity.ts"],
evm: ["EvmoleInterfaceProvider.ts", "EvmoleProviderIdentity.ts"],
uefi: [
"UefiAnalysisProvider.ts",
"UefiProviderIdentity.ts",
"UefiFormatProbe.ts",
],
firmware: [
"FirmwareCommand.ts",
"FirmwareProvider.ts",
"FirmwareProviderIdentities.ts",
"devicetree/DevicetreeProvider.ts",
"espNvs/EspNvsProvider.ts",
],
flutter: ["FlutterBuildProvider.ts", "FlutterProviderIdentity.ts"],
frida: ["FridaInstrumentationManager.ts", "FridaProviderIdentity.ts"],
gdb: [
"GdbCommandClassification.ts",
"GdbProviderIdentity.ts",
"GdbSessionManager.ts",
],
ghidra: [
"GhidraDoctor.ts",
"GhidraProvider.ts",
"GhidraProviderMetadata.ts",
],
go: ["GoBinaryProvider.ts", "GoBinaryProviderIdentity.ts"],
gpu: ["GpuCodeObjectsProvider.ts", "GpuCodeObjectsProviderIdentity.ts"],
hopper: [
"HopperProvider.ts",
"HopperProviderMetadata.ts",
"LinuxPrivateDisplayProbe.ts",
],
ida: [
"IdaConfiguration.ts",
"IdaDoctor.ts",
"IdaMcpConnection.ts",
"IdaProvider.ts",
"IdaProviderMetadata.ts",
],
il2cpp: [
"Il2CppMetadataProviderIdentity.ts",
"Il2cppGhidraSeedWriter.ts",
"Il2cppMetadataProvider.ts",
],
labview: ["LabviewArtifactProvider.ts", "LabviewProviderIdentity.ts"],
inspector: ["V8InspectorProvider.ts", "providerIdentity.ts"],
java: [
"MavenGradleMetadataProvider.ts",
"MavenGradleMetadataProviderIdentity.ts",
],
javascript: [
"analysis/JavaScriptAnalysisTransfer.ts",
"analysis/JavaScriptAnalysisWorkerServer.ts",
"analysis/JavaScriptSourceAnalysis.ts",
"recovery/WakaruCommand.ts",
"recovery/WakaruProvider.ts",
"recovery/WakaruProviderIdentity.ts",
"sourceMaps/SourceMapDecoder.ts",
],
jeb: ["JebMcpConnection.ts", "JebProvider.ts", "JebProviderIdentity.ts"],
kuna: ["KunaDoctor.ts", "KunaProvider.ts", "KunaProviderMetadata.ts"],
model: ["ModelArtifactProvider.ts", "ModelArtifactProviderIdentity.ts"],
native: [
"NativeMacOSProvider.ts",
"NativeMacOSProviderMetadata.ts",
"NativeMacosProviderIdentity.ts",
"apple/AppleIpsProvider.ts",
"apple/MachoFunctionStartsProvider.ts",
"dwarf/DwarfUnitsProvider.ts",
"elf/ElfDebugLinkProvider.ts",
"elf/ElfDependenciesProvider.ts",
"elf/ElfNotesProvider.ts",
"elf/ElfUnwindRangesProvider.ts",
"elf/KernelBuildConfigProvider.ts",
"elf/KernelModuleProvider.ts",
"exports/NativeExportsProvider.ts",
"hardening/BinaryHardeningProvider.ts",
"initializers/NativeInitializersProvider.ts",
"pe/PeCertificatesProvider.ts",
"pe/PeImportsProvider.ts",
"pe/PeLoadConfigProvider.ts",
"pe/PeUnwindRangesProvider.ts",
"pe/PeOverlayProvider.ts",
"pe/PeResourcesProvider.ts",
"pwntools/PwntoolsDecoder.ts",
"pwntools/PwntoolsLayoutProvider.ts",
"pwntools/PwntoolsProviderIdentity.ts",
"pwntools/PwntoolsRecordedCrashProvider.ts",
"windows/WindowsShortcutProvider.ts",
],
nuget: ["NugetNupkgProvider.ts", "NugetNupkgProviderIdentity.ts"],
vsix: ["VsixPackageProvider.ts", "VsixPackageProviderIdentity.ts"],
objdump: ["ObjdumpCommand.ts", "ObjdumpProviderIdentity.ts"],
oci: ["OciImageLayoutProvider.ts", "OciImageLayoutProviderIdentity.ts"],
pcap: [
"PcapConfiguration.ts",
"PcapProvider.ts",
"PcapProviderIdentity.ts",
],
python: ["PythonPycProvider.ts", "PythonPycProviderIdentity.ts"],
reference: [
// The reference-source import workflow (src/application/ReferenceSource*)
// runs the reader and consumes its result and failure types. It reports
// its own root and VCS reads with the reader's two failure builders, so
// both kinds of failure share one shape and wording. Traversal state,
// symlink reconciliation and the per-entry failure helpers stay private.
"ReferenceSourceFailureBuilders.ts",
"ReferenceSourceReader.ts",
"ReferenceSourceReaderTypes.ts",
],
rizin: [
"RizinCommand.ts",
"RizinDebugSessionManager.ts",
"RizinDebuggerProviderIdentity.ts",
"RizinProviderIdentity.ts",
],
rust: ["RustBinaryProvider.ts", "RustBinaryProviderIdentity.ts"],
signals: ["SigrokProviderIdentity.ts", "SigrokRecordingProvider.ts"],
sqlite: ["SqliteDatabaseProvider.ts"],
v8: ["V8CodeCacheProvider.ts", "V8CodeCacheProviderIdentity.ts"],
wasm: ["WabtArtifactProvider.ts", "WabtRelease.ts"],
yara: ["YaraMatchesProvider.ts", "YaraProviderIdentity.ts"],
}).map(([unit, files]) => [unit, Object.freeze(files)]),
),
);
/**
* Whether an import from `from` into `to` must use one of `to`'s entry
* files: every import of a non-provider unit that declares entry files, and
* every application, composition or adapter import of a provider folder (a
* provider without declared entry files has none).
*/
const requiresEntry = (from, to) =>
isProviderUnit(to)
? ENTRY_IMPORTER_LAYERS.has(UNIT_LAYERS[from])
: ENTRY_FILES[to] !== undefined;
/** Whether a resolved target is one of its unit's declared entry files. */
const isEntryFile = (unit, target) =>
(ENTRY_FILES[unit] ?? []).some(
(file) => sourcePath(target) === `src/${unit}/${file}`,
);
/**
* Declared provider-to-provider dependencies: files of one provider folder,
* relative to `src/<to>/`, that another provider folder may import. Each one
* is a deliberate decision, not baseline debt: imports of these files are not
* counted in `crossProvider`, and any other import between the same folders
* still is. Keep the list short and say why.
*/
export const PROVIDER_DEPENDENCIES = Object.freeze([
Object.freeze({
from: "artifacts",
to: "native",
files: Object.freeze(["pe/PeUnsignedDigest.ts"]),
reason:
"ASAR inventory explains PE Authenticode signed-after-packing integrity mismatches",
}),
Object.freeze({
from: "artifacts",
to: "uefi",
files: Object.freeze(["UefiArtifactReader.ts", "UefiFormatProbe.ts"]),
reason:
"artifact inventory uses the UEFI provider's format admission and FV/FFS reader",
}),
Object.freeze({
from: "inspector",
to: "browser",
files: Object.freeze([
"CdpCaptureValues.ts",
"CdpConnection.ts",
"CdpDiscoveryTargets.ts",
"CdpEndpoint.ts",
"CdpScriptContextFacts.ts",
"CdpTargetSessionOwner.ts",
"ElectronFileScope.ts",
"protocol/CdpEvents.ts",
]),
// The V8 inspector speaks the Chrome DevTools Protocol. It reuses
// browser's CDP client (endpoint discovery, connection, target sessions
// and captured value projection) instead of keeping a second client.
// For Electron targets it authorizes script files inside app.asar with
// browser's Electron file scope, which owns the ASAR descriptors.
reason:
"the V8 inspector reuses the browser provider's CDP client and Electron file scope",
}),
Object.freeze({
from: "browser",
to: "electron",
files: Object.freeze([
"ElectronFuseFailures.ts",
"ElectronFusePath.ts",
"ElectronFuseReader.ts",
]),
// Active Electron capture launches the target with inspect arguments,
// which the EnableNodeCliInspectArguments fuse can silently disable.
// The preflight reads that fuse with the electron provider's fuse reader
// and reports its failures, instead of parsing the fuse wire twice.
reason:
"active Electron capture checks the inspect-arguments fuse with the electron provider's fuse reader",
}),
Object.freeze({
from: "desktop",
to: "electron",
files: Object.freeze(["ElectronFuseReader.ts"]),
// The Linux application inventory marks an executable as Electron when
// it carries a fuse sentinel. It locates the sentinel with the electron
// provider's fuse reader instead of searching the fuse wire again.
reason:
"the Linux application inventory detects Electron executables with the electron provider's fuse reader",
}),
Object.freeze({
from: "captures",
to: "pcap",
files: Object.freeze(["PcapConfiguration.ts"]),
// Live packet capture runs the same Wireshark tshark that the pcap
// provider runs. It locates, selects, versions and identity-checks it
// through pcap's Wireshark tool configuration, so REA_TSHARK_COMMAND and
// the executable identity rules have one owner.
reason:
"live packet capture selects and verifies tshark with the pcap provider's Wireshark tool configuration",
}),
]);
/** Whether one provider-to-provider import is a declared dependency. */
const isDeclaredProviderDependency = (from, to, target) =>
PROVIDER_DEPENDENCIES.some(
(dependency) =>
dependency.from === from &&
dependency.to === to &&
dependency.files.some(
(file) => sourcePath(target) === `src/${to}/${file}`,
),
);
const sortedCounts = (counts) =>
Object.fromEntries(
[...counts].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),
);
/**
* Provider boundary facts, counted per unit pair.
*
* A provider folder may import the domain, contracts, foundation and ports
* layers, the shared provider core (its own layer, below providers) and its
* own files. Any other import of another provider folder is recorded debt
* unless PROVIDER_DEPENDENCIES declares its target file for that pair:
* `crossProvider` counts them per pair, and a pair that is not in the
* baseline fails. Application, composition and the
* CLI/MCP adapters reach a provider only through its declared ENTRY_FILES, and
* every unit reaches src/resources only through its `index.ts`: `entry` counts
* the imports of any other file in such a unit. Both counts may only shrink.
*/
export const providerBoundaryFacts = (imports) => {
const cross = new Map();
const entry = new Map();
for (const { file, target } of imports) {
const from = sourceUnit(file);
const to = sourceUnit(target);
if (from === undefined || to === undefined || from === to) continue;
const key = `${from} -> ${to}`;
if (isProviderUnit(from) && isProviderUnit(to)) {
if (!isDeclaredProviderDependency(from, to, target))
cross.set(key, (cross.get(key) ?? 0) + 1);
} else if (requiresEntry(from, to) && !isEntryFile(to, target))
entry.set(key, (entry.get(key) ?? 0) + 1);
}
return {
crossProvider: sortedCounts(cross),
entry: sortedCounts(entry),
};
};
/** Counted pair maps a baseline ratchets, with the wording of each finding. */
const COUNTED = Object.freeze([
["upward", "upward import"],
["crossProvider", "cross-provider import"],
["entry", "import past the entry file"],
]);
/**
* Compare facts with the recorded baseline. Growth fails: a new counted pair
* (upward, cross-provider, or past a provider entry), more imports on a
* recorded pair, or a cycle group not recorded. Shrinkage is returned
* separately: the caller fails on it too, so the baseline is lowered in the
* change that removes the imports and can never grow back silently.
*/
export const compareLayerBaseline = (facts, baseline) => {
const failures = [];
const lowerable = [];
for (const unit of facts.undeclared)
failures.push(
`undeclared unit src/${unit}: add it to UNIT_LAYERS in scripts/lib/module-layers.mjs`,
);
for (const [kind, label] of COUNTED) {
const observed = facts[kind] ?? {};
const recorded = baseline[kind] ?? {};
for (const [key, count] of Object.entries(observed)) {
const allowed = recorded[key] ?? 0;
if (count > allowed)
failures.push(`${label} ${key}: ${count} imports, baseline ${allowed}`);
}
for (const [key, allowed] of Object.entries(recorded)) {
const count = observed[key] ?? 0;
if (count < allowed)
lowerable.push(`${label} ${key}: ${count}, baseline ${allowed}`);
}
}
const recordedCycles = new Set(baseline.cycles);
for (const group of facts.cycles)
if (!recordedCycles.has(group))
failures.push(`mutual import not in baseline: ${group}`);
const observedCycles = new Set(facts.cycles);
for (const group of baseline.cycles)
if (!observedCycles.has(group))
lowerable.push(`recorded mutual import no longer present: ${group}`);
return { failures, lowerable };
};
const lowerCounts = (observed = {}, recorded = {}) =>
Object.fromEntries(
Object.entries(recorded).flatMap(([key, allowed]) => {
const count = Math.min(allowed, observed[key] ?? 0);
return count > 0 ? [[key, count]] : [];
}),
);
/**
* The baseline lowered to the observed facts: each recorded counted pair
* keeps the smaller of its recorded and observed counts, and only recorded
* cycles that are still present remain. Nothing is added, so growth still
* fails.
*/
export const lowerLayerBaseline = (facts, baseline) => ({
upward: lowerCounts(facts.upward, baseline.upward),
cycles: baseline.cycles.filter((group) => facts.cycles.includes(group)),
crossProvider: lowerCounts(facts.crossProvider, baseline.crossProvider),
entry: lowerCounts(facts.entry, baseline.entry),
});