Merge remote-tracking branch 'origin/main' into fix/exact-empty-graph-identities
# Conflicts: # docs/product-catalog.json # docs/verification/managed-conformance-manifest.json # skills/reverse-engineer-anything/SKILL.md # src/generatedMcpToolCatalog.ts
This commit is contained in:
@@ -277,7 +277,7 @@ jobs:
|
||||
- run: npm run verify:keyed-archive
|
||||
- run: npm run verify:asset-catalog
|
||||
- name: Native compiled NIB hierarchy regressions
|
||||
run: npm run test:focused -- src/application/NibNativeHierarchy.test.ts
|
||||
run: npm run test:focused -- tests/boundary/filesystem/nibNativeHierarchy.test.ts tests/boundary/filesystem/interfaceBuilderBundle.test.ts
|
||||
- name: Real binary metadata and Interface Builder integration
|
||||
run: npm run verify:apple-dispatch && npm run verify:interface-builder
|
||||
- name: Native plist CLI selection regressions
|
||||
|
||||
@@ -95,6 +95,40 @@ MCP setup, Hopper, Ghidra, or executing the application. For a native app, confi
|
||||
its engine first, then use `analyze` with that app's path. Run `doctor` when you
|
||||
need diagnosis; it is not a prerequisite for each analysis.
|
||||
|
||||
### Check readiness for the task at hand
|
||||
|
||||
`rea doctor` without options is an audit of the whole integration. It checks
|
||||
every detected agent registration, the installed skill, and every optional
|
||||
analysis engine, so it can report `healthy: false` while your current task works.
|
||||
Choose a readiness scope for the work you are doing:
|
||||
|
||||
| Task | Readiness check |
|
||||
| ----------------------------------- | -------------------------------------------------------------------------------------------- |
|
||||
| Static JavaScript/Electron analysis | None. Run `analyze-javascript-application` directly. |
|
||||
| Troubleshoot one analysis engine | `rea doctor --provider ghidra --json` (or `hopper`, `ida`) |
|
||||
| Check one agent's MCP registration | `rea doctor --client codex --json` (see [client IDs](docs/installation.md#supported-agents)) |
|
||||
| Check the installed skill | `rea doctor --skill --json` |
|
||||
|
||||
A scoped report has `scope.mode: "explicit"`. Only `scope_checks` determine
|
||||
`healthy` and the exit status. Everything else is listed in
|
||||
`informational_checks`; you don't need to fix it for this task. For example, a
|
||||
missing engine you are not using needs no repair. `environment_healthy` still
|
||||
summarizes the full audit. `--target` adds a target check, but without a scope
|
||||
option the report remains audit-wide.
|
||||
|
||||
When more than one installed engine supports a native target, REA does not pick
|
||||
one: opening the target fails with `code: "capability_unavailable"`,
|
||||
`details.selection_reason: "ambiguous"`, and the providers in
|
||||
`details.candidate_ids`. Choose one once: pass `--provider` on
|
||||
the CLI or `provider_id` on `open_binary`, or set `REA_ANALYSIS_PROVIDER` as a
|
||||
standing preference. An explicit selector overrides the environment variable.
|
||||
The session keeps that choice and never falls back to another engine.
|
||||
Recovery depends on `details.selection_reason`. For `ambiguous`, choose one of
|
||||
the candidates. For `provider_unavailable`, the engine you selected needs repair,
|
||||
so run `rea doctor --provider <id> --json` and follow its remediation. Neither
|
||||
reason means you have to install every engine. See
|
||||
[Choosing a deep-analysis provider](#choosing-a-deep-analysis-provider).
|
||||
|
||||
### Install the rea command
|
||||
|
||||
Install the command-line interface:
|
||||
@@ -166,7 +200,7 @@ REA defaults `HOPPER_LAUNCHER_PATH` to `/Applications/Hopper Disassembler.app/Co
|
||||
|
||||
### Ghidra analysis provider
|
||||
|
||||
Already use Ghidra? REA can connect it to your agent on Linux x64 or macOS x64/arm64. It requires **Ghidra 12.1.4** and a **64-bit JDK 21**. On macOS, your Ghidra installation must also include the native decompiler for your architecture.
|
||||
Already use Ghidra? REA can connect it to your agent on Linux x64 or macOS x64/arm64. It accepts **Ghidra 12.1.x** and the **64-bit full JDK** that installation declares (`application.java.min` through `application.java.max`). Current 12.1 releases require JDK 21 or newer and set no maximum. The bridge is verified with Ghidra 12.1.4 and JDK 21. On macOS, your Ghidra installation must also include the native decompiler for your architecture.
|
||||
|
||||
Set the installation paths, then run setup:
|
||||
|
||||
@@ -742,3 +776,13 @@ See [CONTRIBUTING.md](CONTRIBUTING.md) for development setup and contribution ch
|
||||
## License
|
||||
|
||||
[MIT](LICENSE)
|
||||
|
||||
## Star history
|
||||
|
||||
<a href="https://www.star-history.com/?repos=morluto%2Frea&type=date">
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/chart?repos=morluto/rea&type=date&theme=dark&legend=top-left" />
|
||||
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/chart?repos=morluto/rea&type=date" />
|
||||
<img alt="REA GitHub star history" src="https://api.star-history.com/chart?repos=morluto/rea&type=date" />
|
||||
</picture>
|
||||
</a>
|
||||
|
||||
+2
-2
@@ -141,7 +141,7 @@ rea setup
|
||||
|
||||
يتطلب تحليل الملفات التنفيذية الأصلية Hopper أو Ghidra. Hopper برنامج منفصل، وللوضع التجريبي قيود يحددها المورّد، لكن الترخيص المدفوع ليس إلزاميًا.
|
||||
|
||||
يدعم Ghidra نظامي Linux x64 وmacOS x64/arm64. ثبت Ghidra 12.1.4 وJDK 21 الكامل بنواة 64 بت بصورة منفصلة، ثم اضبط REA لاستخدامهما. يحتاج macOS أيضًا إلى أداة فك الترجمة الأصلية المطابقة لمعمارية الجهاز.
|
||||
يدعم Ghidra نظامي Linux x64 وmacOS x64/arm64. ثبت Ghidra 12.1.x وJDK الكامل بنواة 64 بت الذي يعلنه ذلك التثبيت (`application.java.min` حتى `application.java.max`) بصورة منفصلة، ثم اضبط REA لاستخدامهما. تتطلب إصدارات 12.1 الحالية JDK 21 أو أحدث ولا تحدد حدًا أعلى. جرى التحقق من الجسر مع Ghidra 12.1.4 وJDK 21. يحتاج macOS أيضًا إلى أداة فك الترجمة الأصلية المطابقة لمعمارية الجهاز.
|
||||
|
||||
يستطيع Setup التحقق من التثبيت وحفظ المسارات؛ ولا يثبت أو يحدّث Ghidra أو Java أو Node.js أو npm أو Homebrew.
|
||||
|
||||
@@ -311,7 +311,7 @@ npx -y rea-agents@latest compare /absolute/path/to/left-evidence.json /absolute/
|
||||
<details>
|
||||
<summary><strong>هل يعمل REA على Linux أو Windows؟</strong></summary>
|
||||
|
||||
يدعم REA نظام macOS 12+ وUbuntu 24.04+ وFedora 41+ وArch Linux بنواة 64 بت. يعمل تحليل Ghidra للقراءة فقط على Linux x64 وmacOS x64/arm64 مع Ghidra 12.1.4 وJDK 21 الكامل، إضافة إلى حد Windows x64 P0 التجريبي لتطبيقات PE الأصلية x86-64 على NTFS محلي؛ راجع [دليل Windows Ghidra P0](docs/windows-ghidra-p0.md) للنطاق الموثق.
|
||||
يدعم REA نظام macOS 12+ وUbuntu 24.04+ وFedora 41+ وArch Linux بنواة 64 بت. يعمل تحليل Ghidra للقراءة فقط على Linux x64 وmacOS x64/arm64 مع Ghidra 12.1.x وJDK الكامل الذي يعلنه التثبيت (JDK 21 أو أحدث دون حد أعلى في إصدارات 12.1 الحالية)، إضافة إلى حد Windows x64 P0 التجريبي لتطبيقات PE الأصلية x86-64 على NTFS محلي؛ راجع [دليل Windows Ghidra P0](docs/windows-ghidra-p0.md) للنطاق الموثق.
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
+1
-1
@@ -141,7 +141,7 @@ rea setup
|
||||
|
||||
ネイティブバイナリ解析には Hopper または Ghidra が必要です。Hopper は別製品です。デモにはベンダー所定の制限がありますが、有料ライセンスは必須ではありません。
|
||||
|
||||
Ghidra は Linux x64 と macOS x64/arm64 に対応します。Ghidra 12.1.4 と完全な 64 ビット JDK 21 を別途インストールし、REA で使うように設定してください。macOS ではホストのアーキテクチャに合うネイティブデコンパイラーも必要です。
|
||||
Ghidra は Linux x64 と macOS x64/arm64 に対応します。Ghidra 12.1.x と、そのインストールが宣言する完全な 64 ビット JDK(`application.java.min` から `application.java.max` まで)を別途インストールし、REA で使うように設定してください。現行の 12.1 リリースは JDK 21 以降を要求し、上限は設定しません。ブリッジは Ghidra 12.1.4 と JDK 21 で検証しています。macOS ではホストのアーキテクチャに合うネイティブデコンパイラーも必要です。
|
||||
|
||||
Setup はインストールを確認し、パスを保存できます。Ghidra、Java、Node.js、npm、Homebrew のインストールや更新は行いません。
|
||||
|
||||
|
||||
+1
-1
@@ -142,7 +142,7 @@ rea setup
|
||||
|
||||
네이티브 바이너리 분석에는 Hopper 또는 Ghidra가 필요합니다. Hopper는 별도 소프트웨어입니다. 데모에는 공급업체의 제한이 있지만 유료 라이선스가 필수는 아닙니다.
|
||||
|
||||
Ghidra는 Linux x64와 macOS x64/arm64를 지원합니다. Ghidra 12.1.4와 완전한 64비트 JDK 21을 별도로 설치한 뒤 REA가 사용하도록 설정하세요. macOS에서는 호스트 아키텍처에 맞는 네이티브 디컴파일러도 필요합니다.
|
||||
Ghidra는 Linux x64와 macOS x64/arm64를 지원합니다. Ghidra 12.1.x와 그 설치본이 선언한 완전한 64비트 JDK(`application.java.min`부터 `application.java.max`까지)를 별도로 설치한 뒤 REA가 사용하도록 설정하세요. 현재 12.1 릴리스는 JDK 21 이상을 요구하고 상한은 없습니다. 브리지는 Ghidra 12.1.4와 JDK 21에서 검증됩니다. macOS에서는 호스트 아키텍처에 맞는 네이티브 디컴파일러도 필요합니다.
|
||||
|
||||
Setup은 설치를 확인하고 경로를 저장할 수 있습니다. Ghidra, Java, Node.js, npm, Homebrew를 설치하거나 업데이트하지 않습니다.
|
||||
|
||||
|
||||
+1
-1
@@ -141,7 +141,7 @@ rea setup
|
||||
|
||||
原生二进制分析需要 Hopper 或 Ghidra。Hopper 是独立软件;演示模式有厂商规定的限制,不要求购买许可证。
|
||||
|
||||
Ghidra 支持 Linux x64 和 macOS x64/arm64。单独安装 Ghidra 12.1.4 和完整的 64 位 JDK 21,然后配置 REA 使用它们。macOS 还需要对应架构的原生反编译器。
|
||||
Ghidra 支持 Linux x64 和 macOS x64/arm64。单独安装 Ghidra 12.1.x,以及该安装在 `application.java.min` 到 `application.java.max` 中声明的完整 64 位 JDK,然后配置 REA 使用它们。当前 12.1 发行版要求 JDK 21 或更新版本,并且不设置上限。桥接在 Ghidra 12.1.4 和 JDK 21 上完成验证。macOS 还需要对应架构的原生反编译器。
|
||||
|
||||
Setup 可以验证安装并保存路径,不会安装或升级 Ghidra、Java、Node.js、npm 或 Homebrew。
|
||||
|
||||
|
||||
@@ -16,6 +16,8 @@ graph TD
|
||||
APP["src/application/<br/>Shared CLI/MCP workflows<br/>enhanced analysis and investigations"]
|
||||
SESSION["SessionProviderRouter + BinarySession<br/>one immutable deep binding per target<br/>disjoint auxiliary routing"]
|
||||
REGISTRY["AnalysisProviderRegistry<br/>sorted deep candidates<br/>deterministic selection, no fallback"]
|
||||
RECORDS["src/application/investigation/<br/>composed InvestigationRecords + narrow ports<br/>EvidenceLedger and Unknown ownership"]
|
||||
SNAPSHOT["BinarySessionRecords + AnalysisSnapshotCache<br/>binary target/profile snapshots<br/>compatibility facade and post-commit notifications"]
|
||||
JS_RECON["src/application/ + src/artifacts/<br/>JavaScript artifact reconstruction<br/>directory/ASAR reads<br/>AST-only bundle projection"]
|
||||
end
|
||||
|
||||
@@ -75,6 +77,11 @@ graph TD
|
||||
CLI --> ERRORS
|
||||
APP --> SESSION
|
||||
SESSION --> REGISTRY
|
||||
SESSION --> SNAPSHOT
|
||||
SNAPSHOT --> RECORDS
|
||||
APP -->|record callbacks| RECORDS
|
||||
SERVER -->|narrow record ports| RECORDS
|
||||
RECORDS --> DOMAIN
|
||||
REGISTRY --> HOPPER
|
||||
REGISTRY --> GHIDRA
|
||||
REGISTRY --> IDA
|
||||
|
||||
@@ -13,7 +13,7 @@ there is no new universal provider interface or fixed module manifest.
|
||||
| Producer parsing and external tool protocols | provider adapters | Keep behind the relevant typed port |
|
||||
| Shared analyst workflows | application | Share between CLI and MCP |
|
||||
| Concrete provider construction | binary runtime, composition, MCP startup | Consolidate one capability at a time in production composition |
|
||||
| Investigation Evidence and Unknowns | BinarySessionRecords | Extract one composed record owner after caller migration |
|
||||
| Investigation Evidence and Unknowns | InvestigationRecords/EvidenceLedger | Consume narrow read/write/atomic record ports |
|
||||
| Target/profile snapshots and invalidation | BinarySessionRecords/BinarySession | Keep binary-owned |
|
||||
| Subprocess ownership and host primitives | process/windows | Reuse; preserve cancellation and cleanup |
|
||||
| Public translation | CLI/MCP adapters | Delegate to shared workflows and named contracts |
|
||||
@@ -117,3 +117,54 @@ installs nothing. Core transport failures and shutdown still use their existing
|
||||
lifecycle. Fault-injection coverage uses the production loading/startup path and
|
||||
actual MCP SDK calls; recording ports establish composition behavior, while the
|
||||
real Inspector lane separately establishes runtime behavior.
|
||||
|
||||
## Investigation record ownership pilot
|
||||
|
||||
`src/application/investigation/InvestigationRecords.ts` owns one existing
|
||||
EvidenceLedger per runtime. The production session composition constructs that
|
||||
owner explicitly; the direct BinarySession constructor retains a fresh default
|
||||
for compatibility. There is no second ledger, global store, persistence or new
|
||||
retention policy.
|
||||
|
||||
EvidenceReader, EvidenceWriter and EvidenceUnknownWriter describe existing
|
||||
read/write/atomic callback needs. UnknownRegistryPort preserves optimistic
|
||||
revisions and consistency verification. Non-binary MCP registrars use these
|
||||
record types without depending on the binary execution/lifecycle surface.
|
||||
BinarySessionPort retains its compatible record methods through composition.
|
||||
|
||||
BinarySessionRecords remains the snapshot owner and compatibility facade. It
|
||||
passes the actual active target explicitly for recordUnknown/updateUnknown;
|
||||
recordEvidenceWithUnknown keeps its target-free mutation subject. Snapshot import
|
||||
merges records without notifying midway, then emits after the cache commits.
|
||||
Bundle import retains the full change delta so Unknown-only changes notify even
|
||||
when recordsAdded is zero. Clearing resets records, cache and invalidation before
|
||||
notification; observer failures remain best effort after a committed mutation.
|
||||
|
||||
Close and failed-cleanup clearing, ordinary target-switch retention, detached
|
||||
reads, Evidence identities and deterministic bundle transfer keep their existing
|
||||
behavior. Snapshots still require an active target and concrete analysis profile;
|
||||
extracting investigation ownership does not make them a target-free record store.
|
||||
#721 remains responsible for any future lifetime-policy change.
|
||||
|
||||
## Auxiliary source declaration pilot
|
||||
|
||||
Artifact, macOS native and managed static metadata now belongs to each adapter's
|
||||
`*ProviderMetadata.ts` module. The implementation and
|
||||
`src/composition/auxiliaryAnalysisProviders.ts` reuse the same identity and exact
|
||||
capability descriptors. The declarations reference existing AnalysisProvider
|
||||
loaders; they cover these three disjoint auxiliary implementations only. Deep
|
||||
candidate selection and the five typed observation ports remain separate.
|
||||
|
||||
The binary runtime reads these source declarations while auxiliary construction
|
||||
stays lazy. The separate managed-only entrypoint retains direct construction for
|
||||
its execution-free workflow. The MCP catalog generator reads declarations without
|
||||
constructing implementations, using its canonical macOS platform; actual runtime
|
||||
host restrictions remain explicit.
|
||||
Discovery and binary operation-kind routing now consume canonical source contracts
|
||||
rather than their generated JSON artifact. No declaration imports its generated
|
||||
output. Generated catalog facts and public schemas stay unchanged.
|
||||
|
||||
All observation registrars resolve contracts by name. An isolated compiled-process
|
||||
test reverses presentation arrays and performs actual MCP SDK calls to verify
|
||||
advertised schemas and handler meaning. Reordering metadata must not select a
|
||||
different operation, schema, provider or deep-provider priority.
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
# Firmware analysis
|
||||
|
||||
REA integrates **Binwalk 3.1.0** for region inspection and **Unblob 26.6.4** for
|
||||
explicit extraction. This first firmware milestone is verified on Linux x64.
|
||||
REA accepts **Binwalk 3.1.x** for region inspection and **Unblob 26.6.x** for
|
||||
explicit extraction. The report parsers are verified with Binwalk 3.1.0 and
|
||||
Unblob 26.6.4. Another build on those lines is accepted, the observed version
|
||||
is reported, and a limitation records that the parser was not verified against
|
||||
that build. This first firmware milestone is verified on Linux x64.
|
||||
No device, root privilege, mount, emulation or execution of extracted programs
|
||||
is needed. Arbitrary firmware bytes do not pass native executable admission;
|
||||
select a returned ELF separately for supported Ghidra analysis.
|
||||
@@ -16,7 +19,8 @@ export REA_UNBLOB_COMMAND=/absolute/path/to/unblob
|
||||
```
|
||||
|
||||
REA does not install these tools, their dependencies or system packages. It
|
||||
checks the actual tool version when executing a request. Inspection and
|
||||
checks the tool's `--version` banner when executing a request. Binwalk must
|
||||
print `binwalk <version>` and Unblob must print the version alone. Inspection and
|
||||
extraction have independent prerequisites; one does not require the other.
|
||||
Both require util-linux `prlimit`, normally `/usr/bin/prlimit`; override its
|
||||
absolute path with `REA_FIRMWARE_PRLIMIT_COMMAND` if needed.
|
||||
@@ -161,7 +165,7 @@ Additional lanes are explicit, so the base lane stays small:
|
||||
REA_FIRMWARE_VERIFY_EXT4=1 npm run fixtures:firmware
|
||||
REA_FIRMWARE_VERIFY_EXT4=1 npm run verify:firmware
|
||||
|
||||
# Existing Ghidra 12.1.4 and Java required.
|
||||
# Existing Ghidra 12.1.x and its declared JDK required.
|
||||
REA_FIRMWARE_VERIFY_GHIDRA=1 npm run verify:firmware
|
||||
```
|
||||
|
||||
|
||||
+3
-3
@@ -2,9 +2,9 @@
|
||||
|
||||
REA can analyze DOS MZ executables and explicitly selected COM images through the bring-your-own Ghidra adapter.
|
||||
The Linux x64 verification lane exercises actual 16-bit disassembly and
|
||||
decompilation through the CLI and stdio MCP. It requires the same Ghidra
|
||||
12.1.4 and 64-bit JDK 21 installation as other Ghidra sessions; no DOS emulator
|
||||
or cross-compiler is required.
|
||||
decompilation through the CLI and stdio MCP. Provider admission accepts Ghidra
|
||||
12.1.x and that installation's declared JDK range. The verification lane uses
|
||||
Ghidra 12.1.4 and JDK 21; no DOS emulator or cross-compiler is required.
|
||||
|
||||
## Open and inspect
|
||||
|
||||
|
||||
@@ -7,7 +7,10 @@ source notices are retained. No upstream source or algorithms are rewritten.
|
||||
|
||||
The initial tested layout is .NET runtime **8.0.22**, NativeAOT RTR **9.1**,
|
||||
x86-64 ELF and native Windows PE **targets analyzed on Linux x64**, using
|
||||
Ghidra **12.1.4** and JDK **21**. Other layouts/architectures/hosts are unsupported.
|
||||
Ghidra **12.1.4** and JDK **21**. The build accepts any Ghidra 12.1.x release and
|
||||
javac 21 or newer, and it compiles with `--release 21`. Real verification of
|
||||
this layout remains the Ghidra 12.1.4 and JDK 21 pair. Other NativeAOT layouts,
|
||||
architectures, and hosts are unsupported.
|
||||
Windows Ghidra P0 has no database mutation authority. A PE/CLI or ReadyToRun
|
||||
assembly should use `inspect_managed_artifact`; it is not NativeAOT.
|
||||
|
||||
|
||||
+10
-5
@@ -108,7 +108,9 @@ npx -y rea-agents@latest analyze-javascript-application /absolute/path/to/app --
|
||||
```
|
||||
|
||||
It returns the complete Evidence record directly and requires no native engine.
|
||||
Provider failures in doctor do not prevent unrelated target-free tools.
|
||||
Provider failures in doctor do not prevent unrelated target-free tools. To check
|
||||
readiness for one task instead of auditing every integration, see
|
||||
[Check readiness for the task at hand](../README.md#check-readiness-for-the-task-at-hand).
|
||||
|
||||
## Supported agents
|
||||
|
||||
@@ -264,7 +266,10 @@ copying license secrets into logs, or killing unrelated Hopper processes.
|
||||
|
||||
REA connects to an existing Ghidra installation on Linux x64, macOS x64/arm64,
|
||||
or experimental Windows x64 P0.
|
||||
It requires Ghidra 12.1.4 and a 64-bit full JDK 21. On macOS, the installation
|
||||
It accepts Ghidra 12.1.x and the 64-bit full JDK declared by that installation's
|
||||
`application.java.min` and `application.java.max`. Current 12.1 releases require
|
||||
JDK 21 or newer and set no maximum. The bridge is verified with Ghidra 12.1.4
|
||||
and JDK 21. On macOS, the installation
|
||||
must include the native decompiler for the host architecture; REA does not
|
||||
build it or change Gatekeeper quarantine settings.
|
||||
|
||||
@@ -310,9 +315,9 @@ installation remains unavailable on Windows. Setup never installs Ghidra,
|
||||
Java, or Python. It preserves valid detected Ghidra/JDK settings in agent
|
||||
registrations. See [Windows Ghidra P0](windows-ghidra-p0.md) for provider diagnostics.
|
||||
|
||||
Doctor validates the platform, architecture, application version,
|
||||
`support/analyzeHeadless` or `support/analyzeHeadless.bat`, Java
|
||||
version/bitness, and the presence of `javac`/`javac.exe`.
|
||||
Doctor validates the platform, architecture, Ghidra 12.1.x application version,
|
||||
`support/analyzeHeadless` or `support/analyzeHeadless.bat`, the installation's
|
||||
Java major range, 64-bit JDK bitness, and the presence of `javac`/`javac.exe`.
|
||||
When Java is found through `PATH`, setup records its observed JDK home so GUI
|
||||
MCP clients do not depend on an incidental shell path. Setup shows every exact
|
||||
environment entry in its plan, writes only after approval, and never downloads,
|
||||
|
||||
@@ -150,7 +150,7 @@ actions may change application data or trigger network activity.
|
||||
|
||||
## Provider and verification boundaries
|
||||
|
||||
Install Ghidra 12.1.4 and a full 64-bit JDK 21 separately, then configure REA to
|
||||
Install a Ghidra 12.1.x release and the 64-bit full JDK it declares, then configure REA to
|
||||
use them. Ghidra analysis supports Linux x64 and macOS x64/arm64; macOS requires
|
||||
the matching native decompiler. Experimental Windows x64 P0 admits native
|
||||
x86-64 PE applications on local NTFS using bundled Job Object ownership,
|
||||
|
||||
@@ -637,9 +637,9 @@
|
||||
"mcp_prompts": 6
|
||||
},
|
||||
"digests": {
|
||||
"tools_sha256": "d1962c65198f036b57556918d59b2a5bdf544d2cd7c8a60ff0e4fce2efd472f1",
|
||||
"tools_sha256": "ad67b7ccd2361cac2959737ff8846fc401caf62914f9f07d46eacdb7a0445c6d",
|
||||
"prompts_sha256": "ef2de8814390b340623c32001610aa2709d90bed51537b6e562ab3abf144ab4d",
|
||||
"combined_sha256": "66307e8428ce3bddbf004e43d15a0d6b60965667cc1c1bb792b28a7b63837b74",
|
||||
"combined_sha256": "9fdeb18c4f18dd5843077de00e6c4853ffaa737b1524b0558bac5f4b3d4a2572",
|
||||
"providers_sha256": "7949ddcf2eb5ba41b022bb3dfa1951ab96dbf5640285fa7fd5d35b0e4a5bdab3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,8 +3,10 @@
|
||||
This guide describes repository main. Check the [released package boundary](installation.md#released-package-and-main) when using npm.
|
||||
|
||||
Ghidra read-only analysis is available on Linux x64 and macOS x64/arm64.
|
||||
Install Ghidra 12.1.4 and a full 64-bit JDK 21 separately, then configure REA to
|
||||
use them. macOS installations need the matching native decompiler.
|
||||
Install a Ghidra 12.1.x release and the 64-bit full JDK that release declares,
|
||||
then configure REA to use them. Current 12.1 releases require JDK 21 or newer
|
||||
and set no maximum. The bridge is verified with Ghidra 12.1.4 and JDK 21.
|
||||
macOS installations need the matching native decompiler.
|
||||
|
||||
REA imports one target into a temporary project and exposes 25 read-only
|
||||
operations after analysis completes. They cover inventories, search,
|
||||
@@ -53,9 +55,11 @@ follow.
|
||||
|
||||
## Shipped foundation boundary
|
||||
|
||||
`GHIDRA_INSTALL_DIR` must identify an extracted official 12.1.4 release;
|
||||
optional `JAVA_HOME` must identify a 64-bit full JDK 21, otherwise doctor probes
|
||||
`java`/`javac` or `java.exe`/`javac.exe` from `PATH`. Supported Linux and macOS
|
||||
`GHIDRA_INSTALL_DIR` must identify an extracted Ghidra 12.1.x release. Optional
|
||||
`JAVA_HOME` must identify a 64-bit full JDK inside that installation's
|
||||
`application.java.min` and `application.java.max` (JDK 21 or newer, with no
|
||||
maximum, when the release leaves those at the 12.1 defaults). Otherwise doctor
|
||||
probes `java`/`javac` or `java.exe`/`javac.exe` from `PATH`. Supported Linux and macOS
|
||||
hosts accept compatible ELF, PE, and Mach-O executable targets. Host admission
|
||||
and target compatibility are separate checks. Windows x64 P0 admits only native,
|
||||
non-managed, non-DLL x86-64 PE applications on fixed local NTFS, with the packaged
|
||||
|
||||
+4
-2
@@ -45,8 +45,10 @@ verified paths for an existing Ghidra installation. It configures Claude Code,
|
||||
Claude Desktop, Codex, Cursor, Gemini CLI, Windsurf, Devin, OpenCode, Antigravity,
|
||||
GitHub Copilot CLI, Command Code, and VS Code using each client's configuration format.
|
||||
|
||||
Ghidra analysis supports Linux x64 and macOS x64/arm64 with Ghidra 12.1.4 and a
|
||||
64-bit full JDK 21. macOS also requires the matching native decompiler. The
|
||||
Ghidra analysis supports Linux x64 and macOS x64/arm64 with Ghidra 12.1.x and the
|
||||
64-bit full JDK that installation declares. Current 12.1 releases require JDK 21
|
||||
or newer and set no maximum; the bridge is verified with Ghidra 12.1.4 and JDK 21.
|
||||
macOS also requires the matching native decompiler. The
|
||||
adapter exposes thirteen inventory operations and twelve function-analysis
|
||||
operations, for 25 read-only operations total. Linux and macOS additionally support
|
||||
atomic function-name and entry-comment edits with refreshed analysis; metadata
|
||||
|
||||
@@ -1,169 +0,0 @@
|
||||
# Test suite audit
|
||||
|
||||
## Scope and priority
|
||||
|
||||
The expanded audit on 2026-10-04 reviewed every one of the 355 Vitest files
|
||||
present at its start: 82 domain/contracts, 56 application/composition, 147
|
||||
adapter/configuration/process/filesystem/CLI files, and 70 MCP/acceptance/
|
||||
conformance/evaluation files. Three review passes checked the proposed removals
|
||||
against existing stronger coverage and checked the final changes for lost
|
||||
assertions. The remaining suite has 351 files.
|
||||
|
||||
Prefer full real-provider E2E, then integration across schemas and transports,
|
||||
then real-data goldens. Remove lower-level duplication once the replacement
|
||||
asserts the same behavior. Keep distinct failure regressions that a successful
|
||||
E2E cannot exercise. Do not lower coverage thresholds to accommodate pruning.
|
||||
|
||||
## Changes made
|
||||
|
||||
| Previous test or assertion | Decision | Replacement or retained claim |
|
||||
| ----------------------------------------------------------------------------------------------- | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| Asset application tests using fabricated `.car` bytes and injected utility JSON | Remove two plumbing cases | `verify:asset-catalog`: real actool → assetutil → CLI and stdio MCP, including digest, full metadata, pagination and invalid input |
|
||||
| Keyed archive positive binary/XML objects assembled with the same plist library as the reader | Remove two synthetic success cases | Captured Foundation XML plus reviewed complete object/reference graph golden; real Foundation binary/XML → CLI and stdio MCP |
|
||||
| Generic contract schema/annotation/example loops and output-map inventory comparisons | Consolidate into one SDK wire test | Assert exported schemas, guidance, effect annotations and valid examples on the actual advertised MCP catalog |
|
||||
| Ghidra function operation enum membership | Remove | Canonical catalog, provider handshake and actual operation roundtrips establish admission; malformed provider results remain covered |
|
||||
| Asset page assertion pinning `10_001` | Remove | Invalid-page rejection through real MCP; malformed utility data still covered |
|
||||
| Suggested prompt tool positions | Remove incidental ordering assertions | Keep authority, evidence, untrusted input and preparation constraints |
|
||||
| Package “acceptance” assertions pinning CI matrix/shard values and fake launcher command arrays | Remove configuration-shaped cases | Actual package/install verifier remains; retain a compact release verification-before-publish and registry-canary static guard |
|
||||
| Package failure classifier under acceptance | Move to package evaluation | Preserve all malformed/unrelated-failure rejection cases; do not call them E2E |
|
||||
| Native value graph checks conditional on success | Strengthen | Require success before pagination/ambiguity assertions; unexpected errors can no longer pass |
|
||||
| Native UI verifier treating permission denial as a positive pass | Separate outcomes | Default lane requires real capture/action success; opt-in permissions lane explicitly reports no positive E2E proof |
|
||||
|
||||
Ten previous test cases were removed or consolidated; three replacement
|
||||
Vitest cases cover the captured goldens and release guard. The two real artifact
|
||||
E2E scripts add product-level evidence outside the deterministic Vitest count.
|
||||
|
||||
## Exhaustive follow-up
|
||||
|
||||
The follow-up removes or consolidates another 31 test declarations, including
|
||||
three redundant test files. Parameterized declarations and executed cases have
|
||||
different counts; the figures above count source declarations. It also repairs
|
||||
assertions that could pass without exercising their stated behavior.
|
||||
|
||||
| Area | Cleanup | Stronger retained evidence |
|
||||
| ---------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
|
||||
| Configuration | Merge duplicate target/loader tests and preserve custom launcher, explicit provider and actionable error diagnostics | Independent malformed inputs; each capability flag is rejected separately |
|
||||
| Browser scenarios | Remove fake launch success and expression-selected artifact success | Real Chromium scenarios, actual artifacts, CLI capture and owned/external cleanup in `verify:browser` |
|
||||
| CLI policy | Remove duplicate confirmation helper cases | Compiled CLI proves project files stay unchanged until `--yes`; distinct interactive choices remain |
|
||||
| Provider capabilities | Remove numerical catalog freezes; consolidate Hopper byte-read discovery | Exact canonical capability identities, admission, mutation effects and detached descriptors |
|
||||
| Evidence ledger | Merge reordered-key checks into serialized bundle import; remove one-record quota claims | Atomic import, conflicts, residual revisions, actual large collections and byte regressions |
|
||||
| MCP batching and concurrency | Replace maximum concurrency and empty indistinguishable responses | Every distinct ordered batch result; concurrently gated requests complete in reverse order with matching payloads |
|
||||
| MCP inventories and graphs | Remove traversal/inventory call order and redundant catalog/prose checks | Exact complete cyclic graph, full inline inventories, canonical SDK catalog and all-handler roundtrips |
|
||||
| Authority and lifecycle | Attempt the refused Ghidra mutation; require successful setup, call and switch; close twice | Typed refusal with zero mutation dispatch, restored target calls and exact owned-resource cleanup |
|
||||
| Process and provider output | Remove incidental environment read and command option order/defaults | PID/ownership validation, exact disabled-policy failure and complete decoded response above 10 MiB |
|
||||
| Conformance and CI guards | Merge identical replay runs; remove duplicate missing-row fault, trivial hash/self equality and incidental worker/step counts | Distinct faulty evidence, digest order, actual test discovery, file existence and release/runner authority |
|
||||
| Pure schemas | Remove fabricated comparison-dimension injection and impossible long boundary success | Real artifact comparison and SDK coverage evaluation with returned boundary identity |
|
||||
|
||||
The removed long boundary selector test only parsed a 1,000-character request;
|
||||
workspace boundary identities admit at most 200 characters, so that positive
|
||||
could never represent a successful evaluation. The actual MCP evaluation stays
|
||||
covered. One unused ledger serialization helper was also retired after removing
|
||||
its only test consumer; no CLI or MCP contract changed.
|
||||
|
||||
No further immediately safe pruning was identified in the final review. Retained
|
||||
replacement candidates below are coverage gaps, rather than permission to delete
|
||||
unique tests. Test-only domain scaffolding also stays pending a separate decision
|
||||
about the corresponding source behavior; deleting those tests alone would leave
|
||||
unverified code and fail unused-export checks.
|
||||
|
||||
## Stronger replacements from the closing pass
|
||||
|
||||
Three more synthetic success cases were removed. Native value composition now
|
||||
runs through the production CLI and a separate stdio MCP subprocess with real
|
||||
Ghidra, using a source-built native fixture. It checks argument/parameter/return
|
||||
relationships, the fixture's global operand, authenticated Evidence, upstream
|
||||
and workflow analysis profiles, identical CLI/MCP graphs, discovery availability
|
||||
and successful MCP session closure. Ambiguity, cancellation, target changes,
|
||||
missing flow and bounded-work regressions remain in the focused suite.
|
||||
|
||||
That replacement found missing CLI workflow routing for `trace_native_values`
|
||||
and missing workflow profile classification. The routing and discovery now use
|
||||
the composed operation's actual provider prerequisites; workflow Evidence commits
|
||||
to the upstream Ghidra profile.
|
||||
|
||||
The lone hand-built client-document equality test is replaced by a real TOML
|
||||
filesystem transaction: reversed environment keys leave the original bytes
|
||||
unchanged and create no backup. A real ZIP entry with an application root longer
|
||||
than 5,000 characters replaces injected schema-only positive data. Inventory
|
||||
completeness tests partition actual scans into authenticated partial observations
|
||||
and require exact assembled results and every source citation, including more
|
||||
than 100 citations. These are consumer merge tests, not provider pagination
|
||||
claims. Replay aggregation now covers all four statuses and retains actual runner
|
||||
diagnostics; it does not claim to execute a real sandbox. Retained pixel-metric
|
||||
fixtures now write correct PNG chunk checksums.
|
||||
|
||||
The all-zero screenshot buffer is replaced by a real Chromium PNG of 9,467,940
|
||||
bytes, transported intact through CLI and stdio MCP and decoded by the production
|
||||
pixel comparator. The verifier configures the SDK client's receive buffer because
|
||||
its 10 MiB default is smaller than the inline JSON response. This does not claim
|
||||
large comparison-request transport coverage. A real SDK initialize request,
|
||||
captured during a successful production stdio handshake, replaces the JSON-RPC
|
||||
decoder's field-count-only oracle with exact field/value expectations.
|
||||
|
||||
The closing pass also removed assertions tied to internal call order, defaults,
|
||||
private cache sizes, duplicated polling and fabricated schema extensions. Unique
|
||||
malformed-input, security-capacity and cleanup regressions remain.
|
||||
|
||||
## Real process regression found
|
||||
|
||||
The full suite exposed a renderer ordering race. Publishing a terminal output
|
||||
journal entry could synchronously trigger a reactive resize before the preceding
|
||||
output was queued for rendering. Queue that output first. The existing real
|
||||
source-owned interactive PTY test now also requires the first resized frame to
|
||||
contain the output that triggered the resize, preserving the original event
|
||||
order rather than sorting or changing timestamps to conceal it.
|
||||
|
||||
## Coverage kept
|
||||
|
||||
Malformed archives, broken and cyclic references, unsupported metadata pointers,
|
||||
relative Objective-C method layouts, ambiguous call candidates, digest mismatch,
|
||||
cancellation, host permission denial, bounded output and owned-resource cleanup
|
||||
remain covered. These cases provide evidence beyond a successful real-tool run.
|
||||
The hand-assembled relative method fixture stays until compiler-produced
|
||||
relative-list fixtures establish equivalent assertions.
|
||||
|
||||
## Remaining priorities
|
||||
|
||||
1. Extend the real Ghidra CLI/stdio MCP journey from value tracing to dispatch
|
||||
and UI handlers before pruning their hand-authored composition success cases.
|
||||
Native value tracing now establishes full transport parity.
|
||||
2. Real binary dispatch and nib → full product transports, with normalized
|
||||
semantic goldens. The compiler-backed readers already run in the new Apple
|
||||
CI lane; synthetic pointer/layout rejection tests remain useful.
|
||||
3. An approved interactive macOS runner for native UI capture/actions, including
|
||||
stdio MCP scenarios. Hosted runners without permissions cannot supply this
|
||||
proof. No arbitrary application's windows should be opened for this lane.
|
||||
4. Real macOS/Linux Ghidra CI runners with bring-your-own installations. This
|
||||
change adds Apple artifact CI without installing Java or Ghidra.
|
||||
5. Classify fake-runner replay/application acceptance accurately and replace
|
||||
repeated happy paths only after real sandbox journeys assert the same claims.
|
||||
The replay workflow's allow-unavailable mode must not imply executed replay.
|
||||
6. Replace repeated-array schema ceiling tests with real producer/transport
|
||||
regressions before deleting them. Existing integration tests do not yet
|
||||
establish their large-input guarantees.
|
||||
|
||||
Some static guards protect irreversible release authority rather than product
|
||||
behavior. Keep these few guards explicit and separate from E2E evidence.
|
||||
|
||||
## Verification after the expanded audit
|
||||
|
||||
- `npm run check:pr`: 351 files passed; 1,794 tests passed and two skipped.
|
||||
Typecheck, lint, formatting, unused-code and generated-document gates passed.
|
||||
- `npm run check:fast`: passed; 70 lint warnings and zero errors.
|
||||
- `npm run verify:browser`: actual Chromium observation and scenario CLI routes,
|
||||
retained artifacts, owned/external lifecycle checks and large CLI/stdio MCP PNG
|
||||
capture passed.
|
||||
- `npm run verify:ghidra`: macOS ARM64 with Ghidra 12.1.4/JDK 21 passed, including
|
||||
real native value tracing through CLI and stdio MCP: 171 nodes, 298 edges and
|
||||
six decompilations.
|
||||
- `npm run verify:asset-catalog`: real actool/assetutil → CLI and stdio MCP,
|
||||
complete records, pagination and malformed input checks passed.
|
||||
- `npm run verify:keyed-archive`: real Foundation binary/XML → CLI and stdio MCP,
|
||||
full graph golden, shared/cyclic identity and malformed scope checks passed.
|
||||
|
||||
- `npm run verify:fixtures`: seven source-built host fixtures, source/artifact
|
||||
digests and exhaustive inventory checks passed.
|
||||
|
||||
No Hopper windows were opened for this audit. The closing pass runs real Ghidra
|
||||
on macOS ARM64; earlier Hopper evidence remains separate. No new hosted CI success
|
||||
is claimed.
|
||||
+8
-4
@@ -106,9 +106,6 @@ It uses an installed browser and accepts an optional installed REA entrypoint.
|
||||
The complete `verify:browser` lane also exercises passive script export through
|
||||
both public adapters. See [website script export](website-script-export.md).
|
||||
|
||||
The [test suite audit](test-suite-audit.md) records the pruning decisions,
|
||||
replacement evidence and remaining priorities.
|
||||
|
||||
## Real-toolchain verification lanes
|
||||
|
||||
Each real-toolchain command must require only the host tools needed to prove
|
||||
@@ -118,6 +115,11 @@ commands. Check prerequisites before starting expensive work and name the
|
||||
missing command, target, and lane in any failure message. A lane must not imply
|
||||
that a host or target is covered when it was skipped.
|
||||
|
||||
Provider admission accepts Ghidra 12.1.x and the JDK range declared by that
|
||||
installation (`application.java.min` through `application.java.max`). Current
|
||||
12.1 releases require JDK 21 or newer and set no maximum. The lanes below still
|
||||
prove behavior on the verified Ghidra 12.1.4 and JDK 21 build.
|
||||
|
||||
| Ghidra lane | Supported runner/target | Additional local tools |
|
||||
| ------------------------------------------ | ---------------------------------------------------------------------------------- | ------------------------------------------------------------------- |
|
||||
| `npm run verify:ghidra` | Linux x64 ELF or macOS x64/arm64 Mach-O | Host C compiler, Ghidra 12.1.4, and full JDK 21 |
|
||||
@@ -399,7 +401,9 @@ for the exact ABI, authority, graph and observation boundaries.
|
||||
`npm run fixtures:firmware` uses existing Python 3 and a host C compiler to make
|
||||
an ignored gzip/USTAR firmware fixture and independent offset/hash oracle.
|
||||
`npm run verify:firmware` requires caller-supplied Binwalk 3.1.0, Unblob 26.6.4
|
||||
and util-linux prlimit on Linux. It verifies CLI/MCP parity, selected ranges,
|
||||
and util-linux prlimit on Linux. The provider also accepts other 3.1.x and
|
||||
26.6.x builds and reports them as unverified; this lane proves the audited
|
||||
releases. It verifies CLI/MCP parity, selected ranges,
|
||||
unknown chunks, depth limits and extracted child digests. The optional
|
||||
`REA_FIRMWARE_VERIFY_EXT4=1` lane requires existing mke2fs/debugfs; the separate
|
||||
`REA_FIRMWARE_VERIFY_GHIDRA=1` lane checks a selected host ELF through real Ghidra.
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"manifest_id": "ecm_cbc35f371fbe873508281f13785667c48063cf8d9dee4e8bb8e74126baf0fba7",
|
||||
"manifest_id": "ecm_7150d90ef5af704d4305274dba927a178336c08deaf73eb38e086037125f565b",
|
||||
"verifier": {
|
||||
"id": "rea-managed-conformance",
|
||||
"version": "1"
|
||||
@@ -13,7 +13,7 @@
|
||||
"skill_digests": [
|
||||
{
|
||||
"skill_id": "reverse-engineer-anything",
|
||||
"sha256": "79a973d8c9ac217408e7f92e4a0f776b049d74dbf1d2b0c5249dab5127de893c"
|
||||
"sha256": "02db0b541efa3226e43fa1444f6a3f205aeb28016125263f6f3d64241d89ba80"
|
||||
}
|
||||
],
|
||||
"claims": [
|
||||
|
||||
@@ -13,8 +13,8 @@ additional permission flag or degraded mode is required.
|
||||
|
||||
- Windows 10+ x64 with fixed local NTFS target and temporary volumes;
|
||||
- Node.js 22.x (>=22.19), 24.x (>=24.11), or 26+;
|
||||
- an operator-installed official Ghidra 12.1.4 distribution;
|
||||
- a 64-bit full JDK 21;
|
||||
- an operator-installed Ghidra 12.1.x distribution (verified with 12.1.4);
|
||||
- a 64-bit full JDK inside that installation's declared Java range (JDK 21 or newer, with no maximum, for current 12.1 releases);
|
||||
- an explicit native, non-managed, non-DLL x86-64 PE application; and
|
||||
- the 25 read-only Ghidra inventory, memory, and function-analysis operations.
|
||||
|
||||
|
||||
@@ -20,14 +20,17 @@ const source = resolve(
|
||||
const install = process.env.GHIDRA_INSTALL_DIR;
|
||||
if (!install)
|
||||
throw new Error(
|
||||
"NativeAOT build lane requires existing GHIDRA_INSTALL_DIR (Ghidra 12.1.4).",
|
||||
"NativeAOT build lane requires existing GHIDRA_INSTALL_DIR (Ghidra 12.1.x).",
|
||||
);
|
||||
const properties = await readFile(
|
||||
join(install, "Ghidra/application.properties"),
|
||||
"utf8",
|
||||
);
|
||||
if (!/^application.version=12\.1\.4\s*$/m.test(properties))
|
||||
throw new Error("NativeAOT build lane requires Ghidra 12.1.4.");
|
||||
const ghidraVersion = propertyValue(properties, "application.version");
|
||||
if (!ghidraReleaseLineAccepted(ghidraVersion))
|
||||
throw new Error(
|
||||
`NativeAOT build lane accepts Ghidra 12.1.x (verified with 12.1.4). Observed application.version=${ghidraVersion ?? "missing"}.`,
|
||||
);
|
||||
const output = resolve(
|
||||
process.env.REA_NATIVEAOT_BUILD_ROOT ??
|
||||
join(root, "_reference/nativeaot-integration/extension"),
|
||||
@@ -47,9 +50,11 @@ const run = (command, args) => {
|
||||
return result.stdout.trim();
|
||||
};
|
||||
const javac = java ? join(java, "javac") : "javac";
|
||||
if (!/^javac 21(?:\.|$)/u.test(run(javac, ["-version"])))
|
||||
const javacBanner = capture(javac, ["-version"]);
|
||||
const javacMajor = Number(/^javac (\d+)/mu.exec(javacBanner)?.[1]);
|
||||
if (!Number.isInteger(javacMajor) || javacMajor < 21)
|
||||
throw new Error(
|
||||
"NativeAOT build lane requires an existing JDK 21 javac; REA does not install or upgrade Java.",
|
||||
`NativeAOT build lane requires javac 21 or newer and compiles with --release 21. Observed: ${javacBanner || "no version"}. REA does not install or upgrade Java.`,
|
||||
);
|
||||
const revision = run("git", ["-C", source, "rev-parse", "HEAD"]);
|
||||
if (
|
||||
@@ -93,6 +98,8 @@ try {
|
||||
run(javac, [
|
||||
"-J-Xmx512m",
|
||||
"-J-XX:ActiveProcessorCount=1",
|
||||
"--release",
|
||||
"21",
|
||||
`@${join(output, "javac.args")}`,
|
||||
]);
|
||||
await writeFile(
|
||||
@@ -119,7 +126,7 @@ try {
|
||||
jar,
|
||||
sha256,
|
||||
upstream_revision: revision,
|
||||
ghidra_version: "12.1.4",
|
||||
ghidra_version: ghidraVersion,
|
||||
integration_api: 1,
|
||||
},
|
||||
null,
|
||||
@@ -131,10 +138,41 @@ try {
|
||||
jar,
|
||||
sha256,
|
||||
upstream_revision: revision,
|
||||
ghidra_version: "12.1.4",
|
||||
ghidra_version: ghidraVersion,
|
||||
integration_api: 1,
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
await rm(classes, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
/** Read one application.properties value. Empty and missing values stay unknown. */
|
||||
function propertyValue(content, name) {
|
||||
for (const line of content.split(/\r?\n/u)) {
|
||||
const separator = line.indexOf("=");
|
||||
if (separator < 0 || line.slice(0, separator).trim() !== name) continue;
|
||||
const value = line.slice(separator + 1).trim();
|
||||
return value.length === 0 ? null : value;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Same 12.1 line as GhidraInstallationPolicy, including a distro suffix. */
|
||||
function ghidraReleaseLineAccepted(raw) {
|
||||
const match = /^(\d+)\.(\d+)(?:\.(\d+))?([-+].*)?$/u.exec(raw ?? "");
|
||||
return match !== null && Number(match[1]) === 12 && Number(match[2]) === 1;
|
||||
}
|
||||
|
||||
function capture(command, args) {
|
||||
const result = spawnSync(command, args, {
|
||||
cwd: root,
|
||||
encoding: "utf8",
|
||||
timeout: 120_000,
|
||||
maxBuffer: 4 * 1024 * 1024,
|
||||
});
|
||||
if (result.error || result.status !== 0)
|
||||
throw new Error(
|
||||
`NativeAOT build prerequisite/action ${command} failed: ${result.error?.message ?? ""}\n${result.stdout ?? ""}${result.stderr ?? ""}`,
|
||||
);
|
||||
return `${result.stdout ?? ""}\n${result.stderr ?? ""}`.trim();
|
||||
}
|
||||
|
||||
@@ -7,9 +7,7 @@ import { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import { TOOL_CONTRACTS } from "../dist/contracts/toolContracts.js";
|
||||
import { MANAGED_WORKFLOW_TOOL_CONTRACTS } from "../dist/contracts/managedWorkflowToolContracts.js";
|
||||
import { ArtifactProvider } from "../dist/artifacts/ArtifactProvider.js";
|
||||
import { ManagedStaticProvider } from "../dist/dotnet/ManagedStaticProvider.js";
|
||||
import { NativeMacOSProvider } from "../dist/native/NativeMacOSProvider.js";
|
||||
import { auxiliaryAnalysisProviderDeclarations } from "../dist/composition/auxiliaryAnalysisProviders.js";
|
||||
import { toolRegistrationOptions } from "../dist/server/toolRegistrationOptions.js";
|
||||
import { ensureGeneratedFile } from "./lib/generated-file.mjs";
|
||||
|
||||
@@ -88,14 +86,9 @@ async function sdkToolCatalog() {
|
||||
await Promise.allSettled([client.close(), server.close()]);
|
||||
}
|
||||
}
|
||||
const auxiliaryProviders = [
|
||||
new ArtifactProvider(CATALOG_PLATFORM),
|
||||
new NativeMacOSProvider(undefined, CATALOG_PLATFORM),
|
||||
new ManagedStaticProvider(),
|
||||
].map((provider) => ({
|
||||
identity: provider.identity(),
|
||||
capabilities: provider.capabilities(),
|
||||
}));
|
||||
const auxiliaryProviders = auxiliaryAnalysisProviderDeclarations(
|
||||
CATALOG_PLATFORM,
|
||||
).map(({ identity, capabilities }) => ({ identity, capabilities }));
|
||||
|
||||
const canonicalizeJson = (value) => {
|
||||
if (Array.isArray(value)) return value.map(canonicalizeJson);
|
||||
|
||||
@@ -59,7 +59,7 @@ const SOURCE_PATHS = {
|
||||
hopperProvider: "dist/hopper/HopperProvider.js",
|
||||
ghidraProvider: "dist/ghidra/GhidraProvider.js",
|
||||
idaProvider: "dist/ida/IdaProviderCapabilities.js",
|
||||
nativeProvider: "dist/native/NativeMacOSProvider.js",
|
||||
nativeProvider: "dist/native/NativeMacOSProviderMetadata.js",
|
||||
artifactProviders: "dist/application/InvestigationProviders.js",
|
||||
browserProvider: "dist/browser/CdpBrowserProvider.js",
|
||||
browserScenarioProvider: "dist/browser/PlaywrightBrowserScenarioProvider.js",
|
||||
|
||||
@@ -4,7 +4,7 @@ description: Reverse engineer native, managed, Electron/JavaScript, packaged, fi
|
||||
metadata:
|
||||
version: "26"
|
||||
tool_count: 126
|
||||
catalog_digest: "66307e8428ce3bddbf004e43d15a0d6b60965667cc1c1bb792b28a7b63837b74"
|
||||
catalog_digest: "9fdeb18c4f18dd5843077de00e6c4853ffaa737b1524b0558bac5f4b3d4a2572"
|
||||
---
|
||||
|
||||
# REA
|
||||
|
||||
@@ -79,7 +79,7 @@ export class JadxSession {
|
||||
);
|
||||
const engine = {
|
||||
name: "jadx-headless-mcp",
|
||||
version: "0.7.1",
|
||||
version: JADX_RELEASE.version,
|
||||
artifact_sha256: jarHash,
|
||||
source_revision:
|
||||
jarHash === JADX_RELEASE.sha256 ? JADX_RELEASE.revision : null,
|
||||
|
||||
@@ -18,12 +18,14 @@ import type {
|
||||
ProviderIdentity,
|
||||
} from "./AnalysisProvider.js";
|
||||
import type { AnalysisOperation } from "./AnalysisProvider.js";
|
||||
import { GENERATED_MCP_TOOL_CATALOG } from "../generatedMcpToolCatalog.js";
|
||||
import { OFFICIAL_TOOL_CONTRACTS } from "../contracts/officialToolContracts.js";
|
||||
import { ENHANCED_TOOL_CONTRACTS } from "../contracts/enhancedToolContracts.js";
|
||||
import type { BinarySessionPort } from "./BinarySessionPort.js";
|
||||
import {
|
||||
SessionProviderRouter,
|
||||
type SessionProviderRoute,
|
||||
} from "./SessionProviderRouter.js";
|
||||
import { InvestigationRecords } from "./investigation/InvestigationRecords.js";
|
||||
import { BinarySessionRecords } from "./BinarySessionRecords.js";
|
||||
import { binarySessionStatus } from "./BinarySessionStatus.js";
|
||||
import {
|
||||
@@ -38,14 +40,10 @@ import {
|
||||
import { closeAnalysisClient } from "./AnalysisClientCleanup.js";
|
||||
export type { BinarySessionPort } from "./BinarySessionPort.js";
|
||||
const OFFICIAL_OPERATIONS: ReadonlySet<string> = new Set(
|
||||
GENERATED_MCP_TOOL_CATALOG.filter(
|
||||
({ kind }) => kind === "official-proxy",
|
||||
).map(({ name }) => name),
|
||||
OFFICIAL_TOOL_CONTRACTS.map(({ name }) => name),
|
||||
);
|
||||
const ENHANCED_OPERATIONS: ReadonlySet<string> = new Set(
|
||||
GENERATED_MCP_TOOL_CATALOG.filter(({ kind }) => kind === "enhanced").map(
|
||||
({ name }) => name,
|
||||
),
|
||||
ENHANCED_TOOL_CONTRACTS.map(({ name }) => name),
|
||||
);
|
||||
|
||||
/**
|
||||
@@ -78,8 +76,11 @@ export class BinarySession
|
||||
>();
|
||||
readonly #availabilityListeners = new Set<() => void | Promise<void>>();
|
||||
|
||||
constructor(providerRouter: SessionProviderRouter) {
|
||||
super();
|
||||
constructor(
|
||||
providerRouter: SessionProviderRouter,
|
||||
records: InvestigationRecords = new InvestigationRecords(),
|
||||
) {
|
||||
super(records);
|
||||
this.#providerRouter = providerRouter;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { InvestigationRecords } from "./investigation/InvestigationRecords.js";
|
||||
import type { AnalysisProvider } from "./AnalysisProvider.js";
|
||||
import { AnalysisProviderRegistry } from "./AnalysisProviderRegistry.js";
|
||||
import { BinarySession } from "./BinarySession.js";
|
||||
@@ -15,4 +16,5 @@ export const composeBinarySession = (
|
||||
registry instanceof SessionProviderRouter
|
||||
? registry
|
||||
: SessionProviderRouter.selectable(registry, auxiliaryProviders),
|
||||
new InvestigationRecords(),
|
||||
);
|
||||
|
||||
@@ -1,21 +1,13 @@
|
||||
import type { InvestigationRecordPort } from "./investigation/InvestigationRecordPort.js";
|
||||
import type { ExecutableFormatHint } from "../domain/dosCom.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import type { EvidenceBundle } from "../domain/evidenceBundle.js";
|
||||
import type { AnalysisSnapshot } from "../domain/analysisSnapshot.js";
|
||||
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
|
||||
import type { AnalysisProviderSelector } from "../contracts/providerSelection.js";
|
||||
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import type { EvidenceIntegrityError } from "../domain/evidenceErrors.js";
|
||||
import type { UnknownRegistryError } from "../domain/unknownRegistryError.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
import type {
|
||||
RecordUnknownInput,
|
||||
ResidualUnknown,
|
||||
UnknownStatus,
|
||||
UpdateUnknownInput,
|
||||
} from "../domain/residualUnknown.js";
|
||||
|
||||
import type {
|
||||
AnalysisOperation,
|
||||
AnalysisOperationPort,
|
||||
@@ -24,7 +16,8 @@ import type {
|
||||
} from "./AnalysisProvider.js";
|
||||
|
||||
/** Target lifecycle used by CLI and MCP without exposing a concrete provider. */
|
||||
export interface BinarySessionPort extends AnalysisOperationPort {
|
||||
export interface BinarySessionPort
|
||||
extends AnalysisOperationPort, InvestigationRecordPort {
|
||||
open(
|
||||
path: string,
|
||||
options?: {
|
||||
@@ -42,40 +35,10 @@ export interface BinarySessionPort extends AnalysisOperationPort {
|
||||
): Promise<Result<null, AnalysisError>>;
|
||||
status(): JsonValue;
|
||||
activeTarget(): BinaryTarget | undefined;
|
||||
recordEvidence(
|
||||
evidence: Evidence,
|
||||
): Result<"added" | "duplicate", EvidenceIntegrityError>;
|
||||
hasEvidence(evidenceId: string): boolean;
|
||||
evidenceById(evidenceId: string): Evidence | undefined;
|
||||
exportEvidenceBundle(): EvidenceBundle;
|
||||
importEvidenceBundle(bundle: unknown): Result<number, EvidenceIntegrityError>;
|
||||
exportAnalysisSnapshot(): Result<AnalysisSnapshot, AnalysisError>;
|
||||
importAnalysisSnapshot(
|
||||
snapshot: AnalysisSnapshot,
|
||||
): Result<number, AnalysisError>;
|
||||
recordUnknown(
|
||||
input: RecordUnknownInput,
|
||||
): Result<ResidualUnknown, AnalysisError>;
|
||||
recordEvidenceWithUnknown(
|
||||
evidence: Evidence,
|
||||
input: RecordUnknownInput,
|
||||
): Result<ResidualUnknown | null, AnalysisError>;
|
||||
updateUnknown(
|
||||
input: UpdateUnknownInput,
|
||||
): Result<ResidualUnknown, AnalysisError>;
|
||||
listUnknowns(filters?: {
|
||||
readonly status?: UnknownStatus;
|
||||
readonly severity?: ResidualUnknown["severity"];
|
||||
readonly domain?: string;
|
||||
}): ResidualUnknown[];
|
||||
verifyUnknownResolution(unknownId: string): Result<
|
||||
{
|
||||
readonly valid: boolean;
|
||||
readonly truthVerified: boolean;
|
||||
readonly unknown: ResidualUnknown;
|
||||
},
|
||||
UnknownRegistryError
|
||||
>;
|
||||
providerIdentity(operation?: AnalysisOperation): ProviderIdentity;
|
||||
analysisProfile(
|
||||
operation?: AnalysisOperation,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { AnalysisProfileCommitment } from "../domain/analysisProfile.js";
|
||||
import type { AnalysisSnapshot } from "../domain/analysisSnapshot.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import type { EvidenceBundle } from "../domain/evidenceBundle.js";
|
||||
import { evidenceBundleForTarget } from "../domain/evidenceBundle.js";
|
||||
import { EvidenceIntegrityError } from "../domain/evidenceErrors.js";
|
||||
@@ -19,25 +19,24 @@ import type {
|
||||
AnalysisOperation,
|
||||
} from "./AnalysisProvider.js";
|
||||
import { AnalysisSnapshotCache } from "./AnalysisSnapshotCache.js";
|
||||
import { EvidenceLedger } from "./EvidenceLedger.js";
|
||||
import {
|
||||
UNKNOWN_REGISTRY_PROVIDER,
|
||||
unknownEvidenceLinks,
|
||||
unknownMutationEvidence,
|
||||
} from "./UnknownEvidence.js";
|
||||
import { InvestigationRecords } from "./investigation/InvestigationRecords.js";
|
||||
|
||||
export interface ActiveAnalysisBinding {
|
||||
readonly target: BinaryTarget;
|
||||
readonly profile: AnalysisProfileCommitment | null;
|
||||
}
|
||||
|
||||
/** Owns session evidence, snapshots, and residual unknowns. */
|
||||
/** Binary snapshot owner and compatibility facade for composed investigation records. */
|
||||
export abstract class BinarySessionRecords {
|
||||
readonly #evidence = new EvidenceLedger();
|
||||
readonly #records: InvestigationRecords;
|
||||
readonly #snapshot = new AnalysisSnapshotCache();
|
||||
#snapshotInvalidated = false;
|
||||
readonly #snapshotListeners = new Set<() => void | Promise<void>>();
|
||||
|
||||
constructor(records: InvestigationRecords = new InvestigationRecords()) {
|
||||
this.#records = records;
|
||||
}
|
||||
|
||||
/** Observe changes to the mutable current analysis snapshot resource. */
|
||||
onAnalysisSnapshotChanged(listener: () => void | Promise<void>): () => void {
|
||||
this.#snapshotListeners.add(listener);
|
||||
@@ -47,27 +46,27 @@ export abstract class BinarySessionRecords {
|
||||
recordEvidence(
|
||||
evidence: Evidence,
|
||||
): Result<"added" | "duplicate", EvidenceIntegrityError> {
|
||||
const recorded = this.#evidence.record(evidence);
|
||||
const recorded = this.#records.recordEvidence(evidence);
|
||||
if (recorded.ok && recorded.value === "added") this.#emitSnapshotChanged();
|
||||
return recorded;
|
||||
}
|
||||
|
||||
hasEvidence(evidenceId: string): boolean {
|
||||
return this.#evidence.has(evidenceId);
|
||||
return this.#records.hasEvidence(evidenceId);
|
||||
}
|
||||
|
||||
evidenceById(evidenceId: string): Evidence | undefined {
|
||||
return this.#evidence.get(evidenceId);
|
||||
return this.#records.evidenceById(evidenceId);
|
||||
}
|
||||
|
||||
exportEvidenceBundle(): EvidenceBundle {
|
||||
return this.#evidence.export();
|
||||
return this.#records.exportEvidenceBundle();
|
||||
}
|
||||
|
||||
importEvidenceBundle(
|
||||
bundle: unknown,
|
||||
): Result<number, EvidenceIntegrityError> {
|
||||
const imported = this.#evidence.import(bundle);
|
||||
const imported = this.#records.mergeEvidenceBundle(bundle);
|
||||
if (!imported.ok) return imported;
|
||||
if (imported.value.changed) this.#emitSnapshotChanged();
|
||||
return ok(imported.value.recordsAdded);
|
||||
@@ -95,8 +94,11 @@ export abstract class BinarySessionRecords {
|
||||
target,
|
||||
profile,
|
||||
target === undefined
|
||||
? this.#evidence.export()
|
||||
: evidenceBundleForTarget(this.#evidence.export(), target.sha256),
|
||||
? this.#records.exportEvidenceBundle()
|
||||
: evidenceBundleForTarget(
|
||||
this.#records.exportEvidenceBundle(),
|
||||
target.sha256,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -116,7 +118,7 @@ export abstract class BinarySessionRecords {
|
||||
? undefined
|
||||
: { target: active.target, profile: active.profile },
|
||||
(bundle) => {
|
||||
const imported = this.#evidence.import(bundle);
|
||||
const imported = this.#records.mergeEvidenceBundle(bundle);
|
||||
return imported.ok ? ok(imported.value.recordsAdded) : imported;
|
||||
},
|
||||
);
|
||||
@@ -175,7 +177,7 @@ export abstract class BinarySessionRecords {
|
||||
}
|
||||
|
||||
protected clearSessionRecords(): void {
|
||||
this.#evidence.clear();
|
||||
this.#records.clear();
|
||||
this.#snapshot.clear();
|
||||
this.#snapshotInvalidated = false;
|
||||
this.#emitSnapshotChanged();
|
||||
@@ -202,10 +204,7 @@ export abstract class BinarySessionRecords {
|
||||
input: RecordUnknownInput,
|
||||
): Result<ResidualUnknown, AnalysisError> {
|
||||
const target = this.activeAnalysisBinding()?.target;
|
||||
const recorded = this.#evidence.recordUnknown(
|
||||
input,
|
||||
unknownMutationEvidence(target, input),
|
||||
);
|
||||
const recorded = this.#records.recordUnknown(input, target);
|
||||
if (recorded.ok) this.#emitSnapshotChanged();
|
||||
return recorded;
|
||||
}
|
||||
@@ -214,11 +213,7 @@ export abstract class BinarySessionRecords {
|
||||
evidence: Evidence,
|
||||
input: RecordUnknownInput,
|
||||
): Result<ResidualUnknown | null, AnalysisError> {
|
||||
const recorded = this.#evidence.recordWithUnknown(
|
||||
evidence,
|
||||
input,
|
||||
unknownMutationEvidence(undefined, input),
|
||||
);
|
||||
const recorded = this.#records.recordEvidenceWithUnknown(evidence, input);
|
||||
if (recorded.ok) this.#emitSnapshotChanged();
|
||||
return recorded;
|
||||
}
|
||||
@@ -227,22 +222,7 @@ export abstract class BinarySessionRecords {
|
||||
input: UpdateUnknownInput,
|
||||
): Result<ResidualUnknown, AnalysisError> {
|
||||
const target = this.activeAnalysisBinding()?.target;
|
||||
const evidence = createEvidence(target, UNKNOWN_REGISTRY_PROVIDER, {
|
||||
predicateType: "rea.residual-unknown-mutation",
|
||||
operation: "update_unknown",
|
||||
parameters: {
|
||||
unknown_id: input.unknown_id,
|
||||
expected_revision: input.expected_revision,
|
||||
},
|
||||
result: { action: "update", status: input.status },
|
||||
confidence: "derived",
|
||||
authority: "analyst-inference",
|
||||
evidenceLinks: unknownEvidenceLinks(input),
|
||||
limitations: [
|
||||
"Registry mutation evidence records analyst intent, not proof of the answer.",
|
||||
],
|
||||
});
|
||||
const updated = this.#evidence.updateUnknown(input, evidence);
|
||||
const updated = this.#records.updateUnknown(input, target);
|
||||
if (updated.ok) this.#emitSnapshotChanged();
|
||||
return updated;
|
||||
}
|
||||
@@ -254,7 +234,7 @@ export abstract class BinarySessionRecords {
|
||||
readonly domain?: string;
|
||||
} = {},
|
||||
): ResidualUnknown[] {
|
||||
return this.#evidence.listUnknowns(filters);
|
||||
return this.#records.listUnknowns(filters);
|
||||
}
|
||||
|
||||
verifyUnknownResolution(unknownId: string): Result<
|
||||
@@ -265,6 +245,6 @@ export abstract class BinarySessionRecords {
|
||||
},
|
||||
UnknownRegistryError
|
||||
> {
|
||||
return this.#evidence.verifyUnknownResolution(unknownId);
|
||||
return this.#records.verifyUnknownResolution(unknownId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
} from "../contracts/toolOutputSchemaPrimitives.js";
|
||||
import type { ToolKind } from "../contracts/toolContractTypes.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { GENERATED_MCP_TOOL_CATALOG } from "../generatedMcpToolCatalog.js";
|
||||
import { TOOL_CONTRACTS } from "../contracts/toolContracts.js";
|
||||
import {
|
||||
clientRequirementsFor,
|
||||
NO_CLIENT_FEATURES,
|
||||
@@ -131,7 +131,7 @@ export const buildCapabilityInventory = (
|
||||
const descriptors = new Map<string, ProviderDescriptor>(
|
||||
status.capabilities.map((descriptor) => [descriptor.operation, descriptor]),
|
||||
);
|
||||
return GENERATED_MCP_TOOL_CATALOG.map((contract): ToolAvailability => {
|
||||
return TOOL_CONTRACTS.map((contract): ToolAvailability => {
|
||||
const availability = availabilityFor({
|
||||
name: contract.name,
|
||||
kind: contract.kind,
|
||||
@@ -246,7 +246,7 @@ const workflowAvailabilityFor = ({
|
||||
: {
|
||||
reason: "provider_missing",
|
||||
remediation:
|
||||
"On Linux, provide an absolute REA_BINWALK_COMMAND (Binwalk 3.1.0) or REA_UNBLOB_COMMAND (Unblob 26.6.4) path and util-linux prlimit. Extraction also requires the selected format’s external extractor.",
|
||||
"On Linux, provide an absolute REA_BINWALK_COMMAND (Binwalk 3.1.x, verified with 3.1.0) or REA_UNBLOB_COMMAND (Unblob 26.6.x, verified with 26.6.4) path and util-linux prlimit. Extraction also requires the selected format’s external extractor.",
|
||||
};
|
||||
}
|
||||
if (kind === "android-provider")
|
||||
|
||||
@@ -75,7 +75,12 @@ export const analyzeJavaScriptApplicationValidated = async (
|
||||
} catch (cause: unknown) {
|
||||
if (cause instanceof ArtifactReaderFailure)
|
||||
return err(
|
||||
new ArtifactOperationError(OPERATION, cause.reason, cause.details),
|
||||
new ArtifactOperationError(
|
||||
OPERATION,
|
||||
cause.reason,
|
||||
cause.details,
|
||||
cause.message,
|
||||
),
|
||||
);
|
||||
if (cause instanceof z.ZodError)
|
||||
return err(
|
||||
|
||||
@@ -40,12 +40,12 @@ export class LazyAnalysisProvider implements AnalysisProvider {
|
||||
this.#loadProvider = options.load;
|
||||
}
|
||||
|
||||
/** Return generated provider identity without loading its implementation. */
|
||||
/** Return source-declared provider identity without loading its implementation. */
|
||||
identity(): ProviderIdentity {
|
||||
return this.#providerIdentity;
|
||||
}
|
||||
|
||||
/** Return generated capability metadata without loading its implementation. */
|
||||
/** Return source-declared capability metadata without loading its implementation. */
|
||||
capabilities(): readonly CapabilityDescriptor[] {
|
||||
return this.#capabilityDescriptors;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import type { Evidence } from "../../domain/evidence.js";
|
||||
import type { EvidenceBundle } from "../../domain/evidenceBundle.js";
|
||||
import type { EvidenceIntegrityError } from "../../domain/evidenceErrors.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import type { UnknownRegistryError } from "../../domain/unknownRegistryError.js";
|
||||
import type {
|
||||
RecordUnknownInput,
|
||||
ResidualUnknown,
|
||||
UnknownStatus,
|
||||
UpdateUnknownInput,
|
||||
} from "../../domain/residualUnknown.js";
|
||||
import type { Result } from "../../domain/result.js";
|
||||
|
||||
/** Detached investigation Evidence reads without target execution or lifecycle authority. */
|
||||
export interface EvidenceReader {
|
||||
hasEvidence(evidenceId: string): boolean;
|
||||
evidenceById(evidenceId: string): Evidence | undefined;
|
||||
exportEvidenceBundle(): EvidenceBundle;
|
||||
}
|
||||
|
||||
/** Idempotent investigation Evidence writes without target execution. */
|
||||
export interface EvidenceWriter {
|
||||
recordEvidence(
|
||||
evidence: Evidence,
|
||||
): Result<"added" | "duplicate", EvidenceIntegrityError>;
|
||||
}
|
||||
|
||||
/** Atomic derived Evidence and linked Unknown writes. */
|
||||
export interface EvidenceUnknownWriter {
|
||||
recordEvidenceWithUnknown(
|
||||
evidence: Evidence,
|
||||
input: RecordUnknownInput,
|
||||
): Result<ResidualUnknown | null, AnalysisError>;
|
||||
}
|
||||
|
||||
/** Optimistic Unknown revisions and consistency verification. */
|
||||
export interface UnknownRegistryPort {
|
||||
recordUnknown(
|
||||
input: RecordUnknownInput,
|
||||
): Result<ResidualUnknown, AnalysisError>;
|
||||
updateUnknown(
|
||||
input: UpdateUnknownInput,
|
||||
): Result<ResidualUnknown, AnalysisError>;
|
||||
listUnknowns(filters?: {
|
||||
readonly status?: UnknownStatus;
|
||||
readonly severity?: ResidualUnknown["severity"];
|
||||
readonly domain?: string;
|
||||
}): ResidualUnknown[];
|
||||
verifyUnknownResolution(unknownId: string): Result<
|
||||
{
|
||||
readonly valid: boolean;
|
||||
readonly truthVerified: boolean;
|
||||
readonly unknown: ResidualUnknown;
|
||||
},
|
||||
UnknownRegistryError
|
||||
>;
|
||||
}
|
||||
|
||||
/** Compatibility record surface; binary execution and snapshots remain separate. */
|
||||
export interface InvestigationRecordPort
|
||||
extends
|
||||
EvidenceReader,
|
||||
EvidenceWriter,
|
||||
EvidenceUnknownWriter,
|
||||
UnknownRegistryPort {
|
||||
importEvidenceBundle(bundle: unknown): Result<number, EvidenceIntegrityError>;
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
ANALYSIS_SNAPSHOT_TARGET as target,
|
||||
ANALYSIS_SNAPSHOT_PROVIDER as provider,
|
||||
} from "../../domain/analysisSnapshot.fixture.js";
|
||||
import { createEvidence } from "../../domain/evidence.js";
|
||||
import { createEvidenceBundle } from "../../domain/evidenceBundle.js";
|
||||
import {
|
||||
recordUnknownInputSchema,
|
||||
updateUnknownInputSchema,
|
||||
} from "../../domain/residualUnknown.js";
|
||||
import { unknownMutationEvidence } from "../UnknownEvidence.js";
|
||||
import { InvestigationRecords } from "./InvestigationRecords.js";
|
||||
|
||||
const unknownInput = (question: string) =>
|
||||
recordUnknownInputSchema.parse({
|
||||
question,
|
||||
severity: "medium",
|
||||
domain: "investigation",
|
||||
required_authority: "analyst-inference",
|
||||
required_confidence: "derived",
|
||||
required_environment: null,
|
||||
recommended_probes: [],
|
||||
relationships: [],
|
||||
});
|
||||
const evidence = createEvidence(undefined, provider, {
|
||||
operation: "inspect-fixture",
|
||||
parameters: {},
|
||||
result: true,
|
||||
confidence: "derived",
|
||||
authority: "analyst-inference",
|
||||
});
|
||||
|
||||
describe("investigation record ownership", () => {
|
||||
it("keeps identity, detached reads and independent stores without a binary target", () => {
|
||||
const records = new InvestigationRecords();
|
||||
expect(records.recordEvidence(evidence)).toEqual({
|
||||
ok: true,
|
||||
value: "added",
|
||||
});
|
||||
expect(records.recordEvidence(evidence)).toEqual({
|
||||
ok: true,
|
||||
value: "duplicate",
|
||||
});
|
||||
const read = records.evidenceById(evidence.evidence_id);
|
||||
if (read === undefined) throw new Error("Missing recorded Evidence");
|
||||
Reflect.set(read, "operation", "forged");
|
||||
expect(records.evidenceById(evidence.evidence_id)).toEqual(evidence);
|
||||
expect(new InvestigationRecords().hasEvidence(evidence.evidence_id)).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
it("preserves explicit Unknown subjects and target-free atomic mutation subjects", () => {
|
||||
const records = new InvestigationRecords();
|
||||
const input = unknownInput("Which target supplies this observation?");
|
||||
const bound = records.recordUnknown(input, target);
|
||||
expect(bound).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
scope_digest: target.sha256,
|
||||
mutation_evidence_ids: [
|
||||
unknownMutationEvidence(target, input).evidence_id,
|
||||
],
|
||||
},
|
||||
});
|
||||
const independent = records.recordEvidenceWithUnknown(evidence, input);
|
||||
expect(independent).toMatchObject({
|
||||
ok: true,
|
||||
value: {
|
||||
scope_digest: null,
|
||||
mutation_evidence_ids: [
|
||||
unknownMutationEvidence(undefined, input).evidence_id,
|
||||
],
|
||||
},
|
||||
});
|
||||
const mutation = records.evidenceById(
|
||||
unknownMutationEvidence(undefined, input).evidence_id,
|
||||
);
|
||||
expect(mutation?.subject).toBeNull();
|
||||
expect(records.listUnknowns()).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("rolls back Evidence when the linked Unknown fails validation", () => {
|
||||
const records = new InvestigationRecords();
|
||||
const invalid = {
|
||||
...unknownInput("Is the missing Evidence present?"),
|
||||
supporting_evidence_ids: [`ev_${"f".repeat(64)}`],
|
||||
};
|
||||
expect(records.recordEvidenceWithUnknown(evidence, invalid).ok).toBe(false);
|
||||
expect(records.hasEvidence(evidence.evidence_id)).toBe(false);
|
||||
expect(records.exportEvidenceBundle()).toEqual(createEvidenceBundle([]));
|
||||
});
|
||||
|
||||
it("preserves optimistic revisions and the explicit update subject", () => {
|
||||
const records = new InvestigationRecords();
|
||||
const created = records.recordUnknown(
|
||||
unknownInput("Can this revision be updated?"),
|
||||
target,
|
||||
);
|
||||
if (!created.ok) throw created.error;
|
||||
const input = updateUnknownInputSchema.parse({
|
||||
...created.value,
|
||||
expected_revision: created.value.revision,
|
||||
status: "investigating",
|
||||
});
|
||||
const updated = records.updateUnknown(input, target);
|
||||
expect(updated).toMatchObject({
|
||||
ok: true,
|
||||
value: { revision: 2, scope_digest: target.sha256 },
|
||||
});
|
||||
const bundle = records.exportEvidenceBundle();
|
||||
expect(
|
||||
bundle.records.find(({ operation }) => operation === "update_unknown")
|
||||
?.subject?.digest.sha256,
|
||||
).toBe(target.sha256);
|
||||
expect(records.updateUnknown(input, target).ok).toBe(false);
|
||||
expect(records.exportEvidenceBundle()).toEqual(bundle);
|
||||
});
|
||||
|
||||
it("reports Unknown-only bundle changes and clears the single record owner", () => {
|
||||
const source = new InvestigationRecords();
|
||||
expect(
|
||||
source.recordUnknown(
|
||||
unknownInput("Can imported Unknowns notify observers?"),
|
||||
).ok,
|
||||
).toBe(true);
|
||||
const bundle = source.exportEvidenceBundle();
|
||||
const records = new InvestigationRecords();
|
||||
expect(
|
||||
records.mergeEvidenceBundle(createEvidenceBundle(bundle.records)).ok,
|
||||
).toBe(true);
|
||||
expect(records.mergeEvidenceBundle(bundle)).toEqual({
|
||||
ok: true,
|
||||
value: { recordsAdded: 0, unknownsAdded: 1, changed: true },
|
||||
});
|
||||
expect(records.mergeEvidenceBundle(bundle)).toEqual({
|
||||
ok: true,
|
||||
value: { recordsAdded: 0, unknownsAdded: 0, changed: false },
|
||||
});
|
||||
records.clear();
|
||||
expect(records.exportEvidenceBundle()).toEqual(createEvidenceBundle([]));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,142 @@
|
||||
import type { BinaryTarget } from "../../domain/binaryTarget.js";
|
||||
import { createEvidence, type Evidence } from "../../domain/evidence.js";
|
||||
import type { EvidenceBundle } from "../../domain/evidenceBundle.js";
|
||||
import type { EvidenceIntegrityError } from "../../domain/evidenceErrors.js";
|
||||
import type { AnalysisError } from "../../domain/analysisErrorBase.js";
|
||||
import type { UnknownRegistryError } from "../../domain/unknownRegistryError.js";
|
||||
import type {
|
||||
RecordUnknownInput,
|
||||
ResidualUnknown,
|
||||
UnknownStatus,
|
||||
UpdateUnknownInput,
|
||||
} from "../../domain/residualUnknown.js";
|
||||
import type { Result } from "../../domain/result.js";
|
||||
import { EvidenceLedger, type EvidenceImportDelta } from "../EvidenceLedger.js";
|
||||
import {
|
||||
UNKNOWN_REGISTRY_PROVIDER,
|
||||
unknownEvidenceLinks,
|
||||
unknownMutationEvidence,
|
||||
} from "../UnknownEvidence.js";
|
||||
import type {
|
||||
EvidenceReader,
|
||||
EvidenceWriter,
|
||||
EvidenceUnknownWriter,
|
||||
UnknownRegistryPort,
|
||||
} from "./InvestigationRecordPort.js";
|
||||
|
||||
/** One investigation's validated record owner, independent of binary execution. */
|
||||
export class InvestigationRecords
|
||||
implements
|
||||
EvidenceReader,
|
||||
EvidenceWriter,
|
||||
EvidenceUnknownWriter,
|
||||
UnknownRegistryPort
|
||||
{
|
||||
readonly #evidence = new EvidenceLedger();
|
||||
|
||||
/** Record immutable Evidence idempotently; reject conflicting content. */
|
||||
recordEvidence(
|
||||
evidence: Evidence,
|
||||
): Result<"added" | "duplicate", EvidenceIntegrityError> {
|
||||
return this.#evidence.record(evidence);
|
||||
}
|
||||
|
||||
/** Check one semantic Evidence ID without exposing stored values. */
|
||||
hasEvidence(evidenceId: string): boolean {
|
||||
return this.#evidence.has(evidenceId);
|
||||
}
|
||||
|
||||
/** Return a detached Evidence value for one semantic ID. */
|
||||
evidenceById(evidenceId: string): Evidence | undefined {
|
||||
return this.#evidence.get(evidenceId);
|
||||
}
|
||||
|
||||
/** Export a detached deterministic bundle of Evidence and Unknown revisions. */
|
||||
exportEvidenceBundle(): EvidenceBundle {
|
||||
return this.#evidence.export();
|
||||
}
|
||||
|
||||
/** Atomically merge a bundle and report changes for the owner's post-commit observers. */
|
||||
mergeEvidenceBundle(
|
||||
bundle: unknown,
|
||||
): Result<EvidenceImportDelta, EvidenceIntegrityError> {
|
||||
return this.#evidence.import(bundle);
|
||||
}
|
||||
|
||||
/** Clear records when the owning runtime applies its existing lifecycle policy. */
|
||||
clear(): void {
|
||||
this.#evidence.clear();
|
||||
}
|
||||
|
||||
/** Record an Unknown with an explicitly supplied Evidence subject, if any. */
|
||||
recordUnknown(
|
||||
input: RecordUnknownInput,
|
||||
target?: BinaryTarget,
|
||||
): Result<ResidualUnknown, AnalysisError> {
|
||||
const recorded = this.#evidence.recordUnknown(
|
||||
input,
|
||||
unknownMutationEvidence(target, input),
|
||||
);
|
||||
return recorded;
|
||||
}
|
||||
|
||||
/** Commit derived Evidence and its Unknown atomically without an implicit subject. */
|
||||
recordEvidenceWithUnknown(
|
||||
evidence: Evidence,
|
||||
input: RecordUnknownInput,
|
||||
): Result<ResidualUnknown | null, AnalysisError> {
|
||||
const recorded = this.#evidence.recordWithUnknown(
|
||||
evidence,
|
||||
input,
|
||||
unknownMutationEvidence(undefined, input),
|
||||
);
|
||||
return recorded;
|
||||
}
|
||||
|
||||
/** Update an optimistic revision with an explicitly supplied Evidence subject. */
|
||||
updateUnknown(
|
||||
input: UpdateUnknownInput,
|
||||
target?: BinaryTarget,
|
||||
): Result<ResidualUnknown, AnalysisError> {
|
||||
const evidence = createEvidence(target, UNKNOWN_REGISTRY_PROVIDER, {
|
||||
predicateType: "rea.residual-unknown-mutation",
|
||||
operation: "update_unknown",
|
||||
parameters: {
|
||||
unknown_id: input.unknown_id,
|
||||
expected_revision: input.expected_revision,
|
||||
},
|
||||
result: { action: "update", status: input.status },
|
||||
confidence: "derived",
|
||||
authority: "analyst-inference",
|
||||
evidenceLinks: unknownEvidenceLinks(input),
|
||||
limitations: [
|
||||
"Registry mutation evidence records analyst intent, not proof of the answer.",
|
||||
],
|
||||
});
|
||||
const updated = this.#evidence.updateUnknown(input, evidence);
|
||||
return updated;
|
||||
}
|
||||
|
||||
/** Return detached current Unknown revisions matching the selected filters. */
|
||||
listUnknowns(
|
||||
filters: {
|
||||
readonly status?: UnknownStatus;
|
||||
readonly severity?: ResidualUnknown["severity"];
|
||||
readonly domain?: string;
|
||||
} = {},
|
||||
): ResidualUnknown[] {
|
||||
return this.#evidence.listUnknowns(filters);
|
||||
}
|
||||
|
||||
/** Verify registry consistency without asserting the answer is true. */
|
||||
verifyUnknownResolution(unknownId: string): Result<
|
||||
{
|
||||
readonly valid: boolean;
|
||||
readonly truthVerified: boolean;
|
||||
readonly unknown: ResidualUnknown;
|
||||
},
|
||||
UnknownRegistryError
|
||||
> {
|
||||
return this.#evidence.verifyUnknownResolution(unknownId);
|
||||
}
|
||||
}
|
||||
@@ -4,10 +4,9 @@ import { HopperProvider } from "../hopper/HopperProvider.js";
|
||||
import { GhidraProvider } from "../ghidra/GhidraProvider.js";
|
||||
import { IdaProvider } from "../ida/IdaProvider.js";
|
||||
import { silentLogger, type Logger } from "../logger.js";
|
||||
import { GENERATED_AUXILIARY_PROVIDERS } from "../generatedMcpToolCatalog.js";
|
||||
import { auxiliaryAnalysisProviderDeclarations } from "../composition/auxiliaryAnalysisProviders.js";
|
||||
import { AnalysisProviderRegistry } from "./AnalysisProviderRegistry.js";
|
||||
import { composeBinarySession } from "./BinarySessionComposition.js";
|
||||
import { nativeHostCapabilities } from "../native/NativeHostCapabilities.js";
|
||||
import { LazyAnalysisProvider } from "./LazyAnalysisProvider.js";
|
||||
import { ManagedStaticProvider } from "../dotnet/ManagedStaticProvider.js";
|
||||
import { SessionProviderRouter } from "./SessionProviderRouter.js";
|
||||
@@ -24,47 +23,14 @@ export const createBinarySession = (
|
||||
const hopper = new HopperProvider(config, logger);
|
||||
const ghidra = new GhidraProvider(config, logger);
|
||||
const ida = new IdaProvider(config);
|
||||
const auxiliary = new Map(
|
||||
GENERATED_AUXILIARY_PROVIDERS.map((provider) => [
|
||||
provider.identity.id,
|
||||
provider,
|
||||
]),
|
||||
);
|
||||
const lazyProvider = (
|
||||
id: string,
|
||||
load: ConstructorParameters<typeof LazyAnalysisProvider>[0]["load"],
|
||||
) => {
|
||||
const generated = auxiliary.get(id);
|
||||
if (generated === undefined)
|
||||
throw new TypeError(`Missing generated provider metadata for ${id}`);
|
||||
return new LazyAnalysisProvider({
|
||||
...generated,
|
||||
capabilities: nativeHostCapabilities(generated.capabilities),
|
||||
load,
|
||||
});
|
||||
};
|
||||
return composeBinarySession(
|
||||
new AnalysisProviderRegistry(
|
||||
[hopper, ghidra, ida],
|
||||
config.analysisProvider,
|
||||
),
|
||||
[
|
||||
lazyProvider("rea-artifact-graph", async () => {
|
||||
const { ArtifactProvider } =
|
||||
await import("../artifacts/ArtifactProvider.js");
|
||||
return new ArtifactProvider();
|
||||
}),
|
||||
lazyProvider("native-macos", async () => {
|
||||
const { NativeMacOSProvider } =
|
||||
await import("../native/NativeMacOSProvider.js");
|
||||
return new NativeMacOSProvider();
|
||||
}),
|
||||
lazyProvider("rea-dotnet-static", async () => {
|
||||
const { ManagedStaticProvider } =
|
||||
await import("../dotnet/ManagedStaticProvider.js");
|
||||
return new ManagedStaticProvider();
|
||||
}),
|
||||
],
|
||||
auxiliaryAnalysisProviderDeclarations().map(
|
||||
(declaration) => new LazyAnalysisProvider(declaration),
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ export const normalizeArtifactPath = (input: string): string => {
|
||||
)
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
"Artifact path is absolute or unsafe",
|
||||
`Artifact path is absolute or unsafe: ${JSON.stringify(input)}`,
|
||||
);
|
||||
const normalized = input.normalize("NFC").replace(/\/+$/u, "");
|
||||
const parts = normalized.split("/");
|
||||
@@ -23,7 +23,10 @@ export const normalizeArtifactPath = (input: string): string => {
|
||||
parts.some((part) => part === "" || part === "." || part === "..") ||
|
||||
posix.normalize(normalized) !== normalized
|
||||
)
|
||||
throw new ArtifactReaderFailure("path", "Artifact path is not normalized");
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
`Artifact path is not normalized: ${JSON.stringify(input)}`,
|
||||
);
|
||||
return normalized;
|
||||
};
|
||||
|
||||
@@ -45,7 +48,7 @@ export class ArtifactPathRegistry {
|
||||
if (child !== undefined && child.spelling !== part)
|
||||
throw new ArtifactReaderFailure(
|
||||
"path",
|
||||
`Artifact path collision: ${path}`,
|
||||
`Artifact path collision: ${path} differs only in case from ${[...parts.slice(0, index), child.spelling].join("/")}`,
|
||||
);
|
||||
if (child === undefined) {
|
||||
child = { spelling: part, kind: undefined, children: new Map() };
|
||||
|
||||
@@ -27,54 +27,20 @@ import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { interfaceBuilderLimitsSchema } from "../domain/interfaceBuilderGraph.js";
|
||||
import { err, ok } from "../domain/result.js";
|
||||
import { ArtifactReaderFailure } from "./ArtifactReader.js";
|
||||
import { ARTIFACT_GRAPH_PROVIDER } from "../application/InvestigationProviders.js";
|
||||
import {
|
||||
ARTIFACT_PROVIDER_IDENTITY as IDENTITY,
|
||||
artifactCapabilities,
|
||||
} from "./ArtifactProviderMetadata.js";
|
||||
import { createEvidence } from "../domain/evidence.js";
|
||||
import { createArtifactInspection } from "../domain/artifactInspection.js";
|
||||
import { resolveArtifactIntegrityPolicy } from "../application/ArtifactInventory/policy.js";
|
||||
|
||||
const IDENTITY: ProviderIdentity = Object.freeze(ARTIFACT_GRAPH_PROVIDER);
|
||||
|
||||
/** Read-only inventory and exclusively owned extraction provider. */
|
||||
export class ArtifactProvider implements AnalysisProvider {
|
||||
readonly #capabilities: readonly CapabilityDescriptor[];
|
||||
|
||||
constructor(platform: NodeJS.Platform = process.platform) {
|
||||
this.#capabilities = Object.freeze(
|
||||
ARTIFACT_ANALYSIS_OPERATIONS.map((operation) => {
|
||||
const common = {
|
||||
provider: IDENTITY,
|
||||
operation,
|
||||
effects: Object.freeze({
|
||||
mutatesArtifact: false,
|
||||
launchesProcess:
|
||||
operation !== "decode_interface_builder" &&
|
||||
operation !== "inspect_keyed_archive",
|
||||
mayShowUi: false,
|
||||
mayAccessNetwork: false,
|
||||
mayWriteFilesystem:
|
||||
operation === "extract_artifact" ||
|
||||
operation === "inspect_artifact" ||
|
||||
operation === "inventory_artifact",
|
||||
changesPermissions: false,
|
||||
requiresRoot: false,
|
||||
}),
|
||||
limitations: Object.freeze([
|
||||
"DMG child inventory automatically uses a read-only native macOS mount; PKG remains root-hash-only.",
|
||||
"ASAR files discovered in filesystem-backed inventories are expanded without bulk extraction; other nested containers remain recorded only.",
|
||||
]),
|
||||
};
|
||||
return Object.freeze(
|
||||
operation === "inspect_asset_catalog" && platform !== "darwin"
|
||||
? {
|
||||
...common,
|
||||
available: false as const,
|
||||
availabilityCode: "unsupported_host" as const,
|
||||
reason: "Apple asset catalogs require macOS assetutil.",
|
||||
}
|
||||
: { ...common, available: true as const, reason: null },
|
||||
);
|
||||
}),
|
||||
);
|
||||
this.#capabilities = artifactCapabilities(platform);
|
||||
}
|
||||
|
||||
identity(): ProviderIdentity {
|
||||
@@ -343,7 +309,12 @@ const translateFailure = (
|
||||
cause: unknown,
|
||||
): AnalysisError => {
|
||||
if (cause instanceof ArtifactReaderFailure)
|
||||
return new ArtifactOperationError(operation, cause.reason, cause.details);
|
||||
return new ArtifactOperationError(
|
||||
operation,
|
||||
cause.reason,
|
||||
cause.details,
|
||||
cause.message,
|
||||
);
|
||||
return new ArtifactOperationError(operation, "io");
|
||||
};
|
||||
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import type {
|
||||
CapabilityDescriptor,
|
||||
ProviderIdentity,
|
||||
} from "../application/AnalysisProvider.js";
|
||||
import { ARTIFACT_GRAPH_PROVIDER } from "../application/InvestigationProviders.js";
|
||||
import { ARTIFACT_ANALYSIS_OPERATIONS } from "../contracts/artifactToolContracts.js";
|
||||
|
||||
/** Identity of artifact inventory and owned extraction observations. */
|
||||
export const ARTIFACT_PROVIDER_IDENTITY: ProviderIdentity = Object.freeze(
|
||||
ARTIFACT_GRAPH_PROVIDER,
|
||||
);
|
||||
const IDENTITY = ARTIFACT_PROVIDER_IDENTITY;
|
||||
|
||||
/** Declare artifact coverage without constructing readers or acquiring resources. */
|
||||
export const artifactCapabilities = (
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): readonly CapabilityDescriptor[] =>
|
||||
Object.freeze(
|
||||
ARTIFACT_ANALYSIS_OPERATIONS.map((operation) => {
|
||||
const common = {
|
||||
provider: IDENTITY,
|
||||
operation,
|
||||
effects: Object.freeze({
|
||||
mutatesArtifact: false,
|
||||
launchesProcess:
|
||||
operation !== "decode_interface_builder" &&
|
||||
operation !== "inspect_keyed_archive",
|
||||
mayShowUi: false,
|
||||
mayAccessNetwork: false,
|
||||
mayWriteFilesystem:
|
||||
operation === "extract_artifact" ||
|
||||
operation === "inspect_artifact" ||
|
||||
operation === "inventory_artifact",
|
||||
changesPermissions: false,
|
||||
requiresRoot: false,
|
||||
}),
|
||||
limitations: Object.freeze([
|
||||
"DMG child inventory automatically uses a read-only native macOS mount; PKG remains root-hash-only.",
|
||||
"ASAR files discovered in filesystem-backed inventories are expanded without bulk extraction; other nested containers remain recorded only.",
|
||||
]),
|
||||
};
|
||||
return Object.freeze(
|
||||
operation === "inspect_asset_catalog" && platform !== "darwin"
|
||||
? {
|
||||
...common,
|
||||
available: false as const,
|
||||
availabilityCode: "unsupported_host" as const,
|
||||
reason: "Apple asset catalogs require macOS assetutil.",
|
||||
}
|
||||
: { ...common, available: true as const, reason: null },
|
||||
);
|
||||
}),
|
||||
);
|
||||
@@ -3,6 +3,7 @@ import { TextDecoder } from "node:util";
|
||||
import { parse, parseBinary } from "plist";
|
||||
import { z } from "zod";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import { projectPlistValue } from "../domain/plistValue.js";
|
||||
import {
|
||||
keyedArchiveInputSchema,
|
||||
keyedArchiveResultSchema,
|
||||
@@ -50,27 +51,11 @@ const decodeXmlPlistText = (bytes: Buffer): string => {
|
||||
return text;
|
||||
};
|
||||
|
||||
const normalizePlist = (value: unknown, depth = 0): JsonValue => {
|
||||
if (depth > 128) throw new RangeError("Plist exceeds 128 nesting levels");
|
||||
if (value instanceof Uint8Array)
|
||||
return {
|
||||
$plist_type: "data",
|
||||
base64: Buffer.from(value).toString("base64"),
|
||||
};
|
||||
if (value instanceof Date)
|
||||
return { $plist_type: "date", iso8601: value.toISOString() };
|
||||
if (Array.isArray(value))
|
||||
return value.map((item: unknown) => normalizePlist(item, depth + 1));
|
||||
if (value !== null && typeof value === "object")
|
||||
return Object.fromEntries(
|
||||
Object.entries(value).map(([key, item]) => [
|
||||
key,
|
||||
normalizePlist(item, depth + 1),
|
||||
]),
|
||||
);
|
||||
return z
|
||||
.union([z.string(), z.number().finite(), z.boolean(), z.null()])
|
||||
.parse(value);
|
||||
const normalizePlist = (value: unknown): JsonValue => {
|
||||
const projected = projectPlistValue(value);
|
||||
if (projected.unknownRealCount > 0)
|
||||
throw new RangeError("Keyed archive contains a non-finite real");
|
||||
return projected.value;
|
||||
};
|
||||
|
||||
/** Read exactly one regular, contained bundle entry without following symlinks. */
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import type { LazyAnalysisProvider } from "../application/LazyAnalysisProvider.js";
|
||||
import {
|
||||
ARTIFACT_PROVIDER_IDENTITY,
|
||||
artifactCapabilities,
|
||||
} from "../artifacts/ArtifactProviderMetadata.js";
|
||||
import {
|
||||
MANAGED_STATIC_PROVIDER_IDENTITY,
|
||||
managedStaticCapabilities,
|
||||
} from "../dotnet/ManagedStaticProviderMetadata.js";
|
||||
import {
|
||||
NATIVE_MACOS_PROVIDER_IDENTITY,
|
||||
nativeMacOSCapabilities,
|
||||
} from "../native/NativeMacOSProviderMetadata.js";
|
||||
|
||||
type AuxiliaryProviderDeclaration = ConstructorParameters<
|
||||
typeof LazyAnalysisProvider
|
||||
>[0];
|
||||
|
||||
/** Wire the three existing auxiliary AnalysisProvider implementations lazily. */
|
||||
export const auxiliaryAnalysisProviderDeclarations = (
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): readonly AuxiliaryProviderDeclaration[] => [
|
||||
{
|
||||
identity: ARTIFACT_PROVIDER_IDENTITY,
|
||||
capabilities: artifactCapabilities(platform),
|
||||
load: async () => {
|
||||
const { ArtifactProvider } =
|
||||
await import("../artifacts/ArtifactProvider.js");
|
||||
return new ArtifactProvider(platform);
|
||||
},
|
||||
},
|
||||
{
|
||||
identity: NATIVE_MACOS_PROVIDER_IDENTITY,
|
||||
capabilities: nativeMacOSCapabilities(platform),
|
||||
load: async () => {
|
||||
const { NativeMacOSProvider } =
|
||||
await import("../native/NativeMacOSProvider.js");
|
||||
return new NativeMacOSProvider(undefined, platform);
|
||||
},
|
||||
},
|
||||
{
|
||||
identity: MANAGED_STATIC_PROVIDER_IDENTITY,
|
||||
capabilities: managedStaticCapabilities(),
|
||||
load: async () => {
|
||||
const { ManagedStaticProvider } =
|
||||
await import("../dotnet/ManagedStaticProvider.js");
|
||||
return new ManagedStaticProvider();
|
||||
},
|
||||
},
|
||||
];
|
||||
@@ -13,7 +13,7 @@ export const FIRMWARE_TOOL_CONTRACTS = [
|
||||
...toolContractMetadata("inspect_firmware_regions"),
|
||||
kind: "firmware-provider",
|
||||
description:
|
||||
"Inspect signature candidates in a local firmware file with Binwalk 3.1.0. Returns offsets, reported lengths, descriptions and raw confidence values. Length validation and runtime addresses remain unknown. No extraction or target execution. Linux, caller-supplied tool and util-linux prlimit required; 128 MiB input limit, one worker and 120-second deadline.",
|
||||
"Inspect signature candidates in a local firmware file with Binwalk 3.1.x (verified with 3.1.0). Returns offsets, reported lengths, descriptions and raw confidence values. Length validation and runtime addresses remain unknown. No extraction or target execution. Linux, caller-supplied tool and util-linux prlimit required; 128 MiB input limit, one worker and 120-second deadline.",
|
||||
inputSchema: firmwareInputSchemas.inspect_firmware_regions,
|
||||
outputSchema: evidenceResultOf(
|
||||
firmwareResultSchemas.inspect_firmware_regions,
|
||||
@@ -30,7 +30,7 @@ export const FIRMWARE_TOOL_CONTRACTS = [
|
||||
...toolContractMetadata("extract_firmware"),
|
||||
kind: "firmware-provider",
|
||||
description:
|
||||
"Extract caller-selected firmware bytes with Unblob 26.6.4 into an absent output directory. Returns verified child paths/digests, task derivations, unknown chunks and extraction diagnostics inline. Preserves the default sandbox; publishes regular files only. Linux, caller-supplied tool, format-specific extractors and util-linux prlimit required. No mounts or extracted-code execution. Select a returned native file with open_binary for Ghidra analysis; decompressed offsets are not original-file addresses.",
|
||||
"Extract caller-selected firmware bytes with Unblob 26.6.x (verified with 26.6.4) into an absent output directory. Returns verified child paths/digests, task derivations, unknown chunks and extraction diagnostics inline. Preserves the default sandbox; publishes regular files only. Linux, caller-supplied tool, format-specific extractors and util-linux prlimit required. No mounts or extracted-code execution. Select a returned native file with open_binary for Ghidra analysis; decompressed offsets are not original-file addresses.",
|
||||
inputSchema: firmwareInputSchemas.extract_firmware,
|
||||
outputSchema: evidenceResultOf(firmwareResultSchemas.extract_firmware),
|
||||
examples: [
|
||||
|
||||
@@ -216,6 +216,7 @@ const artifactStateErrorDetails = (
|
||||
operation: error.operation,
|
||||
reason: error.reason,
|
||||
...(error.reason === "limit" ? { truncated: true } : {}),
|
||||
...(error.detail === undefined ? {} : { detail: error.detail }),
|
||||
};
|
||||
if (error instanceof UnknownRegistryError) return { reason: error.reason };
|
||||
if (error instanceof EvidenceFileError)
|
||||
|
||||
@@ -28,6 +28,8 @@ export class ArtifactOperationError extends AnalysisError {
|
||||
calculatedSha256: string | null;
|
||||
unpacked: boolean;
|
||||
}>,
|
||||
/** The specific constraint that failed, such as the colliding path. */
|
||||
readonly detail?: string,
|
||||
) {
|
||||
super(
|
||||
artifactDetails === undefined
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { projectPlistValue } from "./plistValue.js";
|
||||
|
||||
it("projects plist data, dates, and non-finite reals as typed values", () => {
|
||||
expect(
|
||||
projectPlistValue({
|
||||
blob: new Uint8Array([0, 1, 2]),
|
||||
when: new Date("2020-01-01T00:00:00Z"),
|
||||
nested: [{ ratio: 0.5, missing: Number.NaN, unbounded: -Infinity }],
|
||||
plain: { "": "empty key", flag: true, count: 42 },
|
||||
}),
|
||||
).toEqual({
|
||||
value: {
|
||||
blob: { $plist_type: "data", base64: "AAEC" },
|
||||
when: { $plist_type: "date", iso8601: "2020-01-01T00:00:00.000Z" },
|
||||
nested: [
|
||||
{
|
||||
ratio: 0.5,
|
||||
missing: { $plist_type: "real", value: null },
|
||||
unbounded: { $plist_type: "real", value: null },
|
||||
},
|
||||
],
|
||||
plain: { "": "empty key", flag: true, count: 42 },
|
||||
},
|
||||
unknownRealCount: 2,
|
||||
});
|
||||
});
|
||||
|
||||
it("rejects values a plist decoder cannot produce", () => {
|
||||
expect(() => projectPlistValue({ value: Symbol("x") })).toThrow();
|
||||
const deep: unknown[] = [];
|
||||
let cursor = deep;
|
||||
for (let depth = 0; depth < 200; depth += 1) {
|
||||
const next: unknown[] = [];
|
||||
cursor.push(next);
|
||||
cursor = next;
|
||||
}
|
||||
expect(() => projectPlistValue(deep)).toThrow(RangeError);
|
||||
});
|
||||
@@ -0,0 +1,50 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import type { JsonValue } from "./jsonValue.js";
|
||||
|
||||
const MAX_PLIST_DEPTH = 128;
|
||||
|
||||
/** A decoded plist projected into JSON, with values JSON cannot express. */
|
||||
export interface ProjectedPlistValue {
|
||||
readonly value: JsonValue;
|
||||
/** Reals decoded as NaN, which the decoder also uses for ±infinity. */
|
||||
readonly unknownRealCount: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Project a decoded plist into JSON. Data and dates become explicit
|
||||
* `$plist_type` objects; a non-finite real becomes an explicit unknown
|
||||
* because the XML decoder reports NaN and ±infinity alike.
|
||||
*/
|
||||
export const projectPlistValue = (value: unknown): ProjectedPlistValue => {
|
||||
let unknownRealCount = 0;
|
||||
const project = (item: unknown, depth: number): JsonValue => {
|
||||
if (depth > MAX_PLIST_DEPTH)
|
||||
throw new RangeError(
|
||||
`Plist exceeds ${String(MAX_PLIST_DEPTH)} nesting levels`,
|
||||
);
|
||||
if (item instanceof Uint8Array)
|
||||
return {
|
||||
$plist_type: "data",
|
||||
base64: Buffer.from(item).toString("base64"),
|
||||
};
|
||||
if (item instanceof Date)
|
||||
return { $plist_type: "date", iso8601: item.toISOString() };
|
||||
if (typeof item === "number" && !Number.isFinite(item)) {
|
||||
unknownRealCount += 1;
|
||||
return { $plist_type: "real", value: null };
|
||||
}
|
||||
if (Array.isArray(item))
|
||||
return item.map((entry: unknown) => project(entry, depth + 1));
|
||||
if (item !== null && typeof item === "object")
|
||||
return Object.fromEntries(
|
||||
Object.entries(item).map(([key, entry]) => [
|
||||
key,
|
||||
project(entry, depth + 1),
|
||||
]),
|
||||
);
|
||||
return z.union([z.string(), z.number(), z.boolean(), z.null()]).parse(item);
|
||||
};
|
||||
const projected = project(value, 0);
|
||||
return { value: projected, unknownRealCount };
|
||||
};
|
||||
@@ -4,43 +4,8 @@ import {
|
||||
parseArtifactInventoryEvidence,
|
||||
tryAssembleInventorySet,
|
||||
} from "./artifactInventoryEvidence.js";
|
||||
import { EvidenceReferenceError } from "./evidenceErrors.js";
|
||||
import type { ReferenceSourceReaderError } from "../reference/ReferenceSourceReaderTypes.js";
|
||||
|
||||
/**
|
||||
* The three validation taxonomies and their disjoint codes:
|
||||
* - Filesystem reader: cancelled | invalid-root | io | unsupported
|
||||
* (per-entry: cancelled | changed | io | symlink | unsupported).
|
||||
* - Session evidence references: missing | wrong_operation |
|
||||
* wrong_predicate | identity_mismatch.
|
||||
* - Inventory assembly: TypeError strings, migrating to Result leaves
|
||||
* starting with the empty-pages code below.
|
||||
*/
|
||||
const readerCodes: readonly ReferenceSourceReaderError["code"][] = [
|
||||
"cancelled",
|
||||
"invalid-root",
|
||||
"io",
|
||||
"unsupported",
|
||||
];
|
||||
|
||||
const referenceReasons = (
|
||||
[
|
||||
"missing",
|
||||
"wrong_operation",
|
||||
"wrong_predicate",
|
||||
"identity_mismatch",
|
||||
] as const
|
||||
).map(
|
||||
(reason) =>
|
||||
new EvidenceReferenceError("ev_test", reason, "expected", null).reason,
|
||||
);
|
||||
|
||||
describe("validation taxonomy mapping", () => {
|
||||
it("keeps session reference reasons disjoint from reader codes", () => {
|
||||
for (const reason of referenceReasons)
|
||||
expect(readerCodes).not.toContain(reason);
|
||||
});
|
||||
|
||||
describe("inventory validation failure channels", () => {
|
||||
it("returns the empty-pages leaf as Result without throwing", () => {
|
||||
const result = tryAssembleInventorySet([]);
|
||||
expect(result).toEqual({
|
||||
|
||||
@@ -11,7 +11,10 @@ import {
|
||||
type ExecutionOptions,
|
||||
type ProviderIdentity,
|
||||
} from "../application/AnalysisProvider.js";
|
||||
import { MANAGED_STATIC_PROVIDER } from "../application/InvestigationProviders.js";
|
||||
import {
|
||||
MANAGED_STATIC_PROVIDER_IDENTITY as IDENTITY,
|
||||
managedStaticCapabilities,
|
||||
} from "./ManagedStaticProviderMetadata.js";
|
||||
import {
|
||||
MANAGED_TOOL_CONTRACTS,
|
||||
managedArtifactInputSchema,
|
||||
@@ -38,30 +41,10 @@ import { inspectManagedArtifactBytes } from "./ManagedArtifactInspector.js";
|
||||
import { inspectManagedMembersBytes } from "./ManagedMemberInspector.js";
|
||||
import { inspectManagedNativeBoundariesBytes } from "./ManagedNativeBoundaryInspector.js";
|
||||
|
||||
const IDENTITY: ProviderIdentity = Object.freeze(MANAGED_STATIC_PROVIDER);
|
||||
|
||||
/** Execution-free managed PE/CLI auxiliary provider. */
|
||||
export class ManagedStaticProvider implements AnalysisProvider {
|
||||
readonly #capabilities: readonly CapabilityDescriptor[] = Object.freeze(
|
||||
MANAGED_TOOL_CONTRACTS.map((contract) =>
|
||||
Object.freeze({
|
||||
provider: IDENTITY,
|
||||
operation: contract.name,
|
||||
available: true as const,
|
||||
reason: null,
|
||||
effects: Object.freeze({
|
||||
mutatesArtifact: false,
|
||||
launchesProcess: false,
|
||||
mayShowUi: false,
|
||||
mayAccessNetwork: false,
|
||||
mayWriteFilesystem: false,
|
||||
changesPermissions: false,
|
||||
requiresRoot: false,
|
||||
}),
|
||||
limitations: limitationsFor(contract.name),
|
||||
}),
|
||||
),
|
||||
);
|
||||
readonly #capabilities: readonly CapabilityDescriptor[] =
|
||||
managedStaticCapabilities();
|
||||
|
||||
identity(): ProviderIdentity {
|
||||
return IDENTITY;
|
||||
@@ -196,24 +179,6 @@ const isManagedOperation = (
|
||||
): operation is ManagedToolName =>
|
||||
MANAGED_TOOL_CONTRACTS.some(({ name }) => name === operation);
|
||||
|
||||
const limitationsFor = (operation: ManagedToolName): readonly string[] =>
|
||||
Object.freeze(
|
||||
operation === "inspect_managed_artifact"
|
||||
? [
|
||||
"This capability inventories PE/CLI identity only; inspect_managed_members admits metadata members, signatures, and CIL anchors.",
|
||||
"It never loads the target assembly, resolves dependencies through a CLR, decompiles C#, or executes target code.",
|
||||
]
|
||||
: operation === "inspect_managed_native_boundaries"
|
||||
? [
|
||||
"This capability inventories managed declarations for native boundaries only; native exports, thunks, and addresses require separate native-provider evidence.",
|
||||
"It never loads the target assembly, resolves dependencies through a CLR, decompiles C#, or executes target code.",
|
||||
]
|
||||
: [
|
||||
"This capability decodes PE/CLI metadata members, signatures, and file-backed method bodies; decompiled C# reconstruction and cross-build member comparison are separate operations.",
|
||||
"It never loads the target assembly, resolves dependencies through a CLR, decompiles C#, or executes target code.",
|
||||
],
|
||||
);
|
||||
|
||||
const inspectManagedOperation = (
|
||||
operation: ManagedToolName,
|
||||
parameters: Readonly<Record<string, JsonValue>>,
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import type {
|
||||
CapabilityDescriptor,
|
||||
ProviderIdentity,
|
||||
} from "../application/AnalysisProvider.js";
|
||||
import { MANAGED_STATIC_PROVIDER } from "../application/InvestigationProviders.js";
|
||||
import {
|
||||
MANAGED_TOOL_CONTRACTS,
|
||||
type ManagedToolName,
|
||||
} from "../contracts/managedToolContracts.js";
|
||||
|
||||
/** Identity of execution-free managed metadata observations. */
|
||||
export const MANAGED_STATIC_PROVIDER_IDENTITY: ProviderIdentity = Object.freeze(
|
||||
MANAGED_STATIC_PROVIDER,
|
||||
);
|
||||
const IDENTITY = MANAGED_STATIC_PROVIDER_IDENTITY;
|
||||
|
||||
/** Declare managed metadata coverage without opening or loading an assembly. */
|
||||
export const managedStaticCapabilities = (): readonly CapabilityDescriptor[] =>
|
||||
Object.freeze(
|
||||
MANAGED_TOOL_CONTRACTS.map((contract) =>
|
||||
Object.freeze({
|
||||
provider: IDENTITY,
|
||||
operation: contract.name,
|
||||
available: true as const,
|
||||
reason: null,
|
||||
effects: Object.freeze({
|
||||
mutatesArtifact: false,
|
||||
launchesProcess: false,
|
||||
mayShowUi: false,
|
||||
mayAccessNetwork: false,
|
||||
mayWriteFilesystem: false,
|
||||
changesPermissions: false,
|
||||
requiresRoot: false,
|
||||
}),
|
||||
limitations: limitationsFor(contract.name),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const limitationsFor = (operation: ManagedToolName): readonly string[] =>
|
||||
Object.freeze(
|
||||
operation === "inspect_managed_artifact"
|
||||
? [
|
||||
"This capability inventories PE/CLI identity only; inspect_managed_members admits metadata members, signatures, and CIL anchors.",
|
||||
"It never loads the target assembly, resolves dependencies through a CLR, decompiles C#, or executes target code.",
|
||||
]
|
||||
: operation === "inspect_managed_native_boundaries"
|
||||
? [
|
||||
"This capability inventories managed declarations for native boundaries only; native exports, thunks, and addresses require separate native-provider evidence.",
|
||||
"It never loads the target assembly, resolves dependencies through a CLR, decompiles C#, or executes target code.",
|
||||
]
|
||||
: [
|
||||
"This capability decodes PE/CLI metadata members, signatures, and file-backed method bodies; decompiled C# reconstruction and cross-build member comparison are separate operations.",
|
||||
"It never loads the target assembly, resolves dependencies through a CLR, decompiles C#, or executes target code.",
|
||||
],
|
||||
);
|
||||
@@ -24,10 +24,10 @@ import { PrivateRuntimeRoot } from "../process/PrivateRuntimeRoot.js";
|
||||
import { publishFirmwareExtraction } from "./FirmwarePublication.js";
|
||||
import {
|
||||
FIRMWARE_LIMITS,
|
||||
FIRMWARE_RELEASES,
|
||||
BINWALK_PROVIDER_IDENTITY,
|
||||
UNBLOB_PROVIDER_IDENTITY,
|
||||
} from "./FirmwareRelease.js";
|
||||
import { admitFirmwareVersion } from "./FirmwareVersion.js";
|
||||
import {
|
||||
resolveFirmwareCommand,
|
||||
runFirmwareCommand,
|
||||
@@ -143,21 +143,22 @@ export class FirmwareProvider implements FirmwareAnalysisPort {
|
||||
});
|
||||
const versionRun = await run(["--version"]);
|
||||
const version = versionRun.stdout.text.trim();
|
||||
const expected = FIRMWARE_RELEASES[engineName].version;
|
||||
if (
|
||||
versionRun.stdout.bytes > 1024 ||
|
||||
(engineName === "binwalk"
|
||||
? version !== `binwalk ${expected}`
|
||||
: version !== expected)
|
||||
)
|
||||
if (versionRun.stdout.bytes > 1024)
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
engineName,
|
||||
request.operation,
|
||||
`Unsupported tool version ${version}; this adapter is verified against ${expected}`,
|
||||
`Tool version banner is ${String(versionRun.stdout.bytes)} bytes; expected a short ${engineName} version line.`,
|
||||
);
|
||||
const admitted = admitFirmwareVersion(engineName, version);
|
||||
if (admitted.status === "unsupported" || admitted.status === "unresolved")
|
||||
throw new AnalysisCapabilityUnavailableError(
|
||||
engineName,
|
||||
request.operation,
|
||||
admitted.message,
|
||||
);
|
||||
const engine = {
|
||||
name: engineName,
|
||||
version: expected,
|
||||
version: admitted.version,
|
||||
executable_path: command.command,
|
||||
executable_sha256: command.sha256,
|
||||
source_revision: null,
|
||||
@@ -259,16 +260,23 @@ export class FirmwareProvider implements FirmwareAnalysisPort {
|
||||
});
|
||||
raw = { report, execution: processRun, version_execution: versionRun };
|
||||
}
|
||||
const catalog =
|
||||
engineName === "binwalk"
|
||||
? BINWALK_PROVIDER_IDENTITY
|
||||
: UNBLOB_PROVIDER_IDENTITY;
|
||||
outcome = ok(
|
||||
createAnalysisExecution(
|
||||
result,
|
||||
engineName === "binwalk"
|
||||
? BINWALK_PROVIDER_IDENTITY
|
||||
: UNBLOB_PROVIDER_IDENTITY,
|
||||
{ ...catalog, version: admitted.version },
|
||||
{
|
||||
subject: target.subject,
|
||||
rawResult: raw,
|
||||
limitations,
|
||||
limitations: [
|
||||
...limitations,
|
||||
...(admitted.status === "compatible"
|
||||
? [admitted.limitation]
|
||||
: []),
|
||||
],
|
||||
locations: [
|
||||
{
|
||||
kind: "file-offset-range",
|
||||
|
||||
@@ -12,7 +12,7 @@ export const FIRMWARE_RELEASES = {
|
||||
},
|
||||
} as const;
|
||||
|
||||
/** Catalog identities; Evidence uses the version observed from the executed tool. */
|
||||
/** Catalog identity for the verified Binwalk release. Evidence replaces version with the observed banner. */
|
||||
export const BINWALK_PROVIDER_IDENTITY = {
|
||||
id: "binwalk",
|
||||
name: "Binwalk",
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { admitFirmwareVersion } from "./FirmwareVersion.js";
|
||||
|
||||
describe("firmware release lines", () => {
|
||||
it("accepts the verified banners without an extra limitation", () => {
|
||||
expect(admitFirmwareVersion("binwalk", "binwalk 3.1.0")).toEqual({
|
||||
status: "verified",
|
||||
version: "3.1.0",
|
||||
});
|
||||
expect(admitFirmwareVersion("unblob", "26.6.4")).toEqual({
|
||||
status: "verified",
|
||||
version: "26.6.4",
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["binwalk", "binwalk 3.1.2", "3.1.2"],
|
||||
["binwalk", "binwalk 3.1.0-1", "3.1.0-1"],
|
||||
["unblob", "26.6.5", "26.6.5"],
|
||||
] as const)(
|
||||
"accepts %s %s on the verified line",
|
||||
(engine, banner, version) => {
|
||||
const admitted = admitFirmwareVersion(engine, banner);
|
||||
expect(admitted).toMatchObject({ status: "compatible", version });
|
||||
if (admitted.status !== "compatible")
|
||||
throw new Error("expected a compatible release");
|
||||
expect(admitted.limitation).toContain(version);
|
||||
expect(admitted.limitation).toContain(
|
||||
engine === "binwalk" ? "3.1.0" : "26.6.4",
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.each([
|
||||
["binwalk", "binwalk 3.2.0", "Binwalk 3.1.x"],
|
||||
["binwalk", "unsupported", "Binwalk 3.1.x"],
|
||||
["binwalk", "3.1.2", "Binwalk 3.1.x"],
|
||||
["unblob", "26.7.0", "Unblob 26.6.x"],
|
||||
["unblob", "unblob 26.6.4", "Unblob 26.6.x"],
|
||||
["unblob", "", "missing"],
|
||||
] as const)("rejects %s banner %j", (engine, banner, detail) => {
|
||||
const admitted = admitFirmwareVersion(engine, banner);
|
||||
expect(
|
||||
admitted.status === "verified" || admitted.status === "compatible",
|
||||
).toBe(false);
|
||||
if (admitted.status === "verified" || admitted.status === "compatible")
|
||||
throw new Error("expected a rejected banner");
|
||||
expect(admitted.message).toContain(detail);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,116 @@
|
||||
import { FIRMWARE_RELEASES } from "./FirmwareRelease.js";
|
||||
|
||||
/** Caller-supplied firmware engine selected by the operation. */
|
||||
export type FirmwareEngineName = keyof typeof FIRMWARE_RELEASES;
|
||||
|
||||
interface ReleaseNumber {
|
||||
readonly major: number;
|
||||
readonly minor: number;
|
||||
readonly patch: number;
|
||||
readonly suffix: string;
|
||||
readonly token: string;
|
||||
}
|
||||
|
||||
const TOKEN = /^(\d+)\.(\d+)\.(\d+)([-+][0-9A-Za-z.-]+)?$/u;
|
||||
|
||||
const parseToken = (token: string): ReleaseNumber | undefined => {
|
||||
const match = TOKEN.exec(token);
|
||||
if (match === null) return undefined;
|
||||
const major = Number(match[1]);
|
||||
const minor = Number(match[2]);
|
||||
const patch = Number(match[3]);
|
||||
if (![major, minor, patch].every((part) => Number.isSafeInteger(part)))
|
||||
return undefined;
|
||||
const suffix = match[4] ?? "";
|
||||
return { major, minor, patch, suffix, token };
|
||||
};
|
||||
|
||||
const verifiedRelease = (engine: FirmwareEngineName): ReleaseNumber => {
|
||||
const parsed = parseToken(FIRMWARE_RELEASES[engine].version);
|
||||
if (parsed === undefined || parsed.suffix !== "")
|
||||
throw new Error(
|
||||
`FIRMWARE_RELEASES.${engine}.version is not a release number`,
|
||||
);
|
||||
return parsed;
|
||||
};
|
||||
|
||||
/** Caller-facing engine name. */
|
||||
export const firmwareEngineLabel = (engine: FirmwareEngineName): string => {
|
||||
switch (engine) {
|
||||
case "binwalk":
|
||||
return "Binwalk";
|
||||
case "unblob":
|
||||
return "Unblob";
|
||||
default: {
|
||||
const unreachable: never = engine;
|
||||
return unreachable;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/** Release line accepted for one engine, such as `Binwalk 3.1.x`. */
|
||||
export const firmwareReleaseLine = (engine: FirmwareEngineName): string => {
|
||||
const verified = verifiedRelease(engine);
|
||||
return `${firmwareEngineLabel(engine)} ${String(verified.major)}.${String(verified.minor)}.x`;
|
||||
};
|
||||
|
||||
/** Admission of one observed `--version` banner. */
|
||||
export type FirmwareVersionAdmission =
|
||||
| { readonly status: "verified"; readonly version: string }
|
||||
| {
|
||||
readonly status: "compatible";
|
||||
readonly version: string;
|
||||
readonly limitation: string;
|
||||
}
|
||||
| { readonly status: "unsupported"; readonly message: string }
|
||||
| { readonly status: "unresolved"; readonly message: string };
|
||||
|
||||
/**
|
||||
* Classify a `--version` banner against the audited release line.
|
||||
* Binwalk prints `binwalk <version>`; Unblob prints the version alone.
|
||||
*/
|
||||
export const admitFirmwareVersion = (
|
||||
engine: FirmwareEngineName,
|
||||
banner: string,
|
||||
): FirmwareVersionAdmission => {
|
||||
const token = versionToken(engine, banner);
|
||||
const parsed = token === undefined ? undefined : parseToken(token);
|
||||
const verified = verifiedRelease(engine);
|
||||
const accepted = `accepted releases are ${firmwareReleaseLine(engine)} (verified with ${verified.token})`;
|
||||
if (parsed === undefined)
|
||||
return {
|
||||
status: "unresolved",
|
||||
message: `Unsupported tool version ${banner.length === 0 ? "missing" : banner}; ${accepted}.`,
|
||||
};
|
||||
if (parsed.major !== verified.major || parsed.minor !== verified.minor)
|
||||
return {
|
||||
status: "unsupported",
|
||||
message: `Unsupported tool version ${banner}; ${accepted}.`,
|
||||
};
|
||||
if (parsed.token === verified.token)
|
||||
return { status: "verified", version: parsed.token };
|
||||
const line = `${String(verified.major)}.${String(verified.minor)}.x`;
|
||||
return {
|
||||
status: "compatible",
|
||||
version: parsed.token,
|
||||
limitation: `This session uses ${firmwareEngineLabel(engine)} ${parsed.token}. The report parser is verified against ${verified.token}; other ${line} builds are accepted and the observed version is reported.`,
|
||||
};
|
||||
};
|
||||
|
||||
const versionToken = (
|
||||
engine: FirmwareEngineName,
|
||||
banner: string,
|
||||
): string | undefined => {
|
||||
switch (engine) {
|
||||
case "binwalk":
|
||||
return banner.startsWith("binwalk ")
|
||||
? banner.slice("binwalk ".length)
|
||||
: undefined;
|
||||
case "unblob":
|
||||
return banner;
|
||||
default: {
|
||||
const unreachable: never = engine;
|
||||
return unreachable;
|
||||
}
|
||||
}
|
||||
};
|
||||
File diff suppressed because one or more lines are too long
@@ -60,7 +60,7 @@ describe("Ghidra installation inspection", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("accepts only the exact Linux x64 Ghidra and JDK commitment", () => {
|
||||
it("accepts the verified Linux x64 Ghidra release and JDK", () => {
|
||||
expect(
|
||||
inspectGhidraInstallation(
|
||||
{ installDir: INSTALL, platform: "linux", architecture: "x64" },
|
||||
@@ -74,6 +74,40 @@ describe("Ghidra installation inspection", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
["12.1.2", "27", 27],
|
||||
["12.1.2-2.1", "27", 27],
|
||||
["12.1.0", "21.0.2", 21],
|
||||
[SUPPORTED_GHIDRA_VERSION, "25.0.1", 25],
|
||||
])(
|
||||
"accepts Ghidra %s with JDK %s on the verified release line",
|
||||
(providerVersion, javaVersion, major) => {
|
||||
const result = inspectGhidraInstallation(
|
||||
{ installDir: INSTALL, platform: "linux", architecture: "x64" },
|
||||
host({
|
||||
readText: () =>
|
||||
`application.version=${providerVersion}\napplication.java.min=21\napplication.java.max=\n`,
|
||||
probeJava: () => ({
|
||||
...JAVA,
|
||||
version: javaVersion,
|
||||
major,
|
||||
}),
|
||||
}),
|
||||
);
|
||||
expect(result.status).toBe("available");
|
||||
expect(result).toMatchObject({ providerVersion, javaVersion });
|
||||
expect(
|
||||
result.checks.find(({ name }) => name === "version"),
|
||||
).toMatchObject({
|
||||
status: "passed",
|
||||
detail:
|
||||
providerVersion === SUPPORTED_GHIDRA_VERSION
|
||||
? SUPPORTED_GHIDRA_VERSION
|
||||
: expect.stringContaining("verified build"),
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.each(["x64", "arm64"] as const)(
|
||||
"accepts macOS %s with matching native tools",
|
||||
(architecture) => {
|
||||
@@ -247,3 +281,84 @@ describe("Ghidra installation rejection diagnostics", () => {
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe("Ghidra release line and JDK bounds", () => {
|
||||
it.each([
|
||||
{
|
||||
name: "JDK above the installation maximum",
|
||||
readText: () =>
|
||||
"application.version=12.1.4\napplication.java.min=21\napplication.java.max=25\n",
|
||||
probeJava: () => ({ ...JAVA, major: 27, version: "27" }),
|
||||
failed: "java",
|
||||
code: "unsupported_version",
|
||||
},
|
||||
{
|
||||
name: "unreadable Java minimum",
|
||||
readText: () =>
|
||||
"application.version=12.1.4\napplication.java.min=latest\n",
|
||||
probeJava: () => JAVA,
|
||||
failed: "java",
|
||||
code: "version_unresolved",
|
||||
},
|
||||
{
|
||||
name: "unparseable Ghidra version",
|
||||
readText: () => "application.version=latest\n",
|
||||
probeJava: () => JAVA,
|
||||
failed: "version",
|
||||
code: "version_unresolved",
|
||||
},
|
||||
{
|
||||
name: "different Ghidra line",
|
||||
readText: () => "application.version=12.2.0\n",
|
||||
probeJava: () => JAVA,
|
||||
failed: "version",
|
||||
code: "unsupported_version",
|
||||
},
|
||||
])("distinguishes $name", ({ readText, probeJava, failed, code }) => {
|
||||
const result = inspectGhidraInstallation(
|
||||
{ installDir: INSTALL, platform: "linux", architecture: "x64" },
|
||||
host({ readText, probeJava }),
|
||||
);
|
||||
expect(result.status).toBe("unavailable");
|
||||
expect(
|
||||
result.checks.find(({ status }) => status === "failed"),
|
||||
).toMatchObject({ name: failed, code });
|
||||
});
|
||||
|
||||
it("names the accepted Ghidra line and JDK range in failure remediation", () => {
|
||||
const result = inspectGhidraInstallation(
|
||||
{
|
||||
installDir: INSTALL,
|
||||
javaHome: "/usr/lib/jvm/java-17-openjdk",
|
||||
platform: "linux",
|
||||
architecture: "x64",
|
||||
},
|
||||
host({
|
||||
readText: () =>
|
||||
"application.version=12.0.4\napplication.java.min=21\napplication.java.max=\n",
|
||||
probeJava: () => ({ ...JAVA, major: 17, version: "17.0.20.1" }),
|
||||
}),
|
||||
);
|
||||
expect(result.status).toBe("unavailable");
|
||||
if (result.status !== "unavailable") return;
|
||||
expect(result.rejection.reason).toContain("12.1.x");
|
||||
expect(result.rejection.reason).toContain(SUPPORTED_GHIDRA_VERSION);
|
||||
expect(result.checks.find(({ name }) => name === "java")).toMatchObject({
|
||||
status: "failed",
|
||||
remediation: expect.stringContaining("JDK 21 or newer"),
|
||||
});
|
||||
});
|
||||
|
||||
it("honors an installation that declares a lower Java minimum", () => {
|
||||
expect(
|
||||
inspectGhidraInstallation(
|
||||
{ installDir: INSTALL, platform: "linux", architecture: "x64" },
|
||||
host({
|
||||
readText: () =>
|
||||
`application.version=${SUPPORTED_GHIDRA_VERSION}\napplication.java.min=17\n`,
|
||||
probeJava: () => ({ ...JAVA, major: 17, version: "17.0.20.1" }),
|
||||
}),
|
||||
),
|
||||
).toMatchObject({ status: "available", javaVersion: "17.0.20.1" });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,11 +5,22 @@ import { posix, win32 } from "node:path";
|
||||
|
||||
import type { ProviderRejectionCode } from "../contracts/providerSelection.js";
|
||||
import type { JsonValue } from "../domain/jsonValue.js";
|
||||
import {
|
||||
ghidraApplicationProperties,
|
||||
ghidraJavaMajorAccepted,
|
||||
ghidraJavaRangeLabel,
|
||||
ghidraJavaRequirement,
|
||||
ghidraReleaseAccepted,
|
||||
ghidraReleaseCompatibility,
|
||||
ghidraReleaseLine,
|
||||
ghidraVersionDetail,
|
||||
SUPPORTED_GHIDRA_JAVA_MAJOR,
|
||||
SUPPORTED_GHIDRA_VERSION,
|
||||
type GhidraApplicationProperties,
|
||||
type GhidraJavaRequirement,
|
||||
} from "./GhidraInstallationPolicy.js";
|
||||
|
||||
/** Exact Ghidra build whose Java bridge contract this REA release supports. */
|
||||
export const SUPPORTED_GHIDRA_VERSION = "12.1.4";
|
||||
/** Exact JDK major documented by the supported Ghidra release. */
|
||||
export const SUPPORTED_GHIDRA_JAVA_MAJOR = 21;
|
||||
export { SUPPORTED_GHIDRA_JAVA_MAJOR, SUPPORTED_GHIDRA_VERSION };
|
||||
|
||||
/** Caller-owned paths and host coordinates used for one installation probe. */
|
||||
export interface GhidraInstallationOptions {
|
||||
@@ -110,7 +121,7 @@ interface GhidraInstallationCoordinates {
|
||||
readonly applicationPropertiesPath: string | null;
|
||||
readonly analyzeHeadlessPath: string | null;
|
||||
readonly nativeDecompilerPath: string | null;
|
||||
readonly properties: Readonly<{ providerVersion: string | null }> | undefined;
|
||||
readonly properties: GhidraApplicationProperties | undefined;
|
||||
readonly javaCommand: string;
|
||||
readonly java: GhidraJavaObservation | undefined;
|
||||
}
|
||||
@@ -269,7 +280,7 @@ const installationCoordinates = (
|
||||
properties:
|
||||
properties === undefined
|
||||
? undefined
|
||||
: { providerVersion: propertyValue(properties, "application.version") },
|
||||
: ghidraApplicationProperties(properties),
|
||||
javaCommand,
|
||||
java: host.probeJava(
|
||||
javaCommand,
|
||||
@@ -290,8 +301,7 @@ const installationChecks = ({
|
||||
passed: coordinates.installDir !== null,
|
||||
code: "not_configured",
|
||||
detail: coordinates.installDir ?? "GHIDRA_INSTALL_DIR is not set",
|
||||
remediation:
|
||||
"Set GHIDRA_INSTALL_DIR to an extracted Ghidra 12.1.4 release directory.",
|
||||
remediation: `Set GHIDRA_INSTALL_DIR to an extracted Ghidra ${ghidraReleaseLine()} release directory.`,
|
||||
}),
|
||||
installationCheck({
|
||||
name: "platform",
|
||||
@@ -323,18 +333,7 @@ const installationChecks = ({
|
||||
remediation:
|
||||
"Point GHIDRA_INSTALL_DIR at the root of an extracted official Ghidra release.",
|
||||
}),
|
||||
installationCheck({
|
||||
name: "version",
|
||||
passed:
|
||||
coordinates.properties?.providerVersion === SUPPORTED_GHIDRA_VERSION,
|
||||
code:
|
||||
coordinates.properties?.providerVersion === null ||
|
||||
coordinates.properties?.providerVersion === undefined
|
||||
? "version_unresolved"
|
||||
: "unsupported_version",
|
||||
detail: coordinates.properties?.providerVersion ?? "unknown",
|
||||
remediation: `Install Ghidra ${SUPPORTED_GHIDRA_VERSION}, or update REA for a different Ghidra build.`,
|
||||
}),
|
||||
versionCheck(coordinates.properties),
|
||||
installationCheck({
|
||||
name: "headless",
|
||||
passed:
|
||||
@@ -357,7 +356,12 @@ const installationChecks = ({
|
||||
remediation:
|
||||
"REA does not build native tools. Build Ghidra's native components for this macOS architecture or provide an installation containing Ghidra/Features/Decompiler/os/<platform>/decompile.",
|
||||
}),
|
||||
javaCheck(coordinates.java, coordinates.javaCommand, javaHome),
|
||||
javaCheck(
|
||||
coordinates.java,
|
||||
coordinates.javaCommand,
|
||||
javaHome,
|
||||
coordinates.properties,
|
||||
),
|
||||
];
|
||||
|
||||
/** Project an installation probe into caller-visible, secret-free diagnostics. */
|
||||
@@ -428,40 +432,65 @@ const installationCheck = (options: {
|
||||
remediation: options.remediation,
|
||||
};
|
||||
|
||||
const versionCheck = (
|
||||
properties: GhidraApplicationProperties | undefined,
|
||||
): GhidraInstallationCheck => {
|
||||
const raw = properties?.providerVersion;
|
||||
return installationCheck({
|
||||
name: "version",
|
||||
passed: ghidraReleaseAccepted(raw),
|
||||
code:
|
||||
ghidraReleaseCompatibility(raw).status === "unsupported"
|
||||
? "unsupported_version"
|
||||
: "version_unresolved",
|
||||
detail: ghidraVersionDetail(raw),
|
||||
remediation: `Install a Ghidra ${ghidraReleaseLine()} release (verified with ${SUPPORTED_GHIDRA_VERSION}), or update REA for another Ghidra line.`,
|
||||
});
|
||||
};
|
||||
|
||||
const javaCheck = (
|
||||
observation: GhidraJavaObservation | undefined,
|
||||
command: string,
|
||||
configuredHome: string | undefined,
|
||||
properties: GhidraApplicationProperties | undefined,
|
||||
): GhidraInstallationCheck => {
|
||||
const requirement = ghidraJavaRequirement(properties);
|
||||
const range = ghidraJavaRangeLabel(requirement);
|
||||
const supported =
|
||||
observation !== undefined &&
|
||||
observation.major === SUPPORTED_GHIDRA_JAVA_MAJOR &&
|
||||
ghidraJavaMajorAccepted(observation.major, requirement) &&
|
||||
observation.bits === 64 &&
|
||||
observation.runtime === "jdk";
|
||||
const detail =
|
||||
observation === undefined
|
||||
? command
|
||||
: `${observation.version}; ${String(observation.bits)}-bit; ${observation.runtime === "jdk" ? "JDK" : "runtime only"}; ${observation.home}`;
|
||||
? requirement.unresolved === null
|
||||
? command
|
||||
: `${command}; ${requirement.unresolved}`
|
||||
: `${observation.version}; ${String(observation.bits)}-bit; ${observation.runtime === "jdk" ? "JDK" : "runtime only"}; ${observation.home}; accepted ${range}`;
|
||||
return installationCheck({
|
||||
name: "java",
|
||||
passed: supported,
|
||||
code: observation === undefined ? "runtime_missing" : "unsupported_version",
|
||||
code:
|
||||
requirement.unresolved !== null
|
||||
? "version_unresolved"
|
||||
: observation === undefined
|
||||
? "runtime_missing"
|
||||
: "unsupported_version",
|
||||
detail,
|
||||
remediation:
|
||||
configuredHome === undefined
|
||||
? "Install a 64-bit JDK 21 or set JAVA_HOME before starting REA."
|
||||
: "Update JAVA_HOME to the root of a 64-bit JDK 21 installation.",
|
||||
remediation: javaRemediation(requirement, configuredHome, range),
|
||||
});
|
||||
};
|
||||
|
||||
const propertyValue = (content: string, name: string): string | null => {
|
||||
for (const line of content.split(/\r?\n/u)) {
|
||||
const separator = line.indexOf("=");
|
||||
if (separator < 0 || line.slice(0, separator).trim() !== name) continue;
|
||||
const value = line.slice(separator + 1).trim();
|
||||
return value.length === 0 ? null : value;
|
||||
}
|
||||
return null;
|
||||
const javaRemediation = (
|
||||
requirement: GhidraJavaRequirement,
|
||||
configuredHome: string | undefined,
|
||||
range: string,
|
||||
): string => {
|
||||
if (requirement.unresolved !== null)
|
||||
return `The Ghidra installation's Java bounds could not be read (${requirement.unresolved}). Install a 64-bit full JDK inside the declared application.java.min and application.java.max.`;
|
||||
return configuredHome === undefined
|
||||
? `Install ${range}, or set JAVA_HOME before starting REA.`
|
||||
: `Update JAVA_HOME to the root of ${range} installation.`;
|
||||
};
|
||||
|
||||
const systemGhidraInstallationHost = (): GhidraInstallationHost => ({
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
/** Ghidra build whose bridge behavior this REA release verifies. */
|
||||
export const SUPPORTED_GHIDRA_VERSION = "12.1.4";
|
||||
/**
|
||||
* JDK major used when an installation omits `application.java.min`.
|
||||
* Admission uses that installation's `application.java.min` and
|
||||
* `application.java.max`. An empty maximum means the release sets no upper bound.
|
||||
*/
|
||||
export const SUPPORTED_GHIDRA_JAVA_MAJOR = 21;
|
||||
|
||||
/** Numeric Ghidra release read from `application.version`. */
|
||||
interface GhidraReleaseVersion {
|
||||
readonly major: number;
|
||||
readonly minor: number;
|
||||
readonly patch: number;
|
||||
}
|
||||
|
||||
/** How an observed Ghidra release relates to this adapter's bridge. */
|
||||
type GhidraReleaseCompatibility =
|
||||
| {
|
||||
readonly status: "verified";
|
||||
readonly version: GhidraReleaseVersion;
|
||||
readonly raw: string;
|
||||
}
|
||||
| {
|
||||
readonly status: "compatible";
|
||||
readonly version: GhidraReleaseVersion;
|
||||
readonly raw: string;
|
||||
}
|
||||
| {
|
||||
readonly status: "unsupported";
|
||||
readonly version: GhidraReleaseVersion;
|
||||
readonly raw: string;
|
||||
}
|
||||
| { readonly status: "unresolved"; readonly raw: string | null };
|
||||
|
||||
/** One Java major bound declared by `application.properties`. */
|
||||
type GhidraJavaBound =
|
||||
| { readonly status: "absent" }
|
||||
| { readonly status: "major"; readonly major: number }
|
||||
| { readonly status: "unresolved"; readonly raw: string };
|
||||
|
||||
/** JDK majors this installation admits, after reading its own properties. */
|
||||
export interface GhidraJavaRequirement {
|
||||
readonly minimumMajor: number;
|
||||
readonly maximumMajor: number | null;
|
||||
readonly unresolved: string | null;
|
||||
}
|
||||
|
||||
/** Version and Java bounds read from one `application.properties` file. */
|
||||
export interface GhidraApplicationProperties {
|
||||
readonly providerVersion: string | null;
|
||||
readonly javaMinimum: GhidraJavaBound;
|
||||
readonly javaMaximum: GhidraJavaBound;
|
||||
}
|
||||
|
||||
const GHIDRA_RELEASE_PATTERN = /^(\d+)\.(\d+)(?:\.(\d+))?([-+].*)?$/u;
|
||||
const JAVA_MAJOR_PATTERN = /^(\d+)(?:\.\d+)*$/u;
|
||||
|
||||
/** Read the version and Java bounds Ghidra publishes for one installation. */
|
||||
export const ghidraApplicationProperties = (
|
||||
content: string,
|
||||
): GhidraApplicationProperties => ({
|
||||
providerVersion: propertyValue(content, "application.version"),
|
||||
javaMinimum: parseJavaBound(propertyValue(content, "application.java.min")),
|
||||
javaMaximum: parseJavaBound(propertyValue(content, "application.java.max")),
|
||||
});
|
||||
|
||||
/** Classify `application.version` against the verified release line. */
|
||||
export const ghidraReleaseCompatibility = (
|
||||
raw: string | null | undefined,
|
||||
): GhidraReleaseCompatibility => {
|
||||
if (raw === null || raw === undefined)
|
||||
return { status: "unresolved", raw: null };
|
||||
const version = parseGhidraRelease(raw);
|
||||
if (version === undefined) return { status: "unresolved", raw };
|
||||
if (raw === SUPPORTED_GHIDRA_VERSION)
|
||||
return { status: "verified", version, raw };
|
||||
const verified = verifiedGhidraRelease();
|
||||
return version.major === verified.major && version.minor === verified.minor
|
||||
? { status: "compatible", version, raw }
|
||||
: { status: "unsupported", version, raw };
|
||||
};
|
||||
|
||||
/**
|
||||
* Limitation recorded when a session runs a compatible build other than the
|
||||
* verified release. The observed version stays on the provider identity.
|
||||
*/
|
||||
export const unverifiedGhidraBuildLimitation = (
|
||||
providerVersion: string,
|
||||
): string | undefined => {
|
||||
const compatibility = ghidraReleaseCompatibility(providerVersion);
|
||||
if (compatibility.status !== "compatible") return undefined;
|
||||
return `This session uses Ghidra ${providerVersion}. The bridge is verified against ${SUPPORTED_GHIDRA_VERSION}; other ${ghidraReleaseLine()} builds are accepted and the observed version is reported.`;
|
||||
};
|
||||
|
||||
/** Release line accepted by this bridge, such as `12.1.x`. */
|
||||
export const ghidraReleaseLine = (): string => {
|
||||
const verified = verifiedGhidraRelease();
|
||||
return `${String(verified.major)}.${String(verified.minor)}.x`;
|
||||
};
|
||||
|
||||
/** Detail for the installation version check, including the accepted line. */
|
||||
export const ghidraVersionDetail = (raw: string | null | undefined): string => {
|
||||
const compatibility = ghidraReleaseCompatibility(raw);
|
||||
switch (compatibility.status) {
|
||||
case "unresolved":
|
||||
return compatibility.raw ?? "unknown";
|
||||
case "verified":
|
||||
return compatibility.raw;
|
||||
case "compatible":
|
||||
return `${compatibility.raw}; compatible ${ghidraReleaseLine()} release (verified build ${SUPPORTED_GHIDRA_VERSION})`;
|
||||
case "unsupported":
|
||||
return `${compatibility.raw}; accepted releases are ${ghidraReleaseLine()} (verified build ${SUPPORTED_GHIDRA_VERSION})`;
|
||||
default: {
|
||||
const unreachable: never = compatibility;
|
||||
return unreachable;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/** Whether this release line can run the packaged bridge. */
|
||||
export const ghidraReleaseAccepted = (
|
||||
raw: string | null | undefined,
|
||||
): boolean => {
|
||||
const status = ghidraReleaseCompatibility(raw).status;
|
||||
return status === "verified" || status === "compatible";
|
||||
};
|
||||
|
||||
/** Resolve JDK majors from `application.java.min` and `application.java.max`. */
|
||||
export const ghidraJavaRequirement = (
|
||||
properties: GhidraApplicationProperties | undefined,
|
||||
): GhidraJavaRequirement => {
|
||||
const minimum = properties?.javaMinimum ?? { status: "absent" };
|
||||
const maximum = properties?.javaMaximum ?? { status: "absent" };
|
||||
if (minimum.status === "unresolved")
|
||||
return unresolvedJavaRequirement(`application.java.min=${minimum.raw}`);
|
||||
if (maximum.status === "unresolved")
|
||||
return unresolvedJavaRequirement(`application.java.max=${maximum.raw}`);
|
||||
const minimumMajor =
|
||||
minimum.status === "major" ? minimum.major : SUPPORTED_GHIDRA_JAVA_MAJOR;
|
||||
const maximumMajor = maximum.status === "major" ? maximum.major : null;
|
||||
if (maximumMajor !== null && maximumMajor < minimumMajor)
|
||||
return unresolvedJavaRequirement(
|
||||
`application.java.max=${String(maximumMajor)} is below application.java.min=${String(minimumMajor)}`,
|
||||
);
|
||||
return { minimumMajor, maximumMajor, unresolved: null };
|
||||
};
|
||||
|
||||
/** Caller-facing description of one resolved or unreadable JDK range. */
|
||||
export const ghidraJavaRangeLabel = (
|
||||
requirement: GhidraJavaRequirement,
|
||||
): string => {
|
||||
if (requirement.unresolved !== null)
|
||||
return "a 64-bit full JDK matching the installation's declared Java bounds";
|
||||
if (requirement.maximumMajor === null)
|
||||
return `a 64-bit full JDK ${String(requirement.minimumMajor)} or newer`;
|
||||
if (requirement.maximumMajor === requirement.minimumMajor)
|
||||
return `a 64-bit full JDK ${String(requirement.minimumMajor)}`;
|
||||
return `a 64-bit full JDK ${String(requirement.minimumMajor)} through ${String(requirement.maximumMajor)}`;
|
||||
};
|
||||
|
||||
/** Whether an observed JDK satisfies the installation's declared range. */
|
||||
export const ghidraJavaMajorAccepted = (
|
||||
major: number,
|
||||
requirement: GhidraJavaRequirement,
|
||||
): boolean =>
|
||||
requirement.unresolved === null &&
|
||||
major >= requirement.minimumMajor &&
|
||||
(requirement.maximumMajor === null || major <= requirement.maximumMajor);
|
||||
|
||||
const verifiedGhidraRelease = (): GhidraReleaseVersion => {
|
||||
const version = parseGhidraRelease(SUPPORTED_GHIDRA_VERSION);
|
||||
if (version === undefined)
|
||||
throw new TypeError(
|
||||
`SUPPORTED_GHIDRA_VERSION ${SUPPORTED_GHIDRA_VERSION} is not a Ghidra release`,
|
||||
);
|
||||
return version;
|
||||
};
|
||||
|
||||
const parseGhidraRelease = (raw: string): GhidraReleaseVersion | undefined => {
|
||||
const match = GHIDRA_RELEASE_PATTERN.exec(raw);
|
||||
const major = integerGroup(match?.[1]);
|
||||
const minor = integerGroup(match?.[2]);
|
||||
if (match === null || major === undefined || minor === undefined)
|
||||
return undefined;
|
||||
const patch = match[3] === undefined ? 0 : integerGroup(match[3]);
|
||||
return patch === undefined ? undefined : { major, minor, patch };
|
||||
};
|
||||
|
||||
const parseJavaBound = (raw: string | null): GhidraJavaBound => {
|
||||
if (raw === null) return { status: "absent" };
|
||||
const major = integerGroup(JAVA_MAJOR_PATTERN.exec(raw)?.[1]);
|
||||
return major === undefined
|
||||
? { status: "unresolved", raw }
|
||||
: { status: "major", major };
|
||||
};
|
||||
|
||||
const integerGroup = (value: string | undefined): number | undefined => {
|
||||
if (value === undefined) return undefined;
|
||||
const parsed = Number(value);
|
||||
return Number.isSafeInteger(parsed) ? parsed : undefined;
|
||||
};
|
||||
|
||||
const unresolvedJavaRequirement = (
|
||||
unresolved: string,
|
||||
): GhidraJavaRequirement => ({
|
||||
minimumMajor: SUPPORTED_GHIDRA_JAVA_MAJOR,
|
||||
maximumMajor: null,
|
||||
unresolved,
|
||||
});
|
||||
|
||||
const propertyValue = (content: string, name: string): string | null => {
|
||||
for (const line of content.split(/\r?\n/u)) {
|
||||
const separator = line.indexOf("=");
|
||||
if (separator < 0 || line.slice(0, separator).trim() !== name) continue;
|
||||
const value = line.slice(separator + 1).trim();
|
||||
return value.length === 0 ? null : value;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
@@ -791,3 +791,70 @@ describe("Ghidra extension failures", () => {
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("compatible Ghidra builds", () => {
|
||||
it("accepts the build and reports that it is unverified", async () => {
|
||||
const ghidra = provider(
|
||||
{
|
||||
...installationHost(),
|
||||
readText: () =>
|
||||
"application.version=12.1.2\napplication.java.min=21\napplication.java.max=\n",
|
||||
probeJava: () => ({
|
||||
version: "27",
|
||||
major: 27,
|
||||
home: "/usr/lib/jvm/java-27-openjdk",
|
||||
bits: 64,
|
||||
runtime: "jdk",
|
||||
}),
|
||||
},
|
||||
() => ({
|
||||
start: () =>
|
||||
Promise.resolve(
|
||||
ok({
|
||||
...sessionInfo(),
|
||||
provider: { id: "ghidra", version: "12.1.2" },
|
||||
}),
|
||||
),
|
||||
callTool: () =>
|
||||
Promise.resolve(
|
||||
ok([
|
||||
{
|
||||
address: "0x1000",
|
||||
value: "fixture_main",
|
||||
procedure: {
|
||||
external: false,
|
||||
thunk: false,
|
||||
thunk_target: null,
|
||||
},
|
||||
},
|
||||
]),
|
||||
),
|
||||
close: () => Promise.resolve(),
|
||||
}),
|
||||
);
|
||||
const resolved = await ghidra.resolveAnalysisProfile(
|
||||
executableTarget("elf", "x86_64"),
|
||||
);
|
||||
if (!resolved.ok || resolved.value.profile === null)
|
||||
throw new Error("expected a compatible Ghidra profile");
|
||||
const client = ghidra.createClient(
|
||||
executableTarget("elf", "x86_64"),
|
||||
resolved.value.profile,
|
||||
);
|
||||
const health = await client.execute("health", {});
|
||||
const procedures = await client.execute("list_procedures", {});
|
||||
expect(ghidra.inspectAvailability()).toMatchObject({
|
||||
status: "available",
|
||||
diagnostics: { provider_version: "12.1.2", java_version: "27" },
|
||||
});
|
||||
expect(health.ok && health.value.provider.version).toBe("12.1.2");
|
||||
const unverified = expect.stringContaining("12.1.2");
|
||||
expect(health.ok && health.value.limitations).toEqual(
|
||||
expect.arrayContaining([unverified]),
|
||||
);
|
||||
expect(procedures.ok && procedures.value.limitations).toEqual(
|
||||
expect.arrayContaining([unverified]),
|
||||
);
|
||||
expect(procedures.ok && procedures.value.provider.version).toBe("12.1.2");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -59,6 +59,7 @@ import {
|
||||
type GhidraInstallationHost,
|
||||
type GhidraInstallationInspection,
|
||||
} from "./GhidraInstallation.js";
|
||||
import { unverifiedGhidraBuildLimitation } from "./GhidraInstallationPolicy.js";
|
||||
import { GhidraHeadlessLauncher } from "./GhidraLauncher.js";
|
||||
import { resolveGhidraAnalysisProfile } from "./GhidraAnalysisProfile.js";
|
||||
import type { GhidraSessionError } from "./GhidraSessionError.js";
|
||||
@@ -332,6 +333,15 @@ export class GhidraProvider implements AnalysisProviderCandidate {
|
||||
await client.close();
|
||||
return extensionFailure;
|
||||
};
|
||||
const releaseLimitation = unverifiedGhidraBuildLimitation(
|
||||
prerequisites.value.providerVersion,
|
||||
);
|
||||
const sessionLimitations = [
|
||||
...providerLimitations,
|
||||
...targetLimitations,
|
||||
...ghidraExtensionLimitations(extensions),
|
||||
...(releaseLimitation === undefined ? [] : [releaseLimitation]),
|
||||
];
|
||||
return {
|
||||
execute: async (operation, parameters, options) => {
|
||||
if (extensionFailure !== undefined) return err(extensionFailure);
|
||||
@@ -356,12 +366,7 @@ export class GhidraProvider implements AnalysisProviderCandidate {
|
||||
return ok(
|
||||
createAnalysisExecution(started.value, committedProfile.provider, {
|
||||
analysisProfile: committedProfile,
|
||||
limitations: [
|
||||
...healthLimitations,
|
||||
...providerLimitations,
|
||||
...targetLimitations,
|
||||
...ghidraExtensionLimitations(extensions),
|
||||
],
|
||||
limitations: [...healthLimitations, ...sessionLimitations],
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -435,12 +440,7 @@ export class GhidraProvider implements AnalysisProviderCandidate {
|
||||
createAnalysisExecution(normalized, committedProfile.provider, {
|
||||
rawResult: called.value,
|
||||
analysisProfile: committedProfile,
|
||||
limitations: [
|
||||
...limitationsFor(operation),
|
||||
...providerLimitations,
|
||||
...targetLimitations,
|
||||
...ghidraExtensionLimitations(extensions),
|
||||
],
|
||||
limitations: [...limitationsFor(operation), ...sessionLimitations],
|
||||
}),
|
||||
);
|
||||
},
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
import type { CapabilityDescriptor } from "../application/AnalysisProvider.js";
|
||||
|
||||
/** Apply native host restrictions to portable provider discovery metadata. */
|
||||
export const nativeHostCapabilities = (
|
||||
capabilities: readonly CapabilityDescriptor[],
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): readonly CapabilityDescriptor[] => {
|
||||
if (platform === "darwin") return capabilities;
|
||||
return capabilities.map((capability): CapabilityDescriptor => {
|
||||
if (capability.provider.id === "native-macos")
|
||||
return {
|
||||
...capability,
|
||||
available: false,
|
||||
availabilityCode: "unsupported_host",
|
||||
reason: "Native macOS utilities require macOS.",
|
||||
};
|
||||
if (
|
||||
capability.provider.id === "rea-artifact-graph" &&
|
||||
capability.operation === "inspect_asset_catalog"
|
||||
)
|
||||
return {
|
||||
...capability,
|
||||
available: false,
|
||||
availabilityCode: "unsupported_host",
|
||||
reason: "Apple asset catalogs require macOS assetutil.",
|
||||
};
|
||||
return capability;
|
||||
});
|
||||
};
|
||||
@@ -1,3 +1,8 @@
|
||||
import {
|
||||
NATIVE_MACOS_PROVIDER_IDENTITY as IDENTITY,
|
||||
nativeMacOSCapabilities,
|
||||
} from "./NativeMacOSProviderMetadata.js";
|
||||
export { NATIVE_MACOS_PROVIDER_IDENTITY } from "./NativeMacOSProviderMetadata.js";
|
||||
import { inspectAppleDispatchMetadata } from "./AppleDispatchMetadata.js";
|
||||
import { observeNativeUi } from "./NativeUiObservation.js";
|
||||
import { dirname, isAbsolute, resolve } from "node:path";
|
||||
@@ -45,20 +50,12 @@ import {
|
||||
import { parseCodeSignature } from "./parsers/codesign.js";
|
||||
import { parseDemangledSymbols } from "./parsers/demangle.js";
|
||||
import { parseLipoArchitectures } from "./parsers/lipo.js";
|
||||
import { parsePlistJson } from "./parsers/plist.js";
|
||||
import { parsePlistJson, parsePlistXml } from "./parsers/plist.js";
|
||||
import {
|
||||
architectureLocations,
|
||||
inspectNativeMacho,
|
||||
} from "./NativeMachoInspection.js";
|
||||
|
||||
/** Public identity committed by macOS-native inspection observations. */
|
||||
export const NATIVE_MACOS_PROVIDER_IDENTITY: ProviderIdentity = Object.freeze({
|
||||
id: "native-macos",
|
||||
name: "macOS native inspection utilities",
|
||||
version: null,
|
||||
});
|
||||
const IDENTITY = NATIVE_MACOS_PROVIDER_IDENTITY;
|
||||
|
||||
/** Read-only semantic provider composed from Xcode command-line utilities. */
|
||||
export class NativeMacOSProvider implements AnalysisProvider {
|
||||
readonly #capabilities: readonly CapabilityDescriptor[];
|
||||
@@ -67,41 +64,7 @@ export class NativeMacOSProvider implements AnalysisProvider {
|
||||
private readonly runner: NativeCommandRunner = new XcrunCommandRunner(),
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
) {
|
||||
const available = platform === "darwin";
|
||||
this.#capabilities = Object.freeze(
|
||||
[
|
||||
...NATIVE_TOOL_CONTRACTS,
|
||||
{ name: "inspect_native_dispatch_metadata" as const },
|
||||
].map((contract): CapabilityDescriptor => {
|
||||
const availability = available
|
||||
? ({ available: true, reason: null } as const)
|
||||
: ({
|
||||
available: false,
|
||||
availabilityCode: "unsupported_host",
|
||||
reason: "Native macOS utilities require macOS.",
|
||||
} as const);
|
||||
return Object.freeze({
|
||||
provider: IDENTITY,
|
||||
operation: contract.name,
|
||||
...availability,
|
||||
effects: Object.freeze({
|
||||
mutatesArtifact: false,
|
||||
launchesProcess:
|
||||
contract.name !== "inspect_native_dispatch_metadata",
|
||||
mayShowUi: contract.name === "capture_native_ui_scenario",
|
||||
mayAccessNetwork: contract.name === "capture_native_ui_scenario",
|
||||
mayWriteFilesystem:
|
||||
contract.name === "capture_native_ui_scenario" ||
|
||||
contract.name === "observe_native_ui",
|
||||
changesPermissions: false,
|
||||
requiresRoot: false,
|
||||
}),
|
||||
limitations: Object.freeze([
|
||||
"Availability and textual formats depend on the installed macOS/Xcode toolchain.",
|
||||
]),
|
||||
});
|
||||
}),
|
||||
);
|
||||
this.#capabilities = nativeMacOSCapabilities(platform);
|
||||
}
|
||||
|
||||
identity(): ProviderIdentity {
|
||||
@@ -460,33 +423,51 @@ class NativeMacOSClient implements AnalysisClient {
|
||||
{ signal },
|
||||
);
|
||||
if (!classified.ok) return classified;
|
||||
const capture = await this.#run(
|
||||
const json = await this.#run(
|
||||
"inspect_plist",
|
||||
"plutil",
|
||||
["-convert", "json", "-o", "-", "--", plist.value],
|
||||
{ signal },
|
||||
{ signal, acceptNonZero: true },
|
||||
);
|
||||
if (!capture.ok) return capture;
|
||||
const parsed = parsePlistJson(capture.value.stdout);
|
||||
if (!json.ok) return json;
|
||||
// JSON cannot express data, dates, or non-finite reals; plutil rejects
|
||||
// such plists, so decode its lossless XML conversion instead.
|
||||
const xml =
|
||||
json.value.exitCode === 0
|
||||
? undefined
|
||||
: await this.#run(
|
||||
"inspect_plist",
|
||||
"plutil",
|
||||
["-convert", "xml1", "-o", "-", "--", plist.value],
|
||||
{ signal },
|
||||
);
|
||||
if (xml !== undefined && !xml.ok) return xml;
|
||||
const parsed =
|
||||
xml === undefined
|
||||
? parsePlistJson(json.value.stdout)
|
||||
: parsePlistXml(xml.value.stdout);
|
||||
if (!parsed.ok) return parsed;
|
||||
const provenance = [classified.value, capture.value].map((item) =>
|
||||
invocation(item, plist.value, "$PLIST"),
|
||||
);
|
||||
const provenance = [
|
||||
classified.value,
|
||||
json.value,
|
||||
...(xml === undefined ? [] : [xml.value]),
|
||||
].map((item) => invocation(item, plist.value, "$PLIST"));
|
||||
const result = inspectPlistSchema.parse({
|
||||
format: /binary property list/iu.test(classified.value.stdout)
|
||||
? "binary"
|
||||
: /XML|text/iu.test(classified.value.stdout)
|
||||
? "xml"
|
||||
: "unknown",
|
||||
...parsed.value,
|
||||
value: parsed.value.value,
|
||||
bundle: parsed.value.bundle,
|
||||
source_path: plist.value,
|
||||
provenance,
|
||||
limitations: [],
|
||||
limitations: parsed.value.limitations,
|
||||
});
|
||||
return ok({
|
||||
result: jsonValueSchema.parse(result),
|
||||
provenance,
|
||||
limitations: [],
|
||||
limitations: parsed.value.limitations,
|
||||
locations: [{ kind: "artifact-path", path: plist.value }],
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import type {
|
||||
CapabilityDescriptor,
|
||||
ProviderIdentity,
|
||||
} from "../application/AnalysisProvider.js";
|
||||
import { NATIVE_TOOL_CONTRACTS } from "../contracts/nativeToolContracts.js";
|
||||
|
||||
/** Public identity committed by macOS-native inspection observations. */
|
||||
export const NATIVE_MACOS_PROVIDER_IDENTITY: ProviderIdentity = Object.freeze({
|
||||
id: "native-macos",
|
||||
name: "macOS native inspection utilities",
|
||||
version: null,
|
||||
});
|
||||
const IDENTITY = NATIVE_MACOS_PROVIDER_IDENTITY;
|
||||
|
||||
/** Declare native host coverage without creating a command runner. */
|
||||
export const nativeMacOSCapabilities = (
|
||||
platform: NodeJS.Platform = process.platform,
|
||||
): readonly CapabilityDescriptor[] => {
|
||||
const available = platform === "darwin";
|
||||
return Object.freeze(
|
||||
[
|
||||
...NATIVE_TOOL_CONTRACTS,
|
||||
{ name: "inspect_native_dispatch_metadata" as const },
|
||||
].map((contract): CapabilityDescriptor => {
|
||||
const availability = available
|
||||
? ({ available: true, reason: null } as const)
|
||||
: ({
|
||||
available: false,
|
||||
availabilityCode: "unsupported_host",
|
||||
reason: "Native macOS utilities require macOS.",
|
||||
} as const);
|
||||
return Object.freeze({
|
||||
provider: IDENTITY,
|
||||
operation: contract.name,
|
||||
...availability,
|
||||
effects: Object.freeze({
|
||||
mutatesArtifact: false,
|
||||
launchesProcess: contract.name !== "inspect_native_dispatch_metadata",
|
||||
mayShowUi: contract.name === "capture_native_ui_scenario",
|
||||
mayAccessNetwork: contract.name === "capture_native_ui_scenario",
|
||||
mayWriteFilesystem:
|
||||
contract.name === "capture_native_ui_scenario" ||
|
||||
contract.name === "observe_native_ui",
|
||||
changesPermissions: false,
|
||||
requiresRoot: false,
|
||||
}),
|
||||
limitations: Object.freeze([
|
||||
"Availability and textual formats depend on the installed macOS/Xcode toolchain.",
|
||||
]),
|
||||
});
|
||||
}),
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,73 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { parsePlistJson, parsePlistXml } from "./plist.js";
|
||||
|
||||
it("keeps exact decimal text for JSON integers beyond the safe range", () => {
|
||||
const parsed = parsePlistJson(
|
||||
'{"Max":18446744073709551615,"Min":-9223372036854775808,"Safe":9007199254740991,"Real":1e21,"Ratio":0.5}',
|
||||
);
|
||||
if (!parsed.ok) throw new Error("expected plist JSON to parse");
|
||||
expect(parsed.value.value).toEqual({
|
||||
Max: { $plist_type: "integer", decimal: "18446744073709551615" },
|
||||
Min: { $plist_type: "integer", decimal: "-9223372036854775808" },
|
||||
Safe: 9007199254740991,
|
||||
Real: 1e21,
|
||||
Ratio: 0.5,
|
||||
});
|
||||
expect(parsed.value.limitations).toEqual([
|
||||
expect.stringContaining("2 integer value(s)"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("reports no limitation when every JSON integer is exact", () => {
|
||||
const parsed = parsePlistJson('{"Count":42,"Nested":[-1,0]}');
|
||||
if (!parsed.ok) throw new Error("expected plist JSON to parse");
|
||||
expect(parsed.value.value).toEqual({ Count: 42, Nested: [-1, 0] });
|
||||
expect(parsed.value.limitations).toEqual([]);
|
||||
});
|
||||
|
||||
it("recovers exact XML integers from their element literals", () => {
|
||||
const parsed = parsePlistXml(
|
||||
"<plist><dict><key>Max</key><integer>18446744073709551615</integer><key>Safe</key><integer>7</integer><key>Blob</key><data>AA==</data></dict></plist>",
|
||||
);
|
||||
if (!parsed.ok) throw new Error("expected plist XML to parse");
|
||||
expect(parsed.value.value).toEqual({
|
||||
Max: { $plist_type: "integer", decimal: "18446744073709551615" },
|
||||
Safe: 7,
|
||||
Blob: { $plist_type: "data", base64: "AA==" },
|
||||
});
|
||||
expect(parsed.value.limitations).toEqual([
|
||||
expect.stringContaining("XML conversion"),
|
||||
expect.stringContaining("1 integer value(s)"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("keeps integral XML reals beyond the safe range as reals", () => {
|
||||
const parsed = parsePlistXml(
|
||||
"<plist><dict><key>Real</key><real>9007199254740992</real><key>Blob</key><data>AA==</data></dict></plist>",
|
||||
);
|
||||
if (!parsed.ok) throw new Error("expected plist XML to parse");
|
||||
expect(parsed.value.value).toEqual({
|
||||
Real: 9007199254740992,
|
||||
Blob: { $plist_type: "data", base64: "AA==" },
|
||||
});
|
||||
expect(parsed.value.limitations).toEqual([
|
||||
expect.stringContaining("XML conversion"),
|
||||
]);
|
||||
});
|
||||
|
||||
it("reports XML numbers whose integer or real origin is ambiguous", () => {
|
||||
const parsed = parsePlistXml(
|
||||
"<plist><array><integer>9007199254740993</integer><real>9007199254740992</real><data>AA==</data></array></plist>",
|
||||
);
|
||||
if (!parsed.ok) throw new Error("expected plist XML to parse");
|
||||
expect(parsed.value.value).toEqual([
|
||||
9007199254740992,
|
||||
9007199254740992,
|
||||
{ $plist_type: "data", base64: "AA==" },
|
||||
]);
|
||||
expect(parsed.value.limitations).toEqual([
|
||||
expect.stringContaining("XML conversion"),
|
||||
expect.stringContaining("2 number(s)"),
|
||||
]);
|
||||
});
|
||||
+165
-30
@@ -1,50 +1,185 @@
|
||||
import { parse as parseXmlPlist } from "plist";
|
||||
import { z } from "zod";
|
||||
|
||||
import { AnalysisOutputError } from "../../domain/analysisErrorCore.js";
|
||||
import type { JsonValue } from "../../domain/jsonValue.js";
|
||||
import {
|
||||
projectPlistValue,
|
||||
type ProjectedPlistValue,
|
||||
} from "../../domain/plistValue.js";
|
||||
import { err, ok, type Result } from "../../domain/result.js";
|
||||
import { safeParseJson } from "../../domain/safeJson.js";
|
||||
|
||||
const plistObject = z.record(z.string(), z.unknown());
|
||||
|
||||
/** Stable bundle metadata projected from one plist value. */
|
||||
export interface PlistBundleMetadata {
|
||||
readonly identifier: string | null;
|
||||
readonly executable: string | null;
|
||||
readonly name: string | null;
|
||||
readonly version: string | null;
|
||||
readonly short_version: string | null;
|
||||
}
|
||||
|
||||
/** One decoded plist with bundle metadata and decoding limitations. */
|
||||
export interface ParsedPlist {
|
||||
readonly value: unknown;
|
||||
readonly bundle: PlistBundleMetadata;
|
||||
readonly limitations: readonly string[];
|
||||
}
|
||||
|
||||
/** Parse plutil JSON output and project stable bundle metadata. */
|
||||
export const parsePlistJson = (
|
||||
output: string,
|
||||
): Result<
|
||||
{
|
||||
readonly value: unknown;
|
||||
readonly bundle: {
|
||||
readonly identifier: string | null;
|
||||
readonly executable: string | null;
|
||||
readonly name: string | null;
|
||||
readonly version: string | null;
|
||||
readonly short_version: string | null;
|
||||
};
|
||||
},
|
||||
AnalysisOutputError
|
||||
> => {
|
||||
): Result<ParsedPlist, AnalysisOutputError> => {
|
||||
// plutil output can carry a UTF-8 BOM, which JSON.parse rejects outright.
|
||||
const parsed = safeParseJson(output.replace(/^\uFEFF/u, ""));
|
||||
if (!parsed.ok)
|
||||
const text = output.replace(/^\uFEFF/u, "");
|
||||
let exactIntegerCount = 0;
|
||||
// A plist integer can exceed the exact range of a JavaScript number; keep
|
||||
// its decimal text from the JSON source instead of a rounded value.
|
||||
const keepExactIntegers = (
|
||||
_key: string,
|
||||
item: unknown,
|
||||
context?: { readonly source?: string },
|
||||
): unknown => {
|
||||
const source = context?.source;
|
||||
if (
|
||||
typeof item !== "number" ||
|
||||
Number.isSafeInteger(item) ||
|
||||
source === undefined ||
|
||||
!/^-?\d+$/u.test(source)
|
||||
)
|
||||
return item;
|
||||
exactIntegerCount += 1;
|
||||
return { $plist_type: "integer", decimal: source };
|
||||
};
|
||||
let value: unknown;
|
||||
try {
|
||||
value = JSON.parse(text, keepExactIntegers);
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new AnalysisOutputError("inspect_plist", parsed.error, {
|
||||
cause: parsed.cause,
|
||||
}),
|
||||
new AnalysisOutputError(
|
||||
"inspect_plist",
|
||||
cause instanceof Error ? cause.message : String(cause),
|
||||
{ cause },
|
||||
),
|
||||
);
|
||||
const value: unknown = parsed.value;
|
||||
}
|
||||
return ok({
|
||||
value,
|
||||
bundle: projectPlistBundle(value),
|
||||
limitations:
|
||||
exactIntegerCount === 0
|
||||
? []
|
||||
: [largeIntegerLimitation(exactIntegerCount)],
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse plutil XML output for a plist that JSON cannot express, such as one
|
||||
* containing data, dates, or non-finite reals.
|
||||
*/
|
||||
export const parsePlistXml = (
|
||||
output: string,
|
||||
): Result<ParsedPlist, AnalysisOutputError> => {
|
||||
let projected: ProjectedPlistValue;
|
||||
try {
|
||||
projected = projectPlistValue(parseXmlPlist(output));
|
||||
} catch (cause: unknown) {
|
||||
return err(
|
||||
new AnalysisOutputError(
|
||||
"inspect_plist",
|
||||
"plutil XML conversion was not a readable plist",
|
||||
{ cause },
|
||||
),
|
||||
);
|
||||
}
|
||||
// The XML decoder turns <integer> and <real> into numbers before REA sees
|
||||
// them, rounding integers beyond the exact range. plutil escapes "<" in keys
|
||||
// and strings, so the element literals can be read from the XML text.
|
||||
const unsafeIntegers = new Map<number, Set<string>>();
|
||||
for (const [, decimal = ""] of output.matchAll(
|
||||
/<integer>\s*([+-]?\d+)\s*<\/integer>/gu,
|
||||
)) {
|
||||
const rounded = Number(decimal);
|
||||
if (Number.isSafeInteger(rounded)) continue;
|
||||
const exact = BigInt(decimal).toString();
|
||||
unsafeIntegers.set(
|
||||
rounded,
|
||||
(unsafeIntegers.get(rounded) ?? new Set()).add(exact),
|
||||
);
|
||||
}
|
||||
const reals = new Set(
|
||||
[...output.matchAll(/<real>([^<]*)<\/real>/gu)].map(([, text = ""]) =>
|
||||
Number.parseFloat(text),
|
||||
),
|
||||
);
|
||||
let exactIntegerCount = 0;
|
||||
let ambiguousNumberCount = 0;
|
||||
const value = mapJsonNumbers(projected.value, (item) => {
|
||||
const decimals = unsafeIntegers.get(item);
|
||||
if (decimals === undefined) return item;
|
||||
const [decimal] = decimals;
|
||||
if (decimals.size !== 1 || decimal === undefined || reals.has(item)) {
|
||||
ambiguousNumberCount += 1;
|
||||
return item;
|
||||
}
|
||||
exactIntegerCount += 1;
|
||||
return { $plist_type: "integer", decimal };
|
||||
});
|
||||
return ok({
|
||||
value,
|
||||
bundle: projectPlistBundle(value),
|
||||
limitations: [
|
||||
'plutil cannot express this plist as JSON, so it was decoded from plutil\'s XML conversion; data and date values are typed objects such as { "$plist_type": "data", "base64": ... }.',
|
||||
...(projected.unknownRealCount === 0
|
||||
? []
|
||||
: [
|
||||
`${String(projected.unknownRealCount)} non-finite real value(s) are reported as { "$plist_type": "real", "value": null } because the XML decoder does not distinguish NaN from infinity.`,
|
||||
]),
|
||||
...(exactIntegerCount === 0
|
||||
? []
|
||||
: [largeIntegerLimitation(exactIntegerCount)]),
|
||||
...(ambiguousNumberCount === 0
|
||||
? []
|
||||
: [
|
||||
`${String(ambiguousNumberCount)} number(s) beyond the exact range of a JSON number are reported as decoded because the XML literal they came from, a rounded <integer> or a <real>, cannot be identified.`,
|
||||
]),
|
||||
],
|
||||
});
|
||||
};
|
||||
|
||||
const largeIntegerLimitation = (count: number): string =>
|
||||
`${String(count)} integer value(s) exceed the exact range of a JSON number and are reported as { "$plist_type": "integer", "decimal": "<exact digits>" }.`;
|
||||
|
||||
const mapJsonNumbers = (
|
||||
value: JsonValue,
|
||||
map: (item: number) => JsonValue,
|
||||
): JsonValue => {
|
||||
if (typeof value === "number") return map(value);
|
||||
if (Array.isArray(value))
|
||||
return value.map((item) => mapJsonNumbers(item, map));
|
||||
if (value !== null && typeof value === "object")
|
||||
return Object.fromEntries(
|
||||
Object.entries(value).map(([key, item]) => [
|
||||
key,
|
||||
mapJsonNumbers(item, map),
|
||||
]),
|
||||
);
|
||||
return value;
|
||||
};
|
||||
|
||||
const projectPlistBundle = (value: unknown): PlistBundleMetadata => {
|
||||
const object = plistObject.safeParse(value);
|
||||
const field = (name: string): string | null => {
|
||||
if (!object.success) return null;
|
||||
const candidate = object.data[name];
|
||||
return typeof candidate === "string" ? candidate : null;
|
||||
};
|
||||
return ok({
|
||||
value,
|
||||
bundle: {
|
||||
identifier: field("CFBundleIdentifier"),
|
||||
executable: field("CFBundleExecutable"),
|
||||
name: field("CFBundleName"),
|
||||
version: field("CFBundleVersion"),
|
||||
short_version: field("CFBundleShortVersionString"),
|
||||
},
|
||||
});
|
||||
return {
|
||||
identifier: field("CFBundleIdentifier"),
|
||||
executable: field("CFBundleExecutable"),
|
||||
name: field("CFBundleName"),
|
||||
version: field("CFBundleVersion"),
|
||||
short_version: field("CFBundleShortVersionString"),
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { EvidenceReader } from "../application/investigation/InvestigationRecordPort.js";
|
||||
import { z } from "zod";
|
||||
|
||||
import { uniqueSorted } from "../domain/canonicalOrdering.js";
|
||||
@@ -138,7 +139,7 @@ const evidenceCandidates = (
|
||||
};
|
||||
|
||||
type LedgerEvidence = ReturnType<
|
||||
BinarySessionPort["exportEvidenceBundle"]
|
||||
EvidenceReader["exportEvidenceBundle"]
|
||||
>["records"][number];
|
||||
|
||||
const evidenceValues = (
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
|
||||
import type { McpServer, ServerContext } from "@modelcontextprotocol/server";
|
||||
import { AndroidAnalysisService } from "../application/AndroidAnalysisService.js";
|
||||
import type { BinarySessionPort } from "../application/BinarySession.js";
|
||||
import { toolContract } from "../contracts/toolContracts.js";
|
||||
import type { ToolContract } from "../contracts/toolContractTypes.js";
|
||||
import type { AndroidOperation } from "../domain/androidAnalysis.js";
|
||||
@@ -14,7 +14,7 @@ export const registerAndroidTools = (
|
||||
server: McpServer,
|
||||
service: AndroidAnalysisService,
|
||||
logger: Logger,
|
||||
recordEvidence?: BinarySessionPort["recordEvidence"],
|
||||
recordEvidence?: EvidenceWriter["recordEvidence"],
|
||||
): void => {
|
||||
const handler = (contract: ToolContract<AndroidOperation>) => {
|
||||
const name = contract.name;
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
import type { BinarySessionPort } from "../../application/BinarySession.js";
|
||||
import type {
|
||||
EvidenceWriter,
|
||||
EvidenceReader,
|
||||
EvidenceUnknownWriter,
|
||||
} from "../../application/investigation/InvestigationRecordPort.js";
|
||||
import type { Logger } from "../../logger.js";
|
||||
|
||||
/** Shared services for registering JavaScript application graph workflows. */
|
||||
export interface ApplicationToolRegistration {
|
||||
readonly logger: Logger;
|
||||
readonly evidenceById: BinarySessionPort["evidenceById"] | undefined;
|
||||
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
|
||||
readonly evidenceById: EvidenceReader["evidenceById"] | undefined;
|
||||
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
|
||||
readonly recordEvidenceWithUnknown:
|
||||
| BinarySessionPort["recordEvidenceWithUnknown"]
|
||||
| EvidenceUnknownWriter["recordEvidenceWithUnknown"]
|
||||
| undefined;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import type { AnalysisOperationPort } from "../application/AnalysisProvider.js";
|
||||
import type { BinarySessionPort } from "../application/BinarySession.js";
|
||||
import { ARTIFACT_TOOL_CONTRACTS } from "../contracts/artifactToolContracts.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
@@ -15,7 +15,7 @@ export const registerArtifactTools = (
|
||||
options: {
|
||||
readonly logger: Logger;
|
||||
readonly activeTarget: (() => BinaryTarget | undefined) | undefined;
|
||||
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
|
||||
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
|
||||
},
|
||||
): void => {
|
||||
registerEvidenceTools(server, analysis, ARTIFACT_TOOL_CONTRACTS, {
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
|
||||
import {
|
||||
optionalProviderUnavailable,
|
||||
type OptionalProviderLoadFailure,
|
||||
@@ -5,10 +6,9 @@ import {
|
||||
import { err } from "../domain/result.js";
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import type { BinarySessionPort } from "../application/BinarySession.js";
|
||||
import type { BrowserScenarioCapturePort } from "../application/BrowserScenarioCapturePort.js";
|
||||
import { captureBrowserScenario } from "../application/BrowserScenarioCaptureService.js";
|
||||
import { BROWSER_SCENARIO_TOOL_CONTRACTS } from "../contracts/browserScenarioToolContracts.js";
|
||||
import { toolContract } from "../contracts/toolContracts.js";
|
||||
import { browserScenarioSchema } from "../domain/browserScenario.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
import { logToolExecution } from "./toolLogging.js";
|
||||
@@ -19,7 +19,7 @@ interface BrowserScenarioToolRegistration {
|
||||
readonly logger: Logger;
|
||||
readonly loadFailure?: OptionalProviderLoadFailure | undefined;
|
||||
readonly provider: BrowserScenarioCapturePort | undefined;
|
||||
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
|
||||
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
|
||||
}
|
||||
|
||||
/** Register the browser scenario tool with execution-time provider diagnostics. */
|
||||
@@ -27,7 +27,7 @@ export const registerBrowserScenarioTool = (
|
||||
server: McpServer,
|
||||
options: BrowserScenarioToolRegistration,
|
||||
): void => {
|
||||
const [contract] = BROWSER_SCENARIO_TOOL_CONTRACTS;
|
||||
const contract = toolContract("capture_browser_scenario");
|
||||
server.registerTool(
|
||||
contract.name,
|
||||
toolRegistrationOptions(contract),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
|
||||
import {
|
||||
optionalProviderUnavailable,
|
||||
type OptionalProviderLoadFailure,
|
||||
@@ -5,7 +6,6 @@ import {
|
||||
import { err } from "../domain/result.js";
|
||||
import type { McpServer, ServerContext } from "@modelcontextprotocol/server";
|
||||
|
||||
import type { BinarySessionPort } from "../application/BinarySession.js";
|
||||
import type { BrowserObservationPort } from "../application/BrowserObservationPort.js";
|
||||
import {
|
||||
analyzeWebBundle,
|
||||
@@ -18,8 +18,7 @@ import {
|
||||
observeWebSession,
|
||||
} from "../application/BrowserObservationService.js";
|
||||
import type { ProgressReporter } from "../application/ProgressReporter.js";
|
||||
import { BROWSER_TOOL_CONTRACTS } from "../contracts/browserToolContracts.js";
|
||||
import type { ToolContract } from "../contracts/toolContracts.js";
|
||||
import { toolContract, type ToolContract } from "../contracts/toolContracts.js";
|
||||
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import { analyzeWebBundleInputSchema } from "../domain/webBundleAnalysis.js";
|
||||
@@ -35,7 +34,7 @@ interface BrowserToolRegistration {
|
||||
readonly logger: Logger;
|
||||
readonly loadFailure?: OptionalProviderLoadFailure | undefined;
|
||||
readonly browser: BrowserObservationPort | undefined;
|
||||
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
|
||||
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
|
||||
}
|
||||
|
||||
interface BrowserToolContext {
|
||||
@@ -49,16 +48,14 @@ export const registerBrowserTools = (
|
||||
server: McpServer,
|
||||
options: BrowserToolRegistration,
|
||||
): void => {
|
||||
const [
|
||||
listContract,
|
||||
inspectContract,
|
||||
analyzeContract,
|
||||
sessionContract,
|
||||
webMcpContract,
|
||||
captureDiffContract,
|
||||
screenshotContract,
|
||||
screenshotDiffContract,
|
||||
] = BROWSER_TOOL_CONTRACTS;
|
||||
const listContract = toolContract("list_browser_targets");
|
||||
const inspectContract = toolContract("inspect_web_page");
|
||||
const analyzeContract = toolContract("analyze_web_bundle");
|
||||
const sessionContract = toolContract("observe_web_session");
|
||||
const webMcpContract = toolContract("discover_webmcp_tools");
|
||||
const captureDiffContract = toolContract("compare_web_captures");
|
||||
const screenshotContract = toolContract("capture_web_screenshot");
|
||||
const screenshotDiffContract = toolContract("compare_web_screenshots");
|
||||
|
||||
server.registerTool(
|
||||
listContract.name,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
|
||||
import {
|
||||
optionalProviderUnavailable,
|
||||
type OptionalProviderLoadFailure,
|
||||
@@ -5,7 +6,6 @@ import {
|
||||
import { err } from "../domain/result.js";
|
||||
import type { McpServer, ServerContext } from "@modelcontextprotocol/server";
|
||||
|
||||
import type { BinarySessionPort } from "../application/BinarySession.js";
|
||||
import type { ElectronActiveObservationPort } from "../application/ElectronActiveObservationPort.js";
|
||||
import { captureElectronScenario } from "../application/ElectronActiveObservationService.js";
|
||||
import type { ElectronObservationPort } from "../application/ElectronObservationPort.js";
|
||||
@@ -16,8 +16,7 @@ import {
|
||||
import { analyzeJavaScriptApplicationValidated } from "../application/JavaScriptApplicationService.js";
|
||||
import { reconcileJavaScriptRuntimeEvidenceValidated } from "../application/JavaScriptRuntimeReconciliationService.js";
|
||||
import type { ProgressReporter } from "../application/ProgressReporter.js";
|
||||
import { ELECTRON_TOOL_CONTRACTS } from "../contracts/electronToolContracts.js";
|
||||
import type { ToolContract } from "../contracts/toolContracts.js";
|
||||
import { toolContract, type ToolContract } from "../contracts/toolContracts.js";
|
||||
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
@@ -34,7 +33,7 @@ interface ElectronToolRegistration {
|
||||
readonly activeLoadFailure?: OptionalProviderLoadFailure | undefined;
|
||||
readonly electron: ElectronObservationPort | undefined;
|
||||
readonly electronActive: ElectronActiveObservationPort | undefined;
|
||||
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
|
||||
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
|
||||
}
|
||||
|
||||
interface ElectronToolContext {
|
||||
@@ -48,13 +47,11 @@ export const registerElectronTools = (
|
||||
server: McpServer,
|
||||
options: ElectronToolRegistration,
|
||||
): void => {
|
||||
const [
|
||||
listContract,
|
||||
inspectContract,
|
||||
analyzeContract,
|
||||
reconcileContract,
|
||||
activeContract,
|
||||
] = ELECTRON_TOOL_CONTRACTS;
|
||||
const listContract = toolContract("list_electron_targets");
|
||||
const inspectContract = toolContract("inspect_electron_page");
|
||||
const analyzeContract = toolContract("analyze_javascript_application");
|
||||
const reconcileContract = toolContract("reconcile_javascript_runtime");
|
||||
const activeContract = toolContract("capture_electron_scenario");
|
||||
|
||||
server.registerTool(
|
||||
listContract.name,
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
import type {
|
||||
EvidenceWriter,
|
||||
UnknownRegistryPort,
|
||||
} from "../application/investigation/InvestigationRecordPort.js";
|
||||
import type {
|
||||
CallToolResult,
|
||||
McpServer,
|
||||
@@ -5,7 +9,6 @@ import type {
|
||||
} from "@modelcontextprotocol/server";
|
||||
|
||||
import type { AnalysisOperationPort } from "../application/AnalysisProvider.js";
|
||||
import type { BinarySessionPort } from "../application/BinarySession.js";
|
||||
import {
|
||||
EnhancedTools,
|
||||
type ValidatedEnhancedCall,
|
||||
@@ -34,8 +37,8 @@ export interface EnhancedToolRegistration {
|
||||
readonly analysisProfile:
|
||||
| (() => AnalysisProfileCommitment | undefined)
|
||||
| undefined;
|
||||
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
|
||||
readonly recordUnknown: BinarySessionPort["recordUnknown"] | undefined;
|
||||
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
|
||||
readonly recordUnknown: UnknownRegistryPort["recordUnknown"] | undefined;
|
||||
}
|
||||
|
||||
/** Register composed workflows against the same port as direct bridge tools. */
|
||||
@@ -319,7 +322,7 @@ interface WorkflowUnknownInput {
|
||||
readonly name: string;
|
||||
readonly result: JsonValue;
|
||||
readonly evidenceId: string;
|
||||
readonly recordUnknown: BinarySessionPort["recordUnknown"] | undefined;
|
||||
readonly recordUnknown: UnknownRegistryPort["recordUnknown"] | undefined;
|
||||
}
|
||||
|
||||
const recordWorkflowUnknowns = ({
|
||||
@@ -328,7 +331,7 @@ const recordWorkflowUnknowns = ({
|
||||
evidenceId,
|
||||
recordUnknown,
|
||||
}: WorkflowUnknownInput):
|
||||
| ReturnType<BinarySessionPort["recordUnknown"]>
|
||||
| ReturnType<UnknownRegistryPort["recordUnknown"]>
|
||||
| { readonly ok: true; readonly value: null } => {
|
||||
if (
|
||||
!["trace_feature", "trace_call_path", "inspect_native_api"].includes(
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import type {
|
||||
AnalysisOperation,
|
||||
AnalysisOperationPort,
|
||||
} from "../application/AnalysisProvider.js";
|
||||
import type { BinarySessionPort } from "../application/BinarySession.js";
|
||||
import type { ToolContract } from "../contracts/toolContracts.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import { createEvidence, type Evidence } from "../domain/evidence.js";
|
||||
@@ -19,7 +19,7 @@ import { createArtifactExtractionDestination } from "../application/ArtifactExtr
|
||||
interface EvidenceToolRegistration {
|
||||
readonly logger: Logger;
|
||||
readonly activeTarget: (() => BinaryTarget | undefined) | undefined;
|
||||
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
|
||||
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
|
||||
readonly sourceEvidence?: (
|
||||
operation: Exclude<AnalysisOperation, "health">,
|
||||
result: import("../domain/jsonValue.js").JsonValue,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
|
||||
import type { McpServer, ServerContext } from "@modelcontextprotocol/server";
|
||||
import type { FirmwareAnalysisService } from "../application/FirmwareAnalysisService.js";
|
||||
import type { BinarySessionPort } from "../application/BinarySession.js";
|
||||
import { toolContract } from "../contracts/toolContracts.js";
|
||||
import type { ToolContract } from "../contracts/toolContractTypes.js";
|
||||
import type { FirmwareOperation } from "../domain/firmwareAnalysis.js";
|
||||
@@ -14,7 +14,7 @@ export const registerFirmwareTools = (
|
||||
server: McpServer,
|
||||
service: FirmwareAnalysisService,
|
||||
logger: Logger,
|
||||
recordEvidence?: BinarySessionPort["recordEvidence"],
|
||||
recordEvidence?: EvidenceWriter["recordEvidence"],
|
||||
): void => {
|
||||
const handler =
|
||||
(contract: ToolContract<FirmwareOperation>) =>
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
|
||||
import {
|
||||
optionalProviderUnavailable,
|
||||
type OptionalProviderLoadFailure,
|
||||
@@ -5,14 +6,12 @@ import {
|
||||
import { err } from "../domain/result.js";
|
||||
import type { McpServer, ServerContext } from "@modelcontextprotocol/server";
|
||||
|
||||
import type { BinarySessionPort } from "../application/BinarySession.js";
|
||||
import type { JavaScriptRuntimeObservationPort } from "../application/JavaScriptRuntimeObservationPort.js";
|
||||
import {
|
||||
listJavaScriptRuntimeTargets,
|
||||
observeJavaScriptRuntime,
|
||||
} from "../application/JavaScriptRuntimeObservationService.js";
|
||||
import { JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS } from "../contracts/javascriptRuntimeObservationToolContracts.js";
|
||||
import type { ToolContract } from "../contracts/toolContracts.js";
|
||||
import { toolContract, type ToolContract } from "../contracts/toolContracts.js";
|
||||
import type { AnalysisError } from "../domain/analysisErrorBase.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import type { Result } from "../domain/result.js";
|
||||
@@ -26,7 +25,7 @@ interface RuntimeToolRegistration {
|
||||
readonly logger: Logger;
|
||||
readonly loadFailure?: OptionalProviderLoadFailure | undefined;
|
||||
readonly runtime: JavaScriptRuntimeObservationPort | undefined;
|
||||
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
|
||||
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
|
||||
}
|
||||
|
||||
/** Register passive Inspector tools even when policy keeps them unavailable. */
|
||||
@@ -34,8 +33,8 @@ export const registerJavaScriptRuntimeObservationTools = (
|
||||
server: McpServer,
|
||||
options: RuntimeToolRegistration,
|
||||
): void => {
|
||||
const [listContract, observeContract] =
|
||||
JAVASCRIPT_RUNTIME_OBSERVATION_TOOL_CONTRACTS;
|
||||
const listContract = toolContract("list_javascript_runtime_targets");
|
||||
const observeContract = toolContract("observe_javascript_runtime");
|
||||
server.registerTool(
|
||||
listContract.name,
|
||||
toolRegistrationOptions(listContract),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import type { AnalysisOperationPort } from "../application/AnalysisProvider.js";
|
||||
@@ -18,7 +19,7 @@ export const registerManagedTools = (
|
||||
options: {
|
||||
readonly logger: Logger;
|
||||
readonly activeTarget: (() => BinaryTarget | undefined) | undefined;
|
||||
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
|
||||
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
|
||||
readonly session: BinarySessionPort | undefined;
|
||||
},
|
||||
): void => {
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
import type {
|
||||
EvidenceWriter,
|
||||
EvidenceUnknownWriter,
|
||||
} from "../../application/investigation/InvestigationRecordPort.js";
|
||||
import type { BinarySessionPort } from "../../application/BinarySession.js";
|
||||
import type { Logger } from "../../logger.js";
|
||||
|
||||
/** Shared services for registering managed-code workflow tools. */
|
||||
export interface ManagedWorkflowToolRegistration {
|
||||
readonly logger: Logger;
|
||||
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
|
||||
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
|
||||
readonly recordEvidenceWithUnknown:
|
||||
| BinarySessionPort["recordEvidenceWithUnknown"]
|
||||
| EvidenceUnknownWriter["recordEvidenceWithUnknown"]
|
||||
| undefined;
|
||||
readonly session: BinarySessionPort;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import type { AnalysisOperationPort } from "../application/AnalysisProvider.js";
|
||||
import type { BinarySessionPort } from "../application/BinarySession.js";
|
||||
import { NATIVE_TOOL_CONTRACTS } from "../contracts/nativeToolContracts.js";
|
||||
import type { BinaryTarget } from "../domain/binaryTarget.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
@@ -14,7 +14,7 @@ export const registerNativeTools = (
|
||||
options: {
|
||||
readonly logger: Logger;
|
||||
readonly activeTarget: (() => BinaryTarget | undefined) | undefined;
|
||||
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
|
||||
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
|
||||
},
|
||||
): void => {
|
||||
registerEvidenceTools(server, analysis, NATIVE_TOOL_CONTRACTS, options);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
|
||||
import type { McpServer, ServerContext } from "@modelcontextprotocol/server";
|
||||
import { z } from "zod";
|
||||
|
||||
@@ -5,7 +6,6 @@ import type {
|
||||
AnalysisExecution,
|
||||
AnalysisOperationPort,
|
||||
} from "../application/AnalysisProvider.js";
|
||||
import type { BinarySessionPort } from "../application/BinarySession.js";
|
||||
import type { ProgressReporter } from "../application/ProgressReporter.js";
|
||||
import type { ToolContract } from "../contracts/toolContracts.js";
|
||||
import { OFFICIAL_TOOL_CONTRACTS } from "../contracts/officialToolContracts.js";
|
||||
@@ -28,7 +28,7 @@ import { toCallToolResult } from "./toolResult.js";
|
||||
export interface OfficialToolRegistration {
|
||||
readonly logger: Logger;
|
||||
readonly activeTarget: (() => BinaryTarget | undefined) | undefined;
|
||||
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
|
||||
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
|
||||
}
|
||||
|
||||
/** Register direct bridge proxies, preserving MCP cancellation and typed errors. */
|
||||
@@ -53,7 +53,7 @@ const registerOfficialTool = (
|
||||
registration: {
|
||||
readonly logger: Logger;
|
||||
readonly activeTarget: (() => BinaryTarget | undefined) | undefined;
|
||||
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
|
||||
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
|
||||
},
|
||||
): void => {
|
||||
server.registerTool(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
|
||||
import type { McpServer } from "@modelcontextprotocol/server";
|
||||
|
||||
import type { BinarySessionPort } from "../application/BinarySession.js";
|
||||
import { exportWebScriptsValidated } from "../application/WebScriptExportService.js";
|
||||
import { toolContract } from "../contracts/toolContracts.js";
|
||||
import type { Logger } from "../logger.js";
|
||||
@@ -13,7 +13,7 @@ export const registerWebScriptTool = (
|
||||
server: McpServer,
|
||||
options: {
|
||||
readonly logger: Logger;
|
||||
readonly recordEvidence: BinarySessionPort["recordEvidence"] | undefined;
|
||||
readonly recordEvidence: EvidenceWriter["recordEvidence"] | undefined;
|
||||
},
|
||||
): void => {
|
||||
const contract = toolContract("export_web_scripts");
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
import type { BinarySessionPort } from "../application/BinarySession.js";
|
||||
import type { EvidenceWriter } from "../application/investigation/InvestigationRecordPort.js";
|
||||
import { EvidenceIntegrityError } from "../domain/evidenceErrors.js";
|
||||
import type { Evidence } from "../domain/evidence.js";
|
||||
import { ok, type Result } from "../domain/result.js";
|
||||
|
||||
/** Record source evidence in order, stopping at the first session rejection. */
|
||||
export const recordSessionEvidenceSources = (
|
||||
recordEvidence: BinarySessionPort["recordEvidence"] | undefined,
|
||||
recordEvidence: EvidenceWriter["recordEvidence"] | undefined,
|
||||
sources: readonly Evidence[],
|
||||
): Result<null, EvidenceIntegrityError> => {
|
||||
for (const source of sources) {
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { promisify } from "node:util";
|
||||
import { expect, it } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { GENERATED_MCP_TOOL_CATALOG } from "../../src/generatedMcpToolCatalog.js";
|
||||
|
||||
const execute = promisify(execFile);
|
||||
const fixture = fileURLToPath(
|
||||
new URL("../fixtures/contractPresentation.mjs", import.meta.url),
|
||||
);
|
||||
const resultSchema = z.object({
|
||||
catalog: z.array(
|
||||
z.object({
|
||||
name: z.string(),
|
||||
inputSchema: z.record(z.string(), z.unknown()),
|
||||
outputSchema: z.record(z.string(), z.unknown()),
|
||||
}),
|
||||
),
|
||||
responses: z.array(
|
||||
z.object({ name: z.string(), response: z.record(z.string(), z.unknown()) }),
|
||||
),
|
||||
});
|
||||
|
||||
it.each(["original", "reversed"])(
|
||||
"preserves advertised schemas and handler meaning with %s presentation",
|
||||
async (presentation) => {
|
||||
const { stdout } = await execute(
|
||||
process.execPath,
|
||||
[fixture, presentation],
|
||||
{
|
||||
timeout: 20_000,
|
||||
maxBuffer: 16 * 1024 * 1024,
|
||||
},
|
||||
);
|
||||
const result = resultSchema.parse(JSON.parse(stdout));
|
||||
expect(result.catalog).toHaveLength(GENERATED_MCP_TOOL_CATALOG.length);
|
||||
expect(new Set(result.catalog.map(({ name }) => name))).toEqual(
|
||||
new Set(GENERATED_MCP_TOOL_CATALOG.map(({ name }) => name)),
|
||||
);
|
||||
for (const advertised of result.catalog) {
|
||||
const canonical = GENERATED_MCP_TOOL_CATALOG.find(
|
||||
({ name }) => name === advertised.name,
|
||||
);
|
||||
expect(advertised.inputSchema).toEqual(canonical?.inputSchema);
|
||||
expect(advertised.outputSchema).toEqual(canonical?.outputSchema);
|
||||
}
|
||||
for (const { name, response } of result.responses) {
|
||||
if (name === "reconcile_javascript_runtime") {
|
||||
expect(response.isError).not.toBe(true);
|
||||
expect(response.structuredContent).toMatchObject({
|
||||
evidence: { operation: name },
|
||||
});
|
||||
} else {
|
||||
expect(response.isError, name).toBe(true);
|
||||
expect(response.structuredContent, name).toMatchObject({
|
||||
error: { details: { operation: name } },
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -1,29 +1,23 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { rm } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { describe, expect } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import {
|
||||
processTest as it,
|
||||
waitForExit,
|
||||
} from "../../support/process/processFixture.js";
|
||||
|
||||
import {
|
||||
BrowserStartupError,
|
||||
waitForBrowserDevtoolsPort,
|
||||
} from "../../../src/browser/BrowserProcessStartup.js";
|
||||
|
||||
const roots: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
describe("browser process startup", () => {
|
||||
it("returns a delayed valid DevToolsActivePort", async () => {
|
||||
it("returns a delayed valid DevToolsActivePort", async ({ processes }) => {
|
||||
const root = await temporaryRoot();
|
||||
const portPath = join(root, "DevToolsActivePort");
|
||||
const child = spawn(process.execPath, [
|
||||
const child = processes.spawn(process.execPath, [
|
||||
"-e",
|
||||
`setTimeout(() => require("node:fs").writeFileSync(${JSON.stringify(portPath)}, "43117\\n/browser"), 20); setTimeout(() => {}, 1000)`,
|
||||
]);
|
||||
@@ -40,12 +34,15 @@ describe("browser process startup", () => {
|
||||
).resolves.toBe(43_117);
|
||||
} finally {
|
||||
child.kill("SIGKILL");
|
||||
expect(await waitForExit(child, 5_000)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it("classifies signal termination instead of timing out", async () => {
|
||||
it("classifies signal termination instead of timing out", async ({
|
||||
processes,
|
||||
}) => {
|
||||
const root = await temporaryRoot();
|
||||
const child = spawn(process.execPath, [
|
||||
const child = processes.spawn(process.execPath, [
|
||||
"-e",
|
||||
"process.kill(process.pid, 'SIGTERM')",
|
||||
]);
|
||||
@@ -68,9 +65,12 @@ describe("browser process startup", () => {
|
||||
});
|
||||
});
|
||||
|
||||
it("reports bounded timeout diagnostics", async () => {
|
||||
it("reports bounded timeout diagnostics", async ({ processes }) => {
|
||||
const root = await temporaryRoot();
|
||||
const child = spawn(process.execPath, ["-e", "setTimeout(() => {}, 1000)"]);
|
||||
const child = processes.spawn(process.execPath, [
|
||||
"-e",
|
||||
"setTimeout(() => {}, 1000)",
|
||||
]);
|
||||
try {
|
||||
const failure = await waitForBrowserDevtoolsPort({
|
||||
child,
|
||||
@@ -90,12 +90,11 @@ describe("browser process startup", () => {
|
||||
expect(String(failure)).toContain("stderr=<empty>");
|
||||
} finally {
|
||||
child.kill("SIGKILL");
|
||||
expect(await waitForExit(child, 5_000)).toBe(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const temporaryRoot = async (): Promise<string> => {
|
||||
const root = await createTestTempDirectory("rea-browser-startup-");
|
||||
roots.push(root);
|
||||
return root;
|
||||
return createTestTempDirectory("rea-browser-startup-");
|
||||
};
|
||||
|
||||
@@ -391,11 +391,12 @@ describeBrowser("CdpBrowserProvider: lifecycle failures 4", () => {
|
||||
);
|
||||
if (!committed.ok) throw committed.error;
|
||||
expect(committed.value.target.origin).toBe(transitioning.allowedOrigin);
|
||||
expect(
|
||||
transitioning.commands.filter(
|
||||
({ method }) => method === "Page.getFrameTree",
|
||||
),
|
||||
).toHaveLength(5);
|
||||
expect(committed.value.frames).toContainEqual(
|
||||
expect.objectContaining({
|
||||
frame_id: "frame-main",
|
||||
origin: transitioning.allowedOrigin,
|
||||
}),
|
||||
);
|
||||
|
||||
const navigated = await startFakeCdpBrowser({
|
||||
attachedFrameUrl: "https://unapproved.example.test/after-attach",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { createServer } from "node:http";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it, onTestFinished } from "vitest";
|
||||
import { fetchWebSourceMaps } from "../../../src/browser/WebSourceMapFetcher.js";
|
||||
import { analyzeWebBundleInputSchema } from "../../../src/domain/webBundleAnalysis.js";
|
||||
|
||||
@@ -34,6 +34,12 @@ describe("source-map discarded HTTP response ownership", () => {
|
||||
notifyClosed?.();
|
||||
});
|
||||
});
|
||||
const closeServer = async (): Promise<void> => {
|
||||
server.closeAllConnections();
|
||||
if (server.listening)
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
};
|
||||
onTestFinished(closeServer);
|
||||
try {
|
||||
await new Promise<void>((resolve) =>
|
||||
server.listen(0, "127.0.0.1", resolve),
|
||||
@@ -62,22 +68,10 @@ describe("source-map discarded HTTP response ownership", () => {
|
||||
expect(result.items[0]?.status).toBe(
|
||||
status === 302 ? "included" : "fetch_failed",
|
||||
);
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
await Promise.race([
|
||||
closed,
|
||||
new Promise<void>((resolve) => {
|
||||
timer = setTimeout(resolve, 500);
|
||||
}),
|
||||
]);
|
||||
expect(didClose).toBe(true);
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
await closed;
|
||||
expect(didClose).toBe(true);
|
||||
} finally {
|
||||
server.closeAllConnections();
|
||||
if (server.listening)
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
await closeServer();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { execFile } from "node:child_process";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { describe, expect } from "vitest";
|
||||
|
||||
@@ -60,5 +62,123 @@ describe.skipIf(process.platform !== "darwin")(
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
cliTest.for(["xml", "binary"] as const)(
|
||||
"decodes $0 plists that plutil cannot express as JSON",
|
||||
async (format, { cli }) => {
|
||||
const directory = await createTestTempDirectory("rea-plist-types-");
|
||||
const app = join(directory, "Example.app");
|
||||
const contents = join(app, "Contents");
|
||||
await mkdir(join(contents, "MacOS"), { recursive: true });
|
||||
await writeFile(
|
||||
join(contents, "MacOS/App"),
|
||||
thinMach(0xfeedfacf, 0x0100000c),
|
||||
);
|
||||
const plist = join(contents, "Info.plist");
|
||||
await writeFile(
|
||||
plist,
|
||||
[
|
||||
"<plist><dict>",
|
||||
"<key>CFBundleExecutable</key><string>App</string>",
|
||||
"<key>CFBundleIdentifier</key><string>com.example.types</string>",
|
||||
"<key>Blob</key><data>AAEC</data>",
|
||||
"<key>Built</key><date>2020-01-01T00:00:00Z</date>",
|
||||
"<key>Ratio</key><real>nan</real>",
|
||||
"</dict></plist>",
|
||||
].join(""),
|
||||
);
|
||||
if (format === "binary")
|
||||
await promisify(execFile)("/usr/bin/plutil", [
|
||||
"-convert",
|
||||
"binary1",
|
||||
"--",
|
||||
plist,
|
||||
]);
|
||||
const result = await cli.run({
|
||||
arguments: ["inspect-plist", app, "--json"],
|
||||
environment: {
|
||||
REA_LOG_LEVEL: "silent",
|
||||
REA_ANALYSIS_PROVIDER: "auto",
|
||||
},
|
||||
});
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.json).toMatchObject({
|
||||
normalized_result: {
|
||||
format,
|
||||
value: {
|
||||
CFBundleIdentifier: "com.example.types",
|
||||
Blob: { $plist_type: "data", base64: "AAEC" },
|
||||
Built: {
|
||||
$plist_type: "date",
|
||||
iso8601: "2020-01-01T00:00:00.000Z",
|
||||
},
|
||||
Ratio: { $plist_type: "real", value: null },
|
||||
},
|
||||
bundle: { identifier: "com.example.types", executable: "App" },
|
||||
provenance: [
|
||||
{ tool: "file" },
|
||||
{ command: expect.arrayContaining(["json"]), exit: { code: 1 } },
|
||||
{ command: expect.arrayContaining(["xml1"]), exit: { code: 0 } },
|
||||
],
|
||||
limitations: [
|
||||
expect.stringContaining("XML conversion"),
|
||||
expect.stringContaining("1 non-finite real"),
|
||||
],
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
describe.skipIf(process.platform !== "darwin")(
|
||||
"native plist CLI integers",
|
||||
() => {
|
||||
cliTest.for([false, true])(
|
||||
"reports exact plist integers beyond the JSON number range (data: %s)",
|
||||
async (withData, { cli }) => {
|
||||
const directory = await createTestTempDirectory("rea-plist-integers-");
|
||||
const app = join(directory, "Example.app");
|
||||
const contents = join(app, "Contents");
|
||||
await mkdir(join(contents, "MacOS"), { recursive: true });
|
||||
await writeFile(
|
||||
join(contents, "MacOS/App"),
|
||||
thinMach(0xfeedfacf, 0x0100000c),
|
||||
);
|
||||
await writeFile(
|
||||
join(contents, "Info.plist"),
|
||||
[
|
||||
"<plist><dict>",
|
||||
"<key>CFBundleExecutable</key><string>App</string>",
|
||||
"<key>Max</key><integer>18446744073709551615</integer>",
|
||||
"<key>Min</key><integer>-9223372036854775808</integer>",
|
||||
"<key>Count</key><integer>42</integer>",
|
||||
...(withData ? ["<key>Blob</key><data>AAEC</data>"] : []),
|
||||
"</dict></plist>",
|
||||
].join(""),
|
||||
);
|
||||
const result = await cli.run({
|
||||
arguments: ["inspect-plist", app, "--json"],
|
||||
environment: {
|
||||
REA_LOG_LEVEL: "silent",
|
||||
REA_ANALYSIS_PROVIDER: "auto",
|
||||
},
|
||||
});
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.json).toMatchObject({
|
||||
normalized_result: {
|
||||
value: {
|
||||
Max: { $plist_type: "integer", decimal: "18446744073709551615" },
|
||||
Min: { $plist_type: "integer", decimal: "-9223372036854775808" },
|
||||
Count: 42,
|
||||
},
|
||||
limitations: [
|
||||
...(withData ? [expect.stringContaining("XML conversion")] : []),
|
||||
expect.stringContaining("2 integer value(s)"),
|
||||
],
|
||||
},
|
||||
});
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
+12
-21
@@ -1,26 +1,20 @@
|
||||
import { existsSync } from "node:fs";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { mkdtemp, mkdir, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { execFile } from "node:child_process";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { buildBinary } from "plist";
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { analyzeInterfaceBuilderBundle } from "./InterfaceBuilderAnalysis.js";
|
||||
import { analyzeInterfaceBuilderBundle } from "../../../src/application/InterfaceBuilderAnalysis.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const roots: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
roots.splice(0).map((root) => rm(root, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
const compile = promisify(execFile);
|
||||
|
||||
describe("compiled Interface Builder bundle reader", () => {
|
||||
it("reads nib plist archives and reports provenance", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-ib-test-"));
|
||||
roots.push(root);
|
||||
const root = await createTestTempDirectory("rea-ib-test-");
|
||||
const bundle = join(root, "Example.app");
|
||||
const nib = join(
|
||||
bundle,
|
||||
@@ -78,8 +72,7 @@ describe("compiled Interface Builder bundle reader", () => {
|
||||
});
|
||||
|
||||
it("honors cancellation during directory traversal", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-ib-test-"));
|
||||
roots.push(root);
|
||||
const root = await createTestTempDirectory("rea-ib-test-");
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
await expect(
|
||||
@@ -94,8 +87,7 @@ describe("compiled Interface Builder bundle reader", () => {
|
||||
|
||||
describe("bounded Interface Builder archive decoding", () => {
|
||||
it("counts malformed archives against the document limit", async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-ib-test-"));
|
||||
roots.push(root);
|
||||
const root = await createTestTempDirectory("rea-ib-test-");
|
||||
const bundle = join(root, "Example.app");
|
||||
const resources = join(bundle, "Contents", "Resources");
|
||||
await mkdir(resources, { recursive: true });
|
||||
@@ -122,8 +114,7 @@ describe("bounded Interface Builder archive decoding", () => {
|
||||
it.skipIf(process.platform !== "darwin" || !existsSync("/usr/bin/ibtool"))(
|
||||
"decodes an Xcode-compiled storyboard NIB and recovers its UI routes",
|
||||
async () => {
|
||||
const root = await mkdtemp(join(tmpdir(), "rea-ib-compiled-test-"));
|
||||
roots.push(root);
|
||||
const root = await createTestTempDirectory("rea-ib-compiled-test-");
|
||||
const bundle = join(root, "Example.app");
|
||||
const resources = join(bundle, "Contents", "Resources");
|
||||
const source = join(
|
||||
@@ -134,7 +125,7 @@ describe("bounded Interface Builder archive decoding", () => {
|
||||
"MacFixture.storyboard",
|
||||
);
|
||||
await mkdir(resources, { recursive: true });
|
||||
execFileSync("/usr/bin/ibtool", [
|
||||
await compile("/usr/bin/ibtool", [
|
||||
"--compile",
|
||||
join(resources, "MacFixture.storyboardc"),
|
||||
source,
|
||||
+8
-5
@@ -1,12 +1,15 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { execFile } from "node:child_process";
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { promisify } from "node:util";
|
||||
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../tests/fixtures/temporaryDirectory.js";
|
||||
import { decodeNibArchive } from "../artifacts/NibArchive.js";
|
||||
import { analyzeInterfaceBuilderBundle } from "./InterfaceBuilderAnalysis.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
import { decodeNibArchive } from "../../../src/artifacts/NibArchive.js";
|
||||
import { analyzeInterfaceBuilderBundle } from "../../../src/application/InterfaceBuilderAnalysis.js";
|
||||
|
||||
const compile = promisify(execFile);
|
||||
|
||||
const compileNestedViews = async (depth: number, withWindow = false) => {
|
||||
const root = await createTestTempDirectory("rea-nib-hierarchy-");
|
||||
@@ -34,7 +37,7 @@ const compileNestedViews = async (depth: number, withWindow = false) => {
|
||||
.replace("</view>\n </objects>", "</view></window>\n </objects>");
|
||||
await writeFile(xib, xibSource);
|
||||
const nib = join(resources, "Main.nib");
|
||||
execFileSync("/usr/bin/xcrun", [
|
||||
await compile("/usr/bin/xcrun", [
|
||||
"ibtool",
|
||||
"--errors",
|
||||
"--warnings",
|
||||
@@ -11,24 +11,28 @@ import { PRODUCT_IDENTITY } from "../../../src/identity.js";
|
||||
const pinnedPackage = PRODUCT_IDENTITY.registrationPackageSpecifier;
|
||||
|
||||
describe("JSON client configuration transaction", () => {
|
||||
it("rejects a symlink target not owned by the current user", async () => {
|
||||
if (typeof process.getuid !== "function") return;
|
||||
const currentUid = process.getuid();
|
||||
let statCalls = 0;
|
||||
expect(
|
||||
await resolveClientConfigTransactionPath("/config", {
|
||||
lstat: () => {
|
||||
statCalls += 1;
|
||||
return Promise.resolve({
|
||||
uid: statCalls === 1 ? currentUid : currentUid + 1,
|
||||
isFile: () => statCalls > 1,
|
||||
isSymbolicLink: () => statCalls === 1,
|
||||
});
|
||||
},
|
||||
realpath: () => Promise.resolve("/target"),
|
||||
}),
|
||||
).toBeUndefined();
|
||||
});
|
||||
it.skipIf(typeof process.getuid !== "function")(
|
||||
"rejects a symlink target not owned by the current user",
|
||||
async () => {
|
||||
const currentUid = process.getuid?.();
|
||||
if (currentUid === undefined)
|
||||
throw new Error("UID support is required by this test");
|
||||
let statCalls = 0;
|
||||
expect(
|
||||
await resolveClientConfigTransactionPath("/config", {
|
||||
lstat: () => {
|
||||
statCalls += 1;
|
||||
return Promise.resolve({
|
||||
uid: statCalls === 1 ? currentUid : currentUid + 1,
|
||||
isFile: () => statCalls > 1,
|
||||
isSymbolicLink: () => statCalls === 1,
|
||||
});
|
||||
},
|
||||
realpath: () => Promise.resolve("/target"),
|
||||
}),
|
||||
).toBeUndefined();
|
||||
},
|
||||
);
|
||||
|
||||
it("preserves existing keys, creates a backup, and reads back the MCP entry", async () => {
|
||||
const directory = await createTestTempDirectory("rea-setup-");
|
||||
|
||||
@@ -340,6 +340,37 @@ it("retains an uncertain workspace and blocks new launches after cleanup failure
|
||||
expect(fixture.launches).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("accepts another build on the verified release line and reports it", async () => {
|
||||
const fixture = await firmwareFixture("normal", "binwalk 3.1.2");
|
||||
const result = await fixture.service.execute("inspect_firmware_regions", {
|
||||
path: fixture.path,
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
expect(result.value.provider.version).toBe("3.1.2");
|
||||
expect(result.value.limitations.join("\n")).toContain(
|
||||
"verified against 3.1.0",
|
||||
);
|
||||
expect(result.value.normalized_result).toMatchObject({
|
||||
engine: { version: "3.1.2" },
|
||||
});
|
||||
await assertFirmwareCleanup(fixture.launches);
|
||||
});
|
||||
|
||||
it("names the accepted release line when the banner is another line", async () => {
|
||||
const fixture = await firmwareFixture("normal", "binwalk 3.2.0");
|
||||
const result = await fixture.service.execute("inspect_firmware_regions", {
|
||||
path: fixture.path,
|
||||
});
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisCapabilityUnavailableError",
|
||||
reason: expect.stringContaining("Binwalk 3.1.x"),
|
||||
},
|
||||
});
|
||||
await assertFirmwareCleanup(fixture.launches);
|
||||
});
|
||||
|
||||
it("rejects absent or unsupported engines without installing anything", async () => {
|
||||
const missing = await new FirmwareAnalysisService(
|
||||
new FirmwareProvider({}),
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { readFile, rm } from "node:fs/promises";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { join, resolve } from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
@@ -11,15 +11,7 @@ import {
|
||||
} from "../../../src/mcpDoctor.js";
|
||||
import { CATALOG_IDENTITY } from "../../../src/catalogIdentity.js";
|
||||
|
||||
const temporary: string[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
temporary
|
||||
.splice(0)
|
||||
.map((path) => rm(path, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
describe("production MCP doctor", () => {
|
||||
it("connects to the production stdio child and verifies the canonical catalog", async () => {
|
||||
@@ -78,17 +70,30 @@ describe("production MCP doctor", () => {
|
||||
|
||||
it("kills a child that misses the absolute startup deadline", async () => {
|
||||
const root = await createTestTempDirectory("rea-mcp-doctor-");
|
||||
temporary.push(root);
|
||||
const pidPath = join(root, "pid");
|
||||
const result = await runProductionMcpDoctor({
|
||||
// Keep filesystem/process I/O real. Advance only the deadline timers,
|
||||
// after the fixture proves it started and published its PID.
|
||||
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
|
||||
const pending = runProductionMcpDoctor({
|
||||
command: process.execPath,
|
||||
args: [resolve("tests/fixtures/mcpDoctorHang.mjs")],
|
||||
cwd: process.cwd(),
|
||||
environment: { ...process.env, REA_MCP_DOCTOR_PID_PATH: pidPath },
|
||||
deadlineMs: 250,
|
||||
deadlineMs: 60_000,
|
||||
});
|
||||
const pid = await vi.waitFor(
|
||||
async () => {
|
||||
const value = Number.parseInt(await readFile(pidPath, "utf8"), 10);
|
||||
expect(Number.isSafeInteger(value) && value > 0).toBe(true);
|
||||
return value;
|
||||
},
|
||||
{ timeout: 10_000 },
|
||||
);
|
||||
await vi.advanceTimersByTimeAsync(60_000);
|
||||
const result = await vi.waitFor(() => pending, { timeout: 10_000 });
|
||||
vi.useRealTimers();
|
||||
expect(result.healthy).toBe(false);
|
||||
const pid = Number.parseInt(await readFile(pidPath, "utf8"), 10);
|
||||
expect(result.checks[0]?.detail).toMatch(/deadline|abort|timed/iu);
|
||||
await expect(waitForExit(pid)).resolves.toBeUndefined();
|
||||
}, 10_000);
|
||||
});
|
||||
@@ -98,11 +103,7 @@ const waitForExit = async (pid: number): Promise<void> => {
|
||||
try {
|
||||
process.kill(pid, 0);
|
||||
} catch (cause: unknown) {
|
||||
if (
|
||||
cause instanceof Error &&
|
||||
"code" in cause &&
|
||||
(cause as NodeJS.ErrnoException).code === "ESRCH"
|
||||
)
|
||||
if (cause instanceof Error && "code" in cause && cause.code === "ESRCH")
|
||||
return;
|
||||
throw cause;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { auxiliaryAnalysisProviderDeclarations } from "../../../src/composition/auxiliaryAnalysisProviders.js";
|
||||
import { LazyAnalysisProvider } from "../../../src/application/LazyAnalysisProvider.js";
|
||||
import { parseBinaryTarget } from "../../../src/application/BinaryTargetResolver.js";
|
||||
import { GENERATED_AUXILIARY_PROVIDERS } from "../../../src/generatedMcpToolCatalog.js";
|
||||
|
||||
it.each(["darwin", "linux", "win32"] as const)(
|
||||
"preserves canonical auxiliary metadata and host facts on %s",
|
||||
async (platform) => {
|
||||
const declarations = auxiliaryAnalysisProviderDeclarations(platform);
|
||||
expect(declarations.map(({ identity }) => identity)).toEqual(
|
||||
GENERATED_AUXILIARY_PROVIDERS.map(({ identity }) => identity),
|
||||
);
|
||||
const operations = new Set<string>();
|
||||
for (const declaration of declarations) {
|
||||
const canonical = GENERATED_AUXILIARY_PROVIDERS.find(
|
||||
({ identity }) => identity.id === declaration.identity.id,
|
||||
);
|
||||
if (canonical === undefined)
|
||||
throw new Error("Missing canonical provider");
|
||||
const expected = canonical.capabilities.map((capability) => {
|
||||
if (platform === "darwin") return capability;
|
||||
if (capability.provider.id === "native-macos")
|
||||
return {
|
||||
...capability,
|
||||
available: false,
|
||||
availabilityCode: "unsupported_host",
|
||||
reason: "Native macOS utilities require macOS.",
|
||||
};
|
||||
if (capability.operation === "inspect_asset_catalog")
|
||||
return {
|
||||
...capability,
|
||||
available: false,
|
||||
availabilityCode: "unsupported_host",
|
||||
reason: "Apple asset catalogs require macOS assetutil.",
|
||||
};
|
||||
return capability;
|
||||
});
|
||||
expect(declaration.capabilities).toEqual(expected);
|
||||
const first = await declaration.load();
|
||||
const second = await declaration.load();
|
||||
expect(first).not.toBe(second);
|
||||
expect(first.identity()).toEqual(declaration.identity);
|
||||
expect(first.capabilities()).toEqual(declaration.capabilities);
|
||||
expect(second.capabilities()).toEqual(declaration.capabilities);
|
||||
for (const capability of declaration.capabilities) {
|
||||
expect(operations.has(capability.operation)).toBe(false);
|
||||
operations.add(capability.operation);
|
||||
expect(Object.isFrozen(capability)).toBe(true);
|
||||
expect(Object.isFrozen(capability.effects)).toBe(true);
|
||||
expect(Object.isFrozen(capability.limitations)).toBe(true);
|
||||
}
|
||||
}
|
||||
expect(operations.has("inspect_native_dispatch_metadata")).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps declaration discovery and client creation lazy and independently owned", async () => {
|
||||
const target = await parseBinaryTarget(process.execPath);
|
||||
if (!target.ok) throw target.error;
|
||||
for (const declaration of auxiliaryAnalysisProviderDeclarations()) {
|
||||
let loads = 0;
|
||||
const provider = new LazyAnalysisProvider({
|
||||
...declaration,
|
||||
load: async () => {
|
||||
loads += 1;
|
||||
return declaration.load();
|
||||
},
|
||||
});
|
||||
expect(provider.identity()).toEqual(declaration.identity);
|
||||
expect(provider.capabilities()).toEqual(declaration.capabilities);
|
||||
const client = provider.createClient(target.value);
|
||||
const unusedClient = provider.createClient(target.value);
|
||||
await unusedClient.close();
|
||||
expect(loads).toBe(0);
|
||||
try {
|
||||
expect(await client.execute("health", {})).toMatchObject({
|
||||
ok: true,
|
||||
value: { provider: declaration.identity },
|
||||
});
|
||||
expect(loads).toBe(1);
|
||||
expect(await client.execute("health", {})).toMatchObject({ ok: true });
|
||||
expect(loads).toBe(1);
|
||||
} finally {
|
||||
await client.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -5,7 +5,7 @@ import { access, mkdir } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import pino from "pino";
|
||||
import type { Logger } from "../../../../src/logger.js";
|
||||
|
||||
@@ -20,6 +20,7 @@ import type {
|
||||
} from "../../../../src/ghidra/GhidraLauncher.js";
|
||||
import type { GhidraTransportKind } from "../../../../src/ghidra/GhidraTransport.js";
|
||||
import { GHIDRA_SESSION_CAPABILITIES } from "../../../../src/ghidra/GhidraSessionValues.js";
|
||||
import { waitForExit as waitForChildExit } from "../../../support/process/processFixture.js";
|
||||
|
||||
const fixturePath = fileURLToPath(
|
||||
new URL("../../../fixtures/fakeGhidra.mjs", import.meta.url),
|
||||
@@ -50,10 +51,15 @@ type FixtureMode =
|
||||
| "exit";
|
||||
|
||||
class FixtureLauncher implements GhidraLauncher {
|
||||
#notifyStarted: ((child: ChildProcess) => void) | undefined;
|
||||
readonly started = new Promise<ChildProcess>((resolve) => {
|
||||
this.#notifyStarted = resolve;
|
||||
});
|
||||
readonly runtimeRoots: string[] = [];
|
||||
readonly endpointPaths: string[] = [];
|
||||
readonly tokens: string[] = [];
|
||||
readonly processes: ChildProcess[] = [];
|
||||
readonly requests: string[] = [];
|
||||
|
||||
constructor(readonly mode: FixtureMode = "success") {}
|
||||
|
||||
@@ -64,7 +70,7 @@ class FixtureLauncher implements GhidraLauncher {
|
||||
const projectRoot = join(session.runtimeRoot, "project");
|
||||
await mkdir(projectRoot, { recursive: true });
|
||||
const process_ = spawn(process.execPath, [fixturePath], {
|
||||
stdio: ["ignore", "pipe", "pipe"],
|
||||
stdio: ["ignore", "pipe", "pipe", "ipc"],
|
||||
env: {
|
||||
...process.env,
|
||||
REA_GHIDRA_FIXTURE_CONFIG: JSON.stringify({
|
||||
@@ -79,7 +85,17 @@ class FixtureLauncher implements GhidraLauncher {
|
||||
}),
|
||||
},
|
||||
});
|
||||
process_.on("message", (value: unknown) => {
|
||||
if (
|
||||
typeof value === "object" &&
|
||||
value !== null &&
|
||||
"method" in value &&
|
||||
typeof value.method === "string"
|
||||
)
|
||||
this.requests.push(value.method);
|
||||
});
|
||||
this.processes.push(process_);
|
||||
process_.once("spawn", () => this.#notifyStarted?.(process_));
|
||||
return ok({
|
||||
process: process_,
|
||||
ownsProcessLifetime: true,
|
||||
@@ -120,6 +136,7 @@ const clientFor = (
|
||||
};
|
||||
|
||||
afterEach(async () => {
|
||||
vi.useRealTimers();
|
||||
await Promise.all(clients.splice(0).map((client) => client.close()));
|
||||
});
|
||||
|
||||
@@ -246,10 +263,15 @@ describe("GhidraClient", () => {
|
||||
|
||||
describe("GhidraClient startup lifecycle", () => {
|
||||
it("applies one startup deadline and removes the private runtime", async () => {
|
||||
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "Date"] });
|
||||
const launcher = new FixtureLauncher("silent");
|
||||
const client = clientFor(launcher, { startupTimeoutMs: 30 });
|
||||
|
||||
const result = await client.start();
|
||||
const pending = client.start();
|
||||
const child = await launcher.started;
|
||||
await vi.advanceTimersByTimeAsync(30);
|
||||
const result = await vi.waitFor(() => pending, { timeout: 10_000 });
|
||||
vi.useRealTimers();
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
@@ -259,7 +281,7 @@ describe("GhidraClient startup lifecycle", () => {
|
||||
code: "ENOENT",
|
||||
});
|
||||
await client.close();
|
||||
await expect(waitForExit(launcher.processes[0])).resolves.toBe(true);
|
||||
await expect(waitForExit(child)).resolves.toBe(true);
|
||||
});
|
||||
|
||||
it("cancels startup promptly and leaves no project or process", async () => {
|
||||
@@ -267,7 +289,8 @@ describe("GhidraClient startup lifecycle", () => {
|
||||
const client = clientFor(launcher, { startupTimeoutMs: 10_000 });
|
||||
const controller = new AbortController();
|
||||
const pending = client.start(controller.signal);
|
||||
setTimeout(() => controller.abort(), 10);
|
||||
const process_ = await launcher.started;
|
||||
controller.abort();
|
||||
|
||||
const result = await pending;
|
||||
|
||||
@@ -276,9 +299,7 @@ describe("GhidraClient startup lifecycle", () => {
|
||||
code: "ENOENT",
|
||||
});
|
||||
await client.close();
|
||||
const process_ = launcher.processes[0];
|
||||
if (process_ !== undefined)
|
||||
await expect(waitForExit(process_)).resolves.toBe(true);
|
||||
await expect(waitForExit(process_)).resolves.toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -305,7 +326,9 @@ describe("GhidraClient established requests", () => {
|
||||
{ document: null, procedure: "fixture_main" },
|
||||
{ signal: activeController.signal },
|
||||
);
|
||||
await wait(5);
|
||||
await vi.waitFor(() =>
|
||||
expect(launcher.requests).toContain("procedure_pseudo_code"),
|
||||
);
|
||||
const queuedController = new AbortController();
|
||||
const queued = client.callTool(
|
||||
"procedure_info",
|
||||
@@ -322,7 +345,7 @@ describe("GhidraClient established requests", () => {
|
||||
document: null,
|
||||
procedure: "fixture_main",
|
||||
});
|
||||
await wait(5);
|
||||
expect(launcher.requests).not.toContain("procedure_info");
|
||||
const process_ = launcher.processes[0];
|
||||
activeController.abort();
|
||||
await expect(active).resolves.toMatchObject({
|
||||
@@ -404,15 +427,9 @@ const exited = (process_: ChildProcess | undefined): boolean =>
|
||||
const waitForExit = async (
|
||||
process_: ChildProcess | undefined,
|
||||
): Promise<boolean> => {
|
||||
for (let attempt = 0; attempt < 1_000 && !exited(process_); attempt += 1) {
|
||||
await wait(10);
|
||||
}
|
||||
return exited(process_);
|
||||
return process_ !== undefined && waitForChildExit(process_, 10_000);
|
||||
};
|
||||
|
||||
const wait = (milliseconds: number): Promise<void> =>
|
||||
new Promise((resolve) => setTimeout(resolve, milliseconds));
|
||||
|
||||
describe("GhidraClient rejected requests", () => {
|
||||
it("redacts authentication after failed startup cleanup and retry", async () => {
|
||||
const fixture = new FixtureLauncher();
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { access, chmod, readFile, rm, stat } from "node:fs/promises";
|
||||
import { access, chmod, readFile, stat } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { afterEach, beforeAll, describe, expect, it, vi } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { createTestTempDirectory } from "../../../fixtures/temporaryDirectory.js";
|
||||
import { createGhidraTestRuntime } from "../../../fixtures/ghidraRuntime.js";
|
||||
@@ -22,9 +23,26 @@ const fixturePath = fileURLToPath(
|
||||
import.meta.url,
|
||||
),
|
||||
);
|
||||
const roots: string[] = [];
|
||||
const runtimes: PrivateRuntimeRoot[] = [];
|
||||
|
||||
const launchCaptureSchema = z.object({
|
||||
arguments: z.array(z.string()),
|
||||
environment: z.record(z.string(), z.string()),
|
||||
descriptor_mode: z.number().int(),
|
||||
descriptor_has_token: z.boolean(),
|
||||
});
|
||||
|
||||
const expectOptions = (
|
||||
arguments_: readonly string[],
|
||||
options: readonly (readonly [string, string])[],
|
||||
): void => {
|
||||
for (const [flag, value] of options) {
|
||||
const index = arguments_.indexOf(flag);
|
||||
expect(index, flag).toBeGreaterThanOrEqual(0);
|
||||
expect(arguments_[index + 1], flag).toBe(value);
|
||||
}
|
||||
};
|
||||
|
||||
const expectIsolatedEnvironment = (
|
||||
environment: Record<string, string>,
|
||||
runtimeRoot: string,
|
||||
@@ -68,9 +86,6 @@ beforeAll(async () => {
|
||||
afterEach(async () => {
|
||||
vi.unstubAllEnvs();
|
||||
await Promise.all(runtimes.splice(0).map((runtime) => runtime.close()));
|
||||
await Promise.all(
|
||||
roots.splice(0).map((path) => rm(path, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
describe("Ghidra COM loader", () => {
|
||||
@@ -84,15 +99,11 @@ describe("Ghidra COM loader", () => {
|
||||
scriptLogPath: "/tmp/script.log",
|
||||
dosCom: true,
|
||||
});
|
||||
expect(arguments_.slice(4, 12)).toEqual([
|
||||
"-loader",
|
||||
"BinaryLoader",
|
||||
"-loader-baseAddr",
|
||||
"1000:0100",
|
||||
"-processor",
|
||||
"x86:LE:16:Real Mode",
|
||||
"-cspec",
|
||||
"default",
|
||||
expectOptions(arguments_, [
|
||||
["-loader", "BinaryLoader"],
|
||||
["-loader-baseAddr", "1000:0100"],
|
||||
["-processor", "x86:LE:16:Real Mode"],
|
||||
["-cspec", "default"],
|
||||
]);
|
||||
const prepare = arguments_.indexOf("-preScript");
|
||||
expect(arguments_[prepare + 1]).toBe(
|
||||
@@ -115,44 +126,36 @@ describe("Ghidra headless launcher", () => {
|
||||
scriptLogPath: "/tmp/script.log",
|
||||
dosMz: true,
|
||||
});
|
||||
expect(arguments_.slice(4, 10)).toEqual([
|
||||
"-loader",
|
||||
"MzLoader",
|
||||
"-processor",
|
||||
"x86:LE:16:Real Mode",
|
||||
"-cspec",
|
||||
"default",
|
||||
expectOptions(arguments_, [
|
||||
["-loader", "MzLoader"],
|
||||
["-processor", "x86:LE:16:Real Mode"],
|
||||
["-cspec", "default"],
|
||||
]);
|
||||
expect(arguments_).toContain("-readOnly");
|
||||
expect(arguments_).toContain("-deleteProject");
|
||||
});
|
||||
it("builds a read-only import in deterministic order", () => {
|
||||
expect(
|
||||
ghidraHeadlessArguments({
|
||||
projectRoot: "/tmp/project",
|
||||
targetPath: "/tmp/target",
|
||||
bridgeScriptPath: "/package/bridge/ReaGhidraBridge.java",
|
||||
descriptorPath: "/tmp/session.json",
|
||||
ghidraLogPath: "/tmp/ghidra.log",
|
||||
scriptLogPath: "/tmp/script.log",
|
||||
}),
|
||||
).toEqual([
|
||||
"/tmp/project",
|
||||
"rea-project",
|
||||
"-import",
|
||||
"/tmp/target",
|
||||
"-readOnly",
|
||||
"-deleteProject",
|
||||
"-log",
|
||||
"/tmp/ghidra.log",
|
||||
"-scriptlog",
|
||||
"/tmp/script.log",
|
||||
"-scriptPath",
|
||||
"/package/bridge",
|
||||
"-postScript",
|
||||
"/package/bridge/ReaGhidraBridge.java",
|
||||
"/tmp/session.json",
|
||||
it("builds a read-only ephemeral import with its bridge descriptor", () => {
|
||||
const arguments_ = ghidraHeadlessArguments({
|
||||
projectRoot: "/tmp/project",
|
||||
targetPath: "/tmp/target",
|
||||
bridgeScriptPath: "/package/bridge/ReaGhidraBridge.java",
|
||||
descriptorPath: "/tmp/session.json",
|
||||
ghidraLogPath: "/tmp/ghidra.log",
|
||||
scriptLogPath: "/tmp/script.log",
|
||||
});
|
||||
expect(arguments_.slice(0, 2)).toEqual(["/tmp/project", "rea-project"]);
|
||||
expectOptions(arguments_, [
|
||||
["-import", "/tmp/target"],
|
||||
["-log", "/tmp/ghidra.log"],
|
||||
["-scriptlog", "/tmp/script.log"],
|
||||
["-scriptPath", "/package/bridge"],
|
||||
["-postScript", "/package/bridge/ReaGhidraBridge.java"],
|
||||
]);
|
||||
expect(arguments_[arguments_.indexOf("-postScript") + 2]).toBe(
|
||||
"/tmp/session.json",
|
||||
);
|
||||
expect(arguments_).toContain("-readOnly");
|
||||
expect(arguments_).toContain("-deleteProject");
|
||||
});
|
||||
|
||||
it("wraps the Windows batch launcher without enabling a Node shell", () => {
|
||||
@@ -203,7 +206,6 @@ describe("Ghidra headless launcher", () => {
|
||||
vi.stubEnv("JDK_JAVA_OPTIONS", "-XX:MaxRAMPercentage=99");
|
||||
vi.stubEnv("_JAVA_OPTIONS", "-Xmx99G");
|
||||
const parent = await createTestTempDirectory("rea-launcher-test-");
|
||||
roots.push(parent);
|
||||
const runtime = await createGhidraTestRuntime(parent);
|
||||
runtimes.push(runtime);
|
||||
const runtimeRoot = runtime.path;
|
||||
@@ -229,8 +231,10 @@ describe("Ghidra headless launcher", () => {
|
||||
expect(launched.ok).toBe(true);
|
||||
if (!launched.ok) return;
|
||||
const capturePath = join(runtimeRoot, "launch-capture.json");
|
||||
await waitFor(capturePath);
|
||||
const capture = JSON.parse(await readFile(capturePath, "utf8"));
|
||||
await vi.waitFor(() => access(`${capturePath}.ready`), { timeout: 10_000 });
|
||||
const capture = launchCaptureSchema.parse(
|
||||
JSON.parse(await readFile(capturePath, "utf8")),
|
||||
);
|
||||
const encodedArguments = JSON.stringify(capture.arguments);
|
||||
const encodedEnvironment = JSON.stringify(capture.environment);
|
||||
expect(encodedArguments).not.toContain(token);
|
||||
@@ -255,15 +259,3 @@ describe("Ghidra headless launcher", () => {
|
||||
await expect(access(join(runtimeRoot, "project"))).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
const waitFor = async (path: string): Promise<void> => {
|
||||
for (let attempt = 0; attempt < 100; attempt += 1) {
|
||||
try {
|
||||
await access(path);
|
||||
return;
|
||||
} catch {
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
}
|
||||
}
|
||||
throw new Error(`Timed out waiting for ${path}`);
|
||||
};
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { access } from "node:fs/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
@@ -14,44 +13,11 @@ import { HopperClient } from "../../../../src/hopper/HopperClient.js";
|
||||
import { cleanupOwnedProcessGroup } from "../../../../src/process/ProcessOwnership.js";
|
||||
import { spawnOwnedProviderProcess } from "../../../../src/process/ProviderProcess.js";
|
||||
|
||||
const fixturePath = fileURLToPath(
|
||||
new URL("../../../fixtures/fakeHopper.mjs", import.meta.url),
|
||||
);
|
||||
|
||||
class FixtureLauncher implements BridgeLauncher {
|
||||
socketPaths: string[] = [];
|
||||
directories: string[] = [];
|
||||
runIds: string[] = [];
|
||||
processes: ChildProcess[] = [];
|
||||
|
||||
constructor(readonly tokenOverride?: string) {}
|
||||
|
||||
launch(session: BridgeSession) {
|
||||
this.socketPaths.push(session.socketPath);
|
||||
this.directories.push(session.directory);
|
||||
this.runIds.push(session.runId);
|
||||
const child = spawn(
|
||||
process.execPath,
|
||||
[
|
||||
fixturePath,
|
||||
session.socketPath,
|
||||
this.tokenOverride ?? session.token,
|
||||
session.runId,
|
||||
],
|
||||
{
|
||||
stdio: ["ignore", "ignore", "pipe"],
|
||||
},
|
||||
);
|
||||
this.processes.push(child);
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
process: child,
|
||||
ownsProcessLifetime: true,
|
||||
shutdownMode: "bridge-request" as const,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
import {
|
||||
HopperFixtureLauncher as FixtureLauncher,
|
||||
hopperFixturePath as fixturePath,
|
||||
startHopperFixtureClient as startClient,
|
||||
} from "./hopperClient.fixture.js";
|
||||
|
||||
class OwnedFixtureLauncher implements BridgeLauncher {
|
||||
ownership:
|
||||
@@ -131,18 +97,6 @@ class UnconfirmedOwnedFixtureLauncher implements BridgeLauncher {
|
||||
}
|
||||
|
||||
const clients: HopperClient[] = [];
|
||||
const startClient = async () => {
|
||||
const client = new HopperClient({
|
||||
launcher: new FixtureLauncher(),
|
||||
startupTimeoutMs: 1_000,
|
||||
});
|
||||
clients.push(client);
|
||||
await expect(client.start()).resolves.toEqual({
|
||||
ok: true,
|
||||
value: { name: "REA Hopper bridge", version: "1.0.0" },
|
||||
});
|
||||
return client;
|
||||
};
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(clients.splice(0).map((client) => client.close()));
|
||||
@@ -150,12 +104,15 @@ afterEach(async () => {
|
||||
|
||||
describe("HopperClient cleanup", () => {
|
||||
it("waits for an operation reply without a fixed request deadline", async () => {
|
||||
const client = await startClient();
|
||||
await expect(
|
||||
client.callTool("echo", { value: "waited", delay: 150 }),
|
||||
).resolves.toEqual({
|
||||
const launcher = new FixtureLauncher();
|
||||
const client = await startClient(launcher);
|
||||
const pending = client.callTool("echo", { value: "waited", gate: "reply" });
|
||||
const request = await launcher.waitForRequest("echo", "reply");
|
||||
expect(client.requestActivity()).toMatchObject({ operation: "echo" });
|
||||
await launcher.release(request);
|
||||
await expect(pending).resolves.toEqual({
|
||||
ok: true,
|
||||
value: { value: "waited", delay: 150 },
|
||||
value: { value: "waited", gate: "reply" },
|
||||
});
|
||||
});
|
||||
|
||||
@@ -170,6 +127,34 @@ describe("HopperClient cleanup", () => {
|
||||
await first;
|
||||
});
|
||||
|
||||
it("exits an IPC-backed fixture cleanly after cancelling active work", async () => {
|
||||
const launcher = new FixtureLauncher();
|
||||
const client = await startClient(launcher);
|
||||
const controller = new AbortController();
|
||||
const pending = client.callTool(
|
||||
"echo",
|
||||
{ gate: "cancel-and-close" },
|
||||
{
|
||||
signal: controller.signal,
|
||||
},
|
||||
);
|
||||
await launcher.waitForRequest("echo", "cancel-and-close");
|
||||
controller.abort();
|
||||
await expect(pending).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "HopperCancelledError" },
|
||||
});
|
||||
await client.close();
|
||||
const child = launcher.processes.at(-1);
|
||||
expect({
|
||||
exitCode: child?.exitCode,
|
||||
signalCode: child?.signalCode,
|
||||
}).toEqual({
|
||||
exitCode: 0,
|
||||
signalCode: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("reports unconfirmed unowned document cleanup as a typed close failure", async () => {
|
||||
const client = new HopperClient({
|
||||
launcher: new UnconfirmedFixtureLauncher(),
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { onTestFinished, vi } from "vitest";
|
||||
import { z } from "zod";
|
||||
|
||||
import { ok } from "../../../../src/domain/result.js";
|
||||
import type {
|
||||
BridgeLauncher,
|
||||
BridgeSession,
|
||||
} from "../../../../src/hopper/BridgeLauncher.js";
|
||||
import { HopperClient } from "../../../../src/hopper/HopperClient.js";
|
||||
|
||||
export const hopperFixturePath = fileURLToPath(
|
||||
new URL("../../../fixtures/fakeHopper.mjs", import.meta.url),
|
||||
);
|
||||
|
||||
const requestSchema = z.object({
|
||||
id: z.number().int(),
|
||||
method: z.string(),
|
||||
params: z.record(z.string(), z.unknown()).optional(),
|
||||
});
|
||||
type FixtureRequest = z.infer<typeof requestSchema>;
|
||||
|
||||
/** Real socket fixture with request acknowledgements and explicit response gates. */
|
||||
export class HopperFixtureLauncher implements BridgeLauncher {
|
||||
readonly socketPaths: string[] = [];
|
||||
readonly directories: string[] = [];
|
||||
readonly runIds: string[] = [];
|
||||
readonly processes: ChildProcess[] = [];
|
||||
readonly requests: FixtureRequest[] = [];
|
||||
|
||||
constructor(readonly tokenOverride?: string) {}
|
||||
|
||||
launch(session: BridgeSession) {
|
||||
this.socketPaths.push(session.socketPath);
|
||||
this.directories.push(session.directory);
|
||||
this.runIds.push(session.runId);
|
||||
const child = spawn(
|
||||
process.execPath,
|
||||
[
|
||||
hopperFixturePath,
|
||||
session.socketPath,
|
||||
this.tokenOverride ?? session.token,
|
||||
session.runId,
|
||||
],
|
||||
{ stdio: ["ignore", "ignore", "pipe", "ipc"] },
|
||||
);
|
||||
child.on("message", (value: unknown) => {
|
||||
const request = requestSchema.safeParse(value);
|
||||
if (request.success) this.requests.push(request.data);
|
||||
});
|
||||
this.processes.push(child);
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
process: child,
|
||||
ownsProcessLifetime: true as const,
|
||||
shutdownMode: "bridge-request" as const,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** Wait for acknowledgement that the fixture actually received a request. */
|
||||
waitForRequest(method: string, gate?: string): Promise<FixtureRequest> {
|
||||
return vi.waitFor(
|
||||
() => {
|
||||
const request = this.requests.find(
|
||||
(value) =>
|
||||
value.method === method &&
|
||||
(gate === undefined || value.params?.gate === gate),
|
||||
);
|
||||
if (request === undefined)
|
||||
throw new Error(`Waiting for Hopper fixture request ${method}`);
|
||||
return request;
|
||||
},
|
||||
{ timeout: 10_000 },
|
||||
);
|
||||
}
|
||||
|
||||
/** Release a response held by the fixture's gate parameter. */
|
||||
release(request: FixtureRequest): Promise<void> {
|
||||
const child = this.processes.at(-1);
|
||||
if (child === undefined) throw new Error("Hopper fixture was not launched");
|
||||
return new Promise((resolve, reject) => {
|
||||
child.send({ release: request.id }, (error) => {
|
||||
if (error !== null) reject(error);
|
||||
else resolve();
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Register owned client cleanup before any startup assertion can fail. */
|
||||
export const trackHopperClient = (client: HopperClient): HopperClient => {
|
||||
onTestFinished(() => client.close());
|
||||
return client;
|
||||
};
|
||||
|
||||
/** Start a real fixture session with test-scoped cleanup. */
|
||||
export const startHopperFixtureClient = async (
|
||||
launcher = new HopperFixtureLauncher(),
|
||||
): Promise<HopperClient> => {
|
||||
const client = trackHopperClient(
|
||||
new HopperClient({
|
||||
launcher,
|
||||
startupTimeoutMs: 10_000,
|
||||
}),
|
||||
);
|
||||
const started = await client.start();
|
||||
if (!started.ok) throw started.error;
|
||||
return client;
|
||||
};
|
||||
@@ -1,75 +1,14 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { ok } from "../../../../src/domain/result.js";
|
||||
import type {
|
||||
BridgeLauncher,
|
||||
BridgeSession,
|
||||
} from "../../../../src/hopper/BridgeLauncher.js";
|
||||
import { HopperClient } from "../../../../src/hopper/HopperClient.js";
|
||||
|
||||
const fixturePath = fileURLToPath(
|
||||
new URL("../../../fixtures/fakeHopper.mjs", import.meta.url),
|
||||
);
|
||||
|
||||
class FixtureLauncher implements BridgeLauncher {
|
||||
socketPaths: string[] = [];
|
||||
directories: string[] = [];
|
||||
runIds: string[] = [];
|
||||
processes: ChildProcess[] = [];
|
||||
|
||||
constructor(readonly tokenOverride?: string) {}
|
||||
|
||||
launch(session: BridgeSession) {
|
||||
this.socketPaths.push(session.socketPath);
|
||||
this.directories.push(session.directory);
|
||||
this.runIds.push(session.runId);
|
||||
const child = spawn(
|
||||
process.execPath,
|
||||
[
|
||||
fixturePath,
|
||||
session.socketPath,
|
||||
this.tokenOverride ?? session.token,
|
||||
session.runId,
|
||||
],
|
||||
{
|
||||
stdio: ["ignore", "ignore", "pipe"],
|
||||
},
|
||||
);
|
||||
this.processes.push(child);
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
process: child,
|
||||
ownsProcessLifetime: true as const,
|
||||
shutdownMode: "bridge-request" as const,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const clients: HopperClient[] = [];
|
||||
const startClient = async () => {
|
||||
const client = new HopperClient({
|
||||
launcher: new FixtureLauncher(),
|
||||
startupTimeoutMs: 1_000,
|
||||
});
|
||||
clients.push(client);
|
||||
await expect(client.start()).resolves.toEqual({
|
||||
ok: true,
|
||||
value: { name: "REA Hopper bridge", version: "1.0.0" },
|
||||
});
|
||||
return client;
|
||||
};
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(clients.splice(0).map((client) => client.close()));
|
||||
});
|
||||
import {
|
||||
HopperFixtureLauncher,
|
||||
startHopperFixtureClient as startClient,
|
||||
} from "./hopperClient.fixture.js";
|
||||
|
||||
describe("HopperClient progress", () => {
|
||||
it("forwards correlated Python progress before the terminal response", async () => {
|
||||
const client = await startClient();
|
||||
const launcher = new HopperFixtureLauncher();
|
||||
const client = await startClient(launcher);
|
||||
const updates: Array<{
|
||||
readonly phase: string;
|
||||
readonly completed: number;
|
||||
@@ -77,7 +16,7 @@ describe("HopperClient progress", () => {
|
||||
}> = [];
|
||||
const pending = client.callTool(
|
||||
"echo",
|
||||
{ value: "progress" },
|
||||
{ value: "progress", gate: "progress" },
|
||||
{
|
||||
progress: {
|
||||
report: (update) => {
|
||||
@@ -87,9 +26,20 @@ describe("HopperClient progress", () => {
|
||||
},
|
||||
},
|
||||
);
|
||||
const request = await launcher.waitForRequest("echo", "progress");
|
||||
await vi.waitFor(() =>
|
||||
expect(updates).toContainEqual(
|
||||
expect.objectContaining({ phase: "hopper_bridge", completed: 0 }),
|
||||
),
|
||||
);
|
||||
expect(updates.some(({ terminal }) => terminal === true)).toBe(false);
|
||||
await launcher.release(request);
|
||||
const result = await pending;
|
||||
|
||||
expect(result).toEqual({ ok: true, value: { value: "progress" } });
|
||||
expect(result).toEqual({
|
||||
ok: true,
|
||||
value: { value: "progress", gate: "progress" },
|
||||
});
|
||||
expect(updates).toEqual(
|
||||
expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
@@ -136,17 +86,22 @@ describe("HopperClient progress", () => {
|
||||
});
|
||||
|
||||
it("cancels and ignores late responses without corrupting the session", async () => {
|
||||
const client = await startClient();
|
||||
const launcher = new HopperFixtureLauncher();
|
||||
const client = await startClient(launcher);
|
||||
const controller = new AbortController();
|
||||
const pending = client.callTool("hang", {}, { signal: controller.signal });
|
||||
const pending = client.callTool(
|
||||
"echo",
|
||||
{ gate: "late-reply" },
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
const request = await launcher.waitForRequest("echo", "late-reply");
|
||||
controller.abort();
|
||||
const cancelled = await pending;
|
||||
expect(cancelled.ok).toBe(false);
|
||||
if (!cancelled.ok)
|
||||
expect(cancelled.error._tag).toBe("HopperCancelledError");
|
||||
|
||||
const waited = await client.callTool("echo", { delay: 30 });
|
||||
expect(waited).toMatchObject({ ok: true });
|
||||
await launcher.release(request);
|
||||
await expect(client.callTool("echo", { value: "alive" })).resolves.toEqual({
|
||||
ok: true,
|
||||
value: { value: "alive" },
|
||||
@@ -154,12 +109,13 @@ describe("HopperClient progress", () => {
|
||||
});
|
||||
|
||||
it("retains cancelled bridge activity until the reply releases the queue", async () => {
|
||||
const client = await startClient();
|
||||
const launcher = new HopperFixtureLauncher();
|
||||
const client = await startClient(launcher);
|
||||
const progress: string[] = [];
|
||||
const controller = new AbortController();
|
||||
const pending = client.callTool(
|
||||
"echo",
|
||||
{ delay: 60 },
|
||||
{ gate: "cancel-active" },
|
||||
{
|
||||
signal: controller.signal,
|
||||
progress: {
|
||||
@@ -170,7 +126,7 @@ describe("HopperClient progress", () => {
|
||||
},
|
||||
},
|
||||
);
|
||||
await new Promise((resolve) => setTimeout(resolve, 5));
|
||||
const request = await launcher.waitForRequest("echo", "cancel-active");
|
||||
controller.abort();
|
||||
const result = await pending;
|
||||
|
||||
@@ -187,8 +143,8 @@ describe("HopperClient progress", () => {
|
||||
expect.stringContaining("started on Hopper's serial bridge"),
|
||||
]),
|
||||
);
|
||||
await new Promise((resolve) => setTimeout(resolve, 70));
|
||||
expect(client.requestActivity()).toBeNull();
|
||||
await launcher.release(request);
|
||||
await vi.waitFor(() => expect(client.requestActivity()).toBeNull());
|
||||
await expect(client.callTool("echo", { alive: true })).resolves.toEqual({
|
||||
ok: true,
|
||||
value: { alive: true },
|
||||
|
||||
@@ -1,74 +1,14 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { describe, expect, it, onTestFinished, vi } from "vitest";
|
||||
|
||||
import { HOPPER_PROVIDER_TOOL_CONTRACTS } from "../../../../src/hopper/HopperProvider.js";
|
||||
import { ok } from "../../../../src/domain/result.js";
|
||||
import type {
|
||||
BridgeLauncher,
|
||||
BridgeSession,
|
||||
} from "../../../../src/hopper/BridgeLauncher.js";
|
||||
import { HopperClient } from "../../../../src/hopper/HopperClient.js";
|
||||
import type { HopperDiagnostic } from "../../../../src/hopper/HopperDiagnostics.js";
|
||||
import { providerCleanupFailure } from "../../../../src/hopper/HopperDiagnostics.js";
|
||||
|
||||
const fixturePath = fileURLToPath(
|
||||
new URL("../../../fixtures/fakeHopper.mjs", import.meta.url),
|
||||
);
|
||||
|
||||
class FixtureLauncher implements BridgeLauncher {
|
||||
socketPaths: string[] = [];
|
||||
directories: string[] = [];
|
||||
runIds: string[] = [];
|
||||
processes: ChildProcess[] = [];
|
||||
|
||||
constructor(readonly tokenOverride?: string) {}
|
||||
|
||||
launch(session: BridgeSession) {
|
||||
this.socketPaths.push(session.socketPath);
|
||||
this.directories.push(session.directory);
|
||||
this.runIds.push(session.runId);
|
||||
const child = spawn(
|
||||
process.execPath,
|
||||
[
|
||||
fixturePath,
|
||||
session.socketPath,
|
||||
this.tokenOverride ?? session.token,
|
||||
session.runId,
|
||||
],
|
||||
{
|
||||
stdio: ["ignore", "ignore", "pipe"],
|
||||
},
|
||||
);
|
||||
this.processes.push(child);
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
process: child,
|
||||
ownsProcessLifetime: true as const,
|
||||
shutdownMode: "bridge-request" as const,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const clients: HopperClient[] = [];
|
||||
const startClient = async () => {
|
||||
const client = new HopperClient({
|
||||
launcher: new FixtureLauncher(),
|
||||
startupTimeoutMs: 1_000,
|
||||
});
|
||||
clients.push(client);
|
||||
await expect(client.start()).resolves.toEqual({
|
||||
ok: true,
|
||||
value: { name: "REA Hopper bridge", version: "1.0.0" },
|
||||
});
|
||||
return client;
|
||||
};
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(clients.splice(0).map((client) => client.close()));
|
||||
});
|
||||
import {
|
||||
HopperFixtureLauncher as FixtureLauncher,
|
||||
startHopperFixtureClient as startClient,
|
||||
} from "./hopperClient.fixture.js";
|
||||
|
||||
describe("HopperClient protocol", () => {
|
||||
it("sanitizes unexpected owned-cleanup exceptions", () => {
|
||||
@@ -89,7 +29,7 @@ describe("HopperClient protocol", () => {
|
||||
runId: "11111111-1111-4111-8111-111111111111",
|
||||
startupTimeoutMs: 1_000,
|
||||
});
|
||||
clients.push(client);
|
||||
onTestFinished(() => client.close());
|
||||
|
||||
expect((await client.start()).ok).toBe(true);
|
||||
expect(launcher.runIds).toEqual(["11111111-1111-4111-8111-111111111111"]);
|
||||
@@ -98,25 +38,36 @@ describe("HopperClient protocol", () => {
|
||||
it("keeps the native socket path below macOS sockaddr_un limits", async () => {
|
||||
const launcher = new FixtureLauncher();
|
||||
const client = new HopperClient({ launcher, startupTimeoutMs: 1_000 });
|
||||
clients.push(client);
|
||||
onTestFinished(() => client.close());
|
||||
const started = await client.start();
|
||||
expect(started.ok).toBe(true);
|
||||
expect(Buffer.byteLength(launcher.socketPaths[0] ?? "")).toBeLessThan(104);
|
||||
});
|
||||
|
||||
it("serializes concurrent calls until the active Hopper reply arrives", async () => {
|
||||
const client = await startClient();
|
||||
const slow = client.callTool("echo", { label: "slow", delay: 30 });
|
||||
const fast = client.callTool("echo", { label: "fast", delay: 1 });
|
||||
const launcher = new FixtureLauncher();
|
||||
const client = await startClient(launcher);
|
||||
const slow = client.callTool("echo", { label: "slow", gate: "serial" });
|
||||
const request = await launcher.waitForRequest("echo", "serial");
|
||||
const fast = client.callTool("echo", { label: "fast" });
|
||||
let fastSettled = false;
|
||||
void fast.then(() => {
|
||||
fastSettled = true;
|
||||
});
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
await vi.waitFor(() =>
|
||||
expect(client.requestActivity()).toMatchObject({
|
||||
operation: "echo",
|
||||
queuedRequests: 1,
|
||||
}),
|
||||
);
|
||||
expect(fastSettled).toBe(false);
|
||||
expect(launcher.requests.filter(({ method }) => method === "echo")).toEqual(
|
||||
[request],
|
||||
);
|
||||
await launcher.release(request);
|
||||
await expect(Promise.all([slow, fast])).resolves.toEqual([
|
||||
{ ok: true, value: { label: "slow", delay: 30 } },
|
||||
{ ok: true, value: { label: "fast", delay: 1 } },
|
||||
{ ok: true, value: { label: "slow", gate: "serial" } },
|
||||
{ ok: true, value: { label: "fast" } },
|
||||
]);
|
||||
});
|
||||
|
||||
@@ -136,7 +87,7 @@ describe("HopperClient protocol", () => {
|
||||
launcher: new FixtureLauncher("wrong-token"),
|
||||
startupTimeoutMs: 1_000,
|
||||
});
|
||||
clients.push(client);
|
||||
onTestFinished(() => client.close());
|
||||
const result = await client.start();
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error._tag).toBe("HopperRemoteError");
|
||||
@@ -150,24 +101,40 @@ describe("HopperClient protocol", () => {
|
||||
["remote_error", "HopperRemoteError"],
|
||||
["exit", "HopperProcessError"],
|
||||
])("projects %s as %s", async (method, expectedTag) => {
|
||||
const client = await startClient();
|
||||
const launcher = new FixtureLauncher();
|
||||
const client = await startClient(launcher);
|
||||
const result = await client.callTool(method);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.error._tag).toBe(expectedTag);
|
||||
if (result.error._tag === "HopperRemoteError")
|
||||
expect(result.error).toMatchObject({ operation: method, requestId: 2 });
|
||||
expect(result.error).toMatchObject({
|
||||
operation: method,
|
||||
requestId: (await launcher.waitForRequest(method)).id,
|
||||
});
|
||||
}
|
||||
if (expectedTag === "HopperProtocolError") {
|
||||
await client.close();
|
||||
const child = launcher.processes.at(-1);
|
||||
expect({
|
||||
exitCode: child?.exitCode,
|
||||
signalCode: child?.signalCode,
|
||||
}).toEqual({
|
||||
exitCode: 0,
|
||||
signalCode: null,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves a sanitized bridge exception diagnostic", async () => {
|
||||
const launcher = new FixtureLauncher();
|
||||
const diagnostics: HopperDiagnostic[] = [];
|
||||
const client = new HopperClient({
|
||||
launcher: new FixtureLauncher(),
|
||||
launcher,
|
||||
startupTimeoutMs: 1_000,
|
||||
onDiagnostic: (event) => diagnostics.push(event),
|
||||
});
|
||||
clients.push(client);
|
||||
onTestFinished(() => client.close());
|
||||
await expect(client.start()).resolves.toMatchObject({ ok: true });
|
||||
const result = await client.callTool("remote_error");
|
||||
expect(result.ok).toBe(false);
|
||||
@@ -178,7 +145,7 @@ describe("HopperClient protocol", () => {
|
||||
});
|
||||
expect(diagnostics).toContainEqual({
|
||||
type: "bridge-diagnostic",
|
||||
request_id: 2,
|
||||
request_id: (await launcher.waitForRequest("remote_error")).id,
|
||||
code: -32001,
|
||||
category: "bridge_exception",
|
||||
message: "safe fake failure",
|
||||
|
||||
@@ -1,71 +1,10 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { ok } from "../../../../src/domain/result.js";
|
||||
import type {
|
||||
BridgeLauncher,
|
||||
BridgeSession,
|
||||
} from "../../../../src/hopper/BridgeLauncher.js";
|
||||
import { describe, expect, it, onTestFinished } from "vitest";
|
||||
import { HopperClient } from "../../../../src/hopper/HopperClient.js";
|
||||
|
||||
const fixturePath = fileURLToPath(
|
||||
new URL("../../../fixtures/fakeHopper.mjs", import.meta.url),
|
||||
);
|
||||
|
||||
class FixtureLauncher implements BridgeLauncher {
|
||||
socketPaths: string[] = [];
|
||||
directories: string[] = [];
|
||||
runIds: string[] = [];
|
||||
processes: ChildProcess[] = [];
|
||||
|
||||
constructor(readonly tokenOverride?: string) {}
|
||||
|
||||
launch(session: BridgeSession) {
|
||||
this.socketPaths.push(session.socketPath);
|
||||
this.directories.push(session.directory);
|
||||
this.runIds.push(session.runId);
|
||||
const child = spawn(
|
||||
process.execPath,
|
||||
[
|
||||
fixturePath,
|
||||
session.socketPath,
|
||||
this.tokenOverride ?? session.token,
|
||||
session.runId,
|
||||
],
|
||||
{
|
||||
stdio: ["ignore", "ignore", "pipe"],
|
||||
},
|
||||
);
|
||||
this.processes.push(child);
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
process: child,
|
||||
ownsProcessLifetime: true as const,
|
||||
shutdownMode: "bridge-request" as const,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
const clients: HopperClient[] = [];
|
||||
const startClient = async () => {
|
||||
const client = new HopperClient({
|
||||
launcher: new FixtureLauncher(),
|
||||
startupTimeoutMs: 1_000,
|
||||
});
|
||||
clients.push(client);
|
||||
await expect(client.start()).resolves.toEqual({
|
||||
ok: true,
|
||||
value: { name: "REA Hopper bridge", version: "1.0.0" },
|
||||
});
|
||||
return client;
|
||||
};
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(clients.splice(0).map((client) => client.close()));
|
||||
});
|
||||
import {
|
||||
HopperFixtureLauncher as FixtureLauncher,
|
||||
startHopperFixtureClient as startClient,
|
||||
} from "./hopperClient.fixture.js";
|
||||
|
||||
describe("HopperClient restart", () => {
|
||||
it("does not finish startup after an immediate close", async () => {
|
||||
@@ -73,7 +12,7 @@ describe("HopperClient restart", () => {
|
||||
launcher: new FixtureLauncher(),
|
||||
startupTimeoutMs: 1_000,
|
||||
});
|
||||
clients.push(client);
|
||||
onTestFinished(() => client.close());
|
||||
|
||||
const starting = client.start();
|
||||
await client.close();
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { access } from "node:fs/promises";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
@@ -14,44 +13,7 @@ import type {
|
||||
import { HopperClient } from "../../../../src/hopper/HopperClient.js";
|
||||
import { LINUX_PRIVATE_DISPLAY_DIAGNOSTIC_PREFIX } from "../../../../src/hopper/LinuxPrivateDisplayDiagnostic.js";
|
||||
|
||||
const fixturePath = fileURLToPath(
|
||||
new URL("../../../fixtures/fakeHopper.mjs", import.meta.url),
|
||||
);
|
||||
|
||||
class FixtureLauncher implements BridgeLauncher {
|
||||
socketPaths: string[] = [];
|
||||
directories: string[] = [];
|
||||
runIds: string[] = [];
|
||||
processes: ChildProcess[] = [];
|
||||
|
||||
constructor(readonly tokenOverride?: string) {}
|
||||
|
||||
launch(session: BridgeSession) {
|
||||
this.socketPaths.push(session.socketPath);
|
||||
this.directories.push(session.directory);
|
||||
this.runIds.push(session.runId);
|
||||
const child = spawn(
|
||||
process.execPath,
|
||||
[
|
||||
fixturePath,
|
||||
session.socketPath,
|
||||
this.tokenOverride ?? session.token,
|
||||
session.runId,
|
||||
],
|
||||
{
|
||||
stdio: ["ignore", "ignore", "pipe"],
|
||||
},
|
||||
);
|
||||
this.processes.push(child);
|
||||
return Promise.resolve(
|
||||
ok({
|
||||
process: child,
|
||||
ownsProcessLifetime: true as const,
|
||||
shutdownMode: "bridge-request" as const,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
import { HopperFixtureLauncher as FixtureLauncher } from "./hopperClient.fixture.js";
|
||||
|
||||
class SilentLauncher implements BridgeLauncher {
|
||||
launch() {
|
||||
@@ -175,12 +137,10 @@ describe("HopperClient startup failures", () => {
|
||||
// Cancel after launch: a timer can fire during runtime-directory creation,
|
||||
// leaving the silent first launch to be consumed by the retry instead.
|
||||
const firstProcess = await launcher.firstLaunch;
|
||||
const startedAt = Date.now();
|
||||
controller.abort();
|
||||
const result = await pending;
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error._tag).toBe("HopperCancelledError");
|
||||
expect(Date.now() - startedAt).toBeLessThan(500);
|
||||
expect(
|
||||
firstProcess.exitCode !== null || firstProcess.signalCode !== null,
|
||||
).toBe(true);
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user